blob: 2baa087c488ffd66d087443893e39db544e00961 [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
adlr@google.com3defe6a2009-12-04 20:57:17 +000016
17#include "update_engine/utils.h"
Darin Petkovf74eb652010-08-04 12:08:38 -070018
Ben Chan9abb7632014-08-07 00:10:53 -070019#include <stdint.h>
20
adlr@google.com3defe6a2009-12-04 20:57:17 +000021#include <dirent.h>
Alex Deymoc1711e22014-08-08 13:16:23 -070022#include <elf.h>
Alex Deymo6f20dd42015-08-18 16:42:46 -070023#include <endian.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000024#include <errno.h>
Alex Deymo192393b2014-11-10 15:58:38 -080025#include <ext2fs/ext2fs.h>
Andrew de los Reyes970bb282009-12-09 16:34:04 -080026#include <fcntl.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000027#include <stdio.h>
28#include <stdlib.h>
29#include <string.h>
Alex Deymoc4acdf42014-05-28 21:07:10 -070030#include <sys/mount.h>
31#include <sys/resource.h>
32#include <sys/stat.h>
33#include <sys/types.h>
34#include <sys/wait.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000035#include <unistd.h>
Darin Petkovf74eb652010-08-04 12:08:38 -070036
adlr@google.com3defe6a2009-12-04 20:57:17 +000037#include <algorithm>
Alex Vakulenkod2779df2014-06-16 13:19:00 -070038#include <utility>
Chris Sosac1972482013-04-30 22:31:10 -070039#include <vector>
Darin Petkovf74eb652010-08-04 12:08:38 -070040
Alex Vakulenko4906c1c2014-08-21 13:17:44 -070041#include <base/callback.h>
Ben Chan736fcb52014-05-21 18:28:22 -070042#include <base/files/file_path.h>
Alex Deymo192393b2014-11-10 15:58:38 -080043#include <base/files/file_util.h>
Ben Chan736fcb52014-05-21 18:28:22 -070044#include <base/files/scoped_file.h>
Alex Deymoc00c98a2015-03-17 17:38:00 -070045#include <base/format_macros.h>
Alex Deymo60ca1a72015-06-18 18:19:15 -070046#include <base/location.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040047#include <base/logging.h>
Chris Sosafc661a12013-02-26 14:43:21 -080048#include <base/posix/eintr_wrapper.h>
Will Drewry8f71da82010-08-30 14:07:11 -050049#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070050#include <base/strings/string_number_conversions.h>
51#include <base/strings/string_split.h>
52#include <base/strings/string_util.h>
53#include <base/strings/stringprintf.h>
Alex Vakulenko981a9fb2015-02-09 12:51:24 -080054#include <chromeos/data_encoding.h>
Alex Deymo60ca1a72015-06-18 18:19:15 -070055#include <chromeos/message_loops/message_loop.h>
Will Drewry8f71da82010-08-30 14:07:11 -050056
David Zeuthen33bae492014-02-25 16:16:18 -080057#include "update_engine/clock_interface.h"
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070058#include "update_engine/constants.h"
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080059#include "update_engine/file_descriptor.h"
Andrew de los Reyes970bb282009-12-09 16:34:04 -080060#include "update_engine/file_writer.h"
Darin Petkov33d30642010-08-04 10:18:57 -070061#include "update_engine/omaha_request_params.h"
David Zeuthen33bae492014-02-25 16:16:18 -080062#include "update_engine/prefs_interface.h"
Darin Petkov296889c2010-07-23 16:20:54 -070063#include "update_engine/subprocess.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080064#include "update_engine/system_state.h"
65#include "update_engine/update_attempter.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000066
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070067using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080068using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000069using std::min;
Chris Sosac1972482013-04-30 22:31:10 -070070using std::pair;
adlr@google.com3defe6a2009-12-04 20:57:17 +000071using std::string;
72using std::vector;
73
74namespace chromeos_update_engine {
75
Ben Chan77a1eba2012-10-07 22:54:55 -070076namespace {
77
78// The following constants control how UnmountFilesystem should retry if
79// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
80// one second.
81const int kUnmountMaxNumOfRetries = 5;
82const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Alex Deymo032e7722014-03-25 17:53:56 -070083
84// Number of bytes to read from a file to attempt to detect its contents. Used
85// in GetFileFormat.
86const int kGetFileFormatMaxHeaderSize = 32;
87
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080088// Return true if |disk_name| is an MTD or a UBI device. Note that this test is
89// simply based on the name of the device.
90bool IsMtdDeviceName(const string& disk_name) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -070091 return base::StartsWithASCII(disk_name, "/dev/ubi", true) ||
92 base::StartsWithASCII(disk_name, "/dev/mtd", true);
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080093}
94
95// Return the device name for the corresponding partition on a NAND device.
96// WARNING: This function returns device names that are not mountable.
97string MakeNandPartitionName(int partition_num) {
98 switch (partition_num) {
99 case 2:
100 case 4:
101 case 6: {
102 return base::StringPrintf("/dev/mtd%d", partition_num);
103 }
104 default: {
105 return base::StringPrintf("/dev/ubi%d_0", partition_num);
106 }
107 }
108}
109
110// Return the device name for the corresponding partition on a NAND device that
111// may be mountable (but may not be writable).
112string MakeNandPartitionNameForMount(int partition_num) {
113 switch (partition_num) {
114 case 2:
115 case 4:
116 case 6: {
117 return base::StringPrintf("/dev/mtd%d", partition_num);
118 }
119 case 3:
120 case 5:
121 case 7: {
122 return base::StringPrintf("/dev/ubiblock%d_0", partition_num);
123 }
124 default: {
125 return base::StringPrintf("/dev/ubi%d_0", partition_num);
126 }
127 }
128}
129
Ben Chan77a1eba2012-10-07 22:54:55 -0700130} // namespace
131
adlr@google.com3defe6a2009-12-04 20:57:17 +0000132namespace utils {
133
Chris Sosa4f8ee272012-11-30 13:01:54 -0800134// Cgroup container is created in update-engine's upstart script located at
135// /etc/init/update-engine.conf.
136static const char kCGroupDir[] = "/sys/fs/cgroup/cpu/update-engine";
137
J. Richard Barnette63137e52013-10-28 10:57:29 -0700138string ParseECVersion(string input_line) {
Ben Chan736fcb52014-05-21 18:28:22 -0700139 base::TrimWhitespaceASCII(input_line, base::TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -0700140
Alex Vakulenko75039d72014-03-25 12:36:28 -0700141 // At this point we want to convert the format key=value pair from mosys to
Chris Sosac1972482013-04-30 22:31:10 -0700142 // a vector of key value pairs.
Ben Chanf9cb98c2014-09-21 18:31:30 -0700143 vector<pair<string, string>> kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -0700144 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Alex Deymo020600d2014-11-05 21:05:55 -0800145 for (const pair<string, string>& kv_pair : kv_pairs) {
Chris Sosac1972482013-04-30 22:31:10 -0700146 // Finally match against the fw_verion which may have quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800147 if (kv_pair.first == "fw_version") {
Chris Sosac1972482013-04-30 22:31:10 -0700148 string output;
149 // Trim any quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800150 base::TrimString(kv_pair.second, "\"", &output);
Chris Sosac1972482013-04-30 22:31:10 -0700151 return output;
152 }
153 }
154 }
155 LOG(ERROR) << "Unable to parse fwid from ec info.";
156 return "";
157}
158
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800159bool WriteFile(const char* path, const void* data, int data_len) {
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800160 DirectFileWriter writer;
161 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
162 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700163 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800164 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800165 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800166 return true;
167}
168
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700169bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700170 const char* c_buf = static_cast<const char*>(buf);
171 ssize_t bytes_written = 0;
172 while (bytes_written < static_cast<ssize_t>(count)) {
173 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
174 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
175 bytes_written += rc;
176 }
177 return true;
178}
179
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700180bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
181 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700182 size_t bytes_written = 0;
183 int num_attempts = 0;
184 while (bytes_written < count) {
185 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700186 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
187 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700188 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
189 if (rc < 0) {
190 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
191 << " bytes_written=" << bytes_written
192 << " count=" << count << " offset=" << offset;
193 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700194 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
195 bytes_written += rc;
196 }
197 return true;
198}
199
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800200bool WriteAll(FileDescriptorPtr fd, const void* buf, size_t count) {
201 const char* c_buf = static_cast<const char*>(buf);
202 ssize_t bytes_written = 0;
203 while (bytes_written < static_cast<ssize_t>(count)) {
204 ssize_t rc = fd->Write(c_buf + bytes_written, count - bytes_written);
205 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
206 bytes_written += rc;
207 }
208 return true;
209}
210
211bool PWriteAll(FileDescriptorPtr fd,
212 const void* buf,
213 size_t count,
214 off_t offset) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700215 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
216 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800217 return WriteAll(fd, buf, count);
218}
219
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700220bool PReadAll(int fd, void* buf, size_t count, off_t offset,
221 ssize_t* out_bytes_read) {
222 char* c_buf = static_cast<char*>(buf);
223 ssize_t bytes_read = 0;
224 while (bytes_read < static_cast<ssize_t>(count)) {
225 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
226 offset + bytes_read);
227 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
228 if (rc == 0) {
229 break;
230 }
231 bytes_read += rc;
232 }
233 *out_bytes_read = bytes_read;
234 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700235}
236
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800237bool PReadAll(FileDescriptorPtr fd, void* buf, size_t count, off_t offset,
238 ssize_t* out_bytes_read) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700239 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
240 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800241 char* c_buf = static_cast<char*>(buf);
242 ssize_t bytes_read = 0;
243 while (bytes_read < static_cast<ssize_t>(count)) {
244 ssize_t rc = fd->Read(c_buf + bytes_read, count - bytes_read);
245 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
246 if (rc == 0) {
247 break;
248 }
249 bytes_read += rc;
250 }
251 *out_bytes_read = bytes_read;
252 return true;
253}
254
Gilad Arnold19a45f02012-07-19 12:36:10 -0700255// Append |nbytes| of content from |buf| to the vector pointed to by either
256// |vec_p| or |str_p|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800257static void AppendBytes(const uint8_t* buf, size_t nbytes,
258 chromeos::Blob* vec_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700259 CHECK(buf);
260 CHECK(vec_p);
261 vec_p->insert(vec_p->end(), buf, buf + nbytes);
262}
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800263static void AppendBytes(const uint8_t* buf, size_t nbytes,
Alex Deymof329b932014-10-30 01:37:48 -0700264 string* str_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700265 CHECK(buf);
266 CHECK(str_p);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800267 str_p->append(buf, buf + nbytes);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700268}
269
270// Reads from an open file |fp|, appending the read content to the container
271// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200272// file's content, false otherwise. If |size| is not -1, reads up to |size|
273// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700274template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200275static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700276 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200277 CHECK(size == -1 || size >= 0);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800278 uint8_t buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200279 while (size == -1 || size > 0) {
280 off_t bytes_to_read = sizeof(buf);
281 if (size > 0 && bytes_to_read > size) {
282 bytes_to_read = size;
283 }
284 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
285 if (!nbytes) {
286 break;
287 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700288 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200289 if (size != -1) {
290 CHECK(size >= static_cast<off_t>(nbytes));
291 size -= nbytes;
292 }
293 }
294 if (ferror(fp)) {
295 return false;
296 }
297 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700298}
299
Darin Petkov8e447e02013-04-16 16:23:50 +0200300// Opens a file |path| for reading and appends its the contents to a container
301// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
302// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700303template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700304static bool ReadFileChunkAndAppend(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200305 off_t offset,
306 off_t size,
307 T* out_p) {
308 CHECK_GE(offset, 0);
309 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700310 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200311 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000312 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200313 if (offset) {
314 // Return success without appending any data if a chunk beyond the end of
315 // the file is requested.
316 if (offset >= FileSize(path)) {
317 return true;
318 }
319 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
320 }
321 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000322}
323
Alex Deymo10875d92014-11-10 21:52:57 -0800324// TODO(deymo): This is only used in unittest, but requires the private
325// Read<string>() defined here. Expose Read<string>() or move to base/ version.
326bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700327 FILE* fp = popen(cmd.c_str(), "r");
328 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000329 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200330 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700331 return (success && pclose(fp) >= 0);
332}
333
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800334bool ReadFile(const string& path, chromeos::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200335 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700336}
337
Darin Petkov8e447e02013-04-16 16:23:50 +0200338bool ReadFile(const string& path, string* out_p) {
339 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700340}
341
Darin Petkov8e447e02013-04-16 16:23:50 +0200342bool ReadFileChunk(const string& path, off_t offset, off_t size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800343 chromeos::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200344 return ReadFileChunkAndAppend(path, offset, size, out_p);
345}
346
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700347off_t BlockDevSize(int fd) {
348 uint64_t dev_size;
349 int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
350 if (rc == -1) {
351 dev_size = -1;
352 PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
353 }
354 return dev_size;
355}
356
357off_t BlockDevSize(const string& path) {
358 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
359 if (fd == -1) {
360 PLOG(ERROR) << "Error opening " << path;
361 return fd;
362 }
363
364 off_t dev_size = BlockDevSize(fd);
365 if (dev_size == -1)
366 PLOG(ERROR) << "Error getting block device size on " << path;
367
368 close(fd);
369 return dev_size;
370}
371
372off_t FileSize(int fd) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700373 struct stat stbuf;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700374 int rc = fstat(fd, &stbuf);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700375 CHECK_EQ(rc, 0);
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700376 if (rc < 0) {
377 PLOG(ERROR) << "Error stat-ing " << fd;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700378 return rc;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700379 }
380 if (S_ISREG(stbuf.st_mode))
381 return stbuf.st_size;
382 if (S_ISBLK(stbuf.st_mode))
383 return BlockDevSize(fd);
384 LOG(ERROR) << "Couldn't determine the type of " << fd;
385 return -1;
386}
387
388off_t FileSize(const string& path) {
389 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
390 if (fd == -1) {
391 PLOG(ERROR) << "Error opening " << path;
392 return fd;
393 }
394 off_t size = FileSize(fd);
395 if (size == -1)
396 PLOG(ERROR) << "Error getting file size of " << path;
397 close(fd);
398 return size;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700399}
400
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800401void HexDumpArray(const uint8_t* const arr, const size_t length) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000402 LOG(INFO) << "Logging array of length: " << length;
403 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700404 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000405 const unsigned int bytes_remaining = length - i;
406 const unsigned int bytes_per_this_line = min(bytes_per_line,
407 bytes_remaining);
408 char header[100];
409 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
410 TEST_AND_RETURN(r == 13);
411 string line = header;
412 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
413 char buf[20];
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800414 uint8_t c = arr[i + j];
adlr@google.com3defe6a2009-12-04 20:57:17 +0000415 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
416 TEST_AND_RETURN(r == 3);
417 line += buf;
418 }
419 LOG(INFO) << line;
420 }
421}
422
Alex Deymof329b932014-10-30 01:37:48 -0700423bool SplitPartitionName(const string& partition_name,
424 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800425 int* out_partition_num) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700426 if (!base::StartsWithASCII(partition_name, "/dev/", true)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800427 LOG(ERROR) << "Invalid partition device name: " << partition_name;
428 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700429 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800430
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700431 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
432 if (last_nondigit_pos == string::npos ||
433 (last_nondigit_pos + 1) == partition_name.size()) {
434 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800435 return false;
436 }
437
Alex Deymof329b932014-10-30 01:37:48 -0700438 size_t partition_name_len = string::npos;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700439 if (partition_name[last_nondigit_pos] == '_') {
440 // NAND block devices have weird naming which could be something
441 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
442 size_t prev_nondigit_pos =
443 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
444 if (prev_nondigit_pos == string::npos ||
445 (prev_nondigit_pos + 1) == last_nondigit_pos) {
446 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
447 return false;
448 }
449
450 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
451 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800452 }
453
454 if (out_disk_name) {
455 // Special case for MMC devices which have the following naming scheme:
456 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700457 size_t disk_name_len = last_nondigit_pos;
458 if (partition_name[last_nondigit_pos] != 'p' ||
459 last_nondigit_pos == 0 ||
460 !isdigit(partition_name[last_nondigit_pos - 1])) {
461 disk_name_len++;
462 }
463 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800464 }
465
466 if (out_partition_num) {
Alex Deymof329b932014-10-30 01:37:48 -0700467 string partition_str = partition_name.substr(last_nondigit_pos + 1,
468 partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800469 *out_partition_num = atoi(partition_str.c_str());
470 }
471 return true;
472}
473
Alex Deymof329b932014-10-30 01:37:48 -0700474string MakePartitionName(const string& disk_name, int partition_num) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800475 if (partition_num < 1) {
476 LOG(ERROR) << "Invalid partition number: " << partition_num;
477 return string();
478 }
479
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700480 if (!base::StartsWithASCII(disk_name, "/dev/", true)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800481 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700482 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800483 }
484
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800485 if (IsMtdDeviceName(disk_name)) {
486 // Special case for UBI block devices.
487 // 1. ubiblock is not writable, we need to use plain "ubi".
488 // 2. There is a "_0" suffix.
489 return MakeNandPartitionName(partition_num);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800490 }
491
Alex Deymof329b932014-10-30 01:37:48 -0700492 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700493 if (isdigit(partition_name.back())) {
494 // Special case for devices with names ending with a digit.
495 // Add "p" to separate the disk name from partition number,
496 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800497 partition_name += 'p';
498 }
499
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700500 partition_name += std::to_string(partition_num);
501
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800502 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700503}
504
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800505string MakePartitionNameForMount(const string& part_name) {
506 if (IsMtdDeviceName(part_name)) {
507 int partition_num;
508 if (!SplitPartitionName(part_name, nullptr, &partition_num)) {
509 return "";
510 }
511 return MakeNandPartitionNameForMount(partition_num);
512 }
513 return part_name;
514}
515
Alex Deymof329b932014-10-30 01:37:48 -0700516string ErrnoNumberAsString(int err) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000517 char buf[100];
518 buf[0] = '\0';
519 return strerror_r(err, buf, sizeof(buf));
520}
521
adlr@google.com3defe6a2009-12-04 20:57:17 +0000522bool FileExists(const char* path) {
523 struct stat stbuf;
524 return 0 == lstat(path, &stbuf);
525}
526
Darin Petkov30291ed2010-11-12 10:23:06 -0800527bool IsSymlink(const char* path) {
528 struct stat stbuf;
529 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
530}
531
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800532bool TryAttachingUbiVolume(int volume_num, int timeout) {
533 const string volume_path = base::StringPrintf("/dev/ubi%d_0", volume_num);
534 if (FileExists(volume_path.c_str())) {
535 return true;
536 }
537
538 int exit_code;
539 vector<string> cmd = {
540 "ubiattach",
541 "-m",
542 base::StringPrintf("%d", volume_num),
543 "-d",
544 base::StringPrintf("%d", volume_num)
545 };
546 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
547 TEST_AND_RETURN_FALSE(exit_code == 0);
548
549 cmd = {
550 "ubiblock",
551 "--create",
552 volume_path
553 };
554 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
555 TEST_AND_RETURN_FALSE(exit_code == 0);
556
557 while (timeout > 0 && !FileExists(volume_path.c_str())) {
558 sleep(1);
559 timeout--;
560 }
561
562 return FileExists(volume_path.c_str());
563}
564
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800565// If |path| is absolute, or explicit relative to the current working directory,
566// leaves it as is. Otherwise, if TMPDIR is defined in the environment and is
567// non-empty, prepends it to |path|. Otherwise, prepends /tmp. Returns the
568// resulting path.
569static const string PrependTmpdir(const string& path) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700570 if (path[0] == '/' || base::StartsWithASCII(path, "./", true) ||
571 base::StartsWithASCII(path, "../", true))
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800572 return path;
573
574 const char *tmpdir = getenv("TMPDIR");
575 const string prefix = (tmpdir && *tmpdir ? tmpdir : "/tmp");
576 return prefix + "/" + path;
577}
578
Alex Deymof329b932014-10-30 01:37:48 -0700579bool MakeTempFile(const string& base_filename_template,
580 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700581 int* fd) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800582 const string filename_template = PrependTmpdir(base_filename_template);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700583 DCHECK(filename || fd);
584 vector<char> buf(filename_template.size() + 1);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800585 memcpy(buf.data(), filename_template.data(), filename_template.size());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700586 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700587
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800588 int mkstemp_fd = mkstemp(buf.data());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700589 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
590 if (filename) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800591 *filename = buf.data();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700592 }
593 if (fd) {
594 *fd = mkstemp_fd;
595 } else {
596 close(mkstemp_fd);
597 }
598 return true;
599}
600
Alex Deymof329b932014-10-30 01:37:48 -0700601bool MakeTempDirectory(const string& base_dirname_template,
602 string* dirname) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800603 const string dirname_template = PrependTmpdir(base_dirname_template);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700604 DCHECK(dirname);
605 vector<char> buf(dirname_template.size() + 1);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800606 memcpy(buf.data(), dirname_template.data(), dirname_template.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700607 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700608
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800609 char* return_code = mkdtemp(buf.data());
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700610 TEST_AND_RETURN_FALSE_ERRNO(return_code != nullptr);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800611 *dirname = buf.data();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700612 return true;
613}
614
adlr@google.com3defe6a2009-12-04 20:57:17 +0000615bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700616 const string& mountpoint,
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700617 unsigned long mountflags) { // NOLINT(runtime/int)
Alex Deymo4c82df32014-11-10 22:25:57 -0800618 // TODO(sosa): Remove "ext3" once crbug.com/208022 is resolved.
619 const vector<const char*> fstypes{"ext2", "ext3", "squashfs"};
620 for (const char* fstype : fstypes) {
621 int rc = mount(device.c_str(), mountpoint.c_str(), fstype, mountflags,
622 nullptr);
623 if (rc == 0)
624 return true;
625
626 PLOG(WARNING) << "Unable to mount destination device " << device
627 << " on " << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000628 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800629 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
630 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000631}
632
633bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700634 for (int num_retries = 0; ; ++num_retries) {
635 if (umount(mountpoint.c_str()) == 0)
636 break;
637
638 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
639 num_retries < kUnmountMaxNumOfRetries);
Alex Deymo8d2bbe32015-06-23 16:28:59 -0700640 usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700641 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000642 return true;
643}
644
Alex Deymof329b932014-10-30 01:37:48 -0700645bool GetFilesystemSize(const string& device,
Darin Petkovd3f8c892010-10-12 21:38:45 -0700646 int* out_block_count,
647 int* out_block_size) {
648 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
Alex Deymoe7141c62014-10-17 14:03:01 -0700649 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700650 ScopedFdCloser fd_closer(&fd);
651 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
652}
653
654bool GetFilesystemSizeFromFD(int fd,
655 int* out_block_count,
656 int* out_block_size) {
657 TEST_AND_RETURN_FALSE(fd >= 0);
658
Alex Deymo192393b2014-11-10 15:58:38 -0800659 // Determine the filesystem size by directly reading the block count and
660 // block size information from the superblock. Supported FS are ext3 and
661 // squashfs.
662
663 // Read from the fd only once and detect in memory. The first 2 KiB is enough
664 // to read the ext2 superblock (located at offset 1024) and the squashfs
665 // superblock (located at offset 0).
666 const ssize_t kBufferSize = 2048;
667
668 uint8_t buffer[kBufferSize];
669 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, 0)) != kBufferSize) {
670 PLOG(ERROR) << "Unable to read the file system header:";
Darin Petkovd3f8c892010-10-12 21:38:45 -0700671 return false;
672 }
Alex Deymo192393b2014-11-10 15:58:38 -0800673
674 if (GetSquashfs4Size(buffer, kBufferSize, out_block_count, out_block_size))
675 return true;
676 if (GetExt3Size(buffer, kBufferSize, out_block_count, out_block_size))
677 return true;
678
679 LOG(ERROR) << "Unable to determine file system type.";
680 return false;
681}
682
683bool GetExt3Size(const uint8_t* buffer, size_t buffer_size,
684 int* out_block_count,
685 int* out_block_size) {
686 // See include/linux/ext2_fs.h for more details on the structure. We obtain
687 // ext2 constants from ext2fs/ext2fs.h header but we don't link with the
688 // library.
689 if (buffer_size < SUPERBLOCK_OFFSET + SUPERBLOCK_SIZE)
690 return false;
691
692 const uint8_t* superblock = buffer + SUPERBLOCK_OFFSET;
693
694 // ext3_fs.h: ext3_super_block.s_blocks_count
695 uint32_t block_count =
696 *reinterpret_cast<const uint32_t*>(superblock + 1 * sizeof(int32_t));
697
698 // ext3_fs.h: ext3_super_block.s_log_block_size
699 uint32_t log_block_size =
700 *reinterpret_cast<const uint32_t*>(superblock + 6 * sizeof(int32_t));
701
702 // ext3_fs.h: ext3_super_block.s_magic
703 uint16_t magic =
704 *reinterpret_cast<const uint16_t*>(superblock + 14 * sizeof(int32_t));
705
Darin Petkovd3f8c892010-10-12 21:38:45 -0700706 block_count = le32toh(block_count);
Alex Deymo192393b2014-11-10 15:58:38 -0800707 log_block_size = le32toh(log_block_size) + EXT2_MIN_BLOCK_LOG_SIZE;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700708 magic = le16toh(magic);
709
710 // Sanity check the parameters.
Alex Deymo192393b2014-11-10 15:58:38 -0800711 TEST_AND_RETURN_FALSE(magic == EXT2_SUPER_MAGIC);
712 TEST_AND_RETURN_FALSE(log_block_size >= EXT2_MIN_BLOCK_LOG_SIZE &&
713 log_block_size <= EXT2_MAX_BLOCK_LOG_SIZE);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700714 TEST_AND_RETURN_FALSE(block_count > 0);
715
Alex Deymo192393b2014-11-10 15:58:38 -0800716 if (out_block_count)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700717 *out_block_count = block_count;
Alex Deymo192393b2014-11-10 15:58:38 -0800718 if (out_block_size)
719 *out_block_size = 1 << log_block_size;
720 return true;
721}
722
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800723bool GetSquashfs4Size(const uint8_t* buffer, size_t buffer_size,
Alex Deymo192393b2014-11-10 15:58:38 -0800724 int* out_block_count,
725 int* out_block_size) {
726 // See fs/squashfs/squashfs_fs.h for format details. We only support
727 // Squashfs 4.x little endian.
728
729 // sizeof(struct squashfs_super_block)
730 const size_t kSquashfsSuperBlockSize = 96;
731 if (buffer_size < kSquashfsSuperBlockSize)
732 return false;
733
734 // Check magic, squashfs_fs.h: SQUASHFS_MAGIC
735 if (memcmp(buffer, "hsqs", 4) != 0)
736 return false; // Only little endian is supported.
737
738 // squashfs_fs.h: struct squashfs_super_block.s_major
739 uint16_t s_major = *reinterpret_cast<const uint16_t*>(
740 buffer + 5 * sizeof(uint32_t) + 4 * sizeof(uint16_t));
741
742 if (s_major != 4) {
743 LOG(ERROR) << "Found unsupported squashfs major version " << s_major;
744 return false;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700745 }
Alex Deymo192393b2014-11-10 15:58:38 -0800746
747 // squashfs_fs.h: struct squashfs_super_block.bytes_used
748 uint64_t bytes_used = *reinterpret_cast<const int64_t*>(
749 buffer + 5 * sizeof(uint32_t) + 6 * sizeof(uint16_t) + sizeof(uint64_t));
750
751 const int block_size = 4096;
752
753 // The squashfs' bytes_used doesn't need to be aligned with the block boundary
754 // so we round up to the nearest blocksize.
755 if (out_block_count)
756 *out_block_count = (bytes_used + block_size - 1) / block_size;
757 if (out_block_size)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700758 *out_block_size = block_size;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700759 return true;
760}
761
Alex Deymo60ca1a72015-06-18 18:19:15 -0700762bool IsExtFilesystem(const string& device) {
Alex Deymode942f32015-03-13 11:57:15 -0700763 chromeos::Blob header;
764 // The first 2 KiB is enough to read the ext2 superblock (located at offset
765 // 1024).
766 if (!ReadFileChunk(device, 0, 2048, &header))
767 return false;
768 return GetExt3Size(header.data(), header.size(), nullptr, nullptr);
769}
770
Alex Deymo60ca1a72015-06-18 18:19:15 -0700771bool IsSquashfsFilesystem(const string& device) {
Alex Deymode942f32015-03-13 11:57:15 -0700772 chromeos::Blob header;
773 // The first 96 is enough to read the squashfs superblock.
774 const ssize_t kSquashfsSuperBlockSize = 96;
775 if (!ReadFileChunk(device, 0, kSquashfsSuperBlockSize, &header))
776 return false;
777 return GetSquashfs4Size(header.data(), header.size(), nullptr, nullptr);
778}
779
Alex Deymo032e7722014-03-25 17:53:56 -0700780// Tries to parse the header of an ELF file to obtain a human-readable
781// description of it on the |output| string.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800782static bool GetFileFormatELF(const uint8_t* buffer, size_t size,
783 string* output) {
Alex Deymo032e7722014-03-25 17:53:56 -0700784 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700785 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700786 return false;
787 *output = "ELF";
788
789 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700790 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700791 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700792 switch (buffer[EI_CLASS]) {
793 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700794 *output += " 32-bit";
795 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700796 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700797 *output += " 64-bit";
798 break;
799 default:
800 *output += " ?-bit";
801 }
802
803 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700804 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700805 return true;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800806 uint8_t ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700807 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700808 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700809 *output += " little-endian";
810 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700811 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700812 *output += " big-endian";
813 break;
814 default:
815 *output += " ?-endian";
816 // Don't parse anything after the 0x10 offset if endianness is unknown.
817 return true;
818 }
819
Alex Deymoc1711e22014-08-08 13:16:23 -0700820 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
821 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
822 // and size is the same for both 32 and 64 bits.
823 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700824 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700825 uint16_t e_machine;
Alex Deymo032e7722014-03-25 17:53:56 -0700826 // Fix endianess regardless of the host endianess.
Alex Deymoc1711e22014-08-08 13:16:23 -0700827 if (ei_data == ELFDATA2LSB)
828 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700829 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700830 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700831
832 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700833 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700834 *output += " x86";
835 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700836 case EM_MIPS:
837 *output += " mips";
838 break;
839 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700840 *output += " arm";
841 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700842 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700843 *output += " x86-64";
844 break;
845 default:
846 *output += " unknown-arch";
847 }
848 return true;
849}
850
851string GetFileFormat(const string& path) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800852 chromeos::Blob buffer;
Alex Deymo032e7722014-03-25 17:53:56 -0700853 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
854 return "File not found.";
855
856 string result;
857 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
858 return result;
859
860 return "data";
861}
862
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800863namespace {
864// Do the actual trigger. We do it as a main-loop callback to (try to) get a
865// consistent stack trace.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700866void TriggerCrashReporterUpload() {
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800867 pid_t pid = fork();
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700868 CHECK_GE(pid, 0) << "fork failed"; // fork() failed. Something is very wrong.
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800869 if (pid == 0) {
870 // We are the child. Crash.
871 abort(); // never returns
872 }
873 // We are the parent. Wait for child to terminate.
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700874 pid_t result = waitpid(pid, nullptr, 0);
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800875 LOG_IF(ERROR, result < 0) << "waitpid() failed";
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800876}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700877} // namespace
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800878
879void ScheduleCrashReporterUpload() {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700880 chromeos::MessageLoop::current()->PostTask(
881 FROM_HERE,
882 base::Bind(&TriggerCrashReporterUpload));
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800883}
884
Chris Sosa4f8ee272012-11-30 13:01:54 -0800885bool SetCpuShares(CpuShares shares) {
886 string string_shares = base::IntToString(static_cast<int>(shares));
887 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
888 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700889 if (utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
890 string_shares.size())) {
Chris Sosa4f8ee272012-11-30 13:01:54 -0800891 return true;
892 } else {
893 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
894 << " using " << cpu_shares_file;
895 return false;
896 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700897}
898
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700899int FuzzInt(int value, unsigned int range) {
900 int min = value - range / 2;
901 int max = value + range - range / 2;
902 return base::RandInt(min, max);
903}
904
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700905string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800906 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700907}
908
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800909string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400910 string str;
911
912 // Handle negative durations by prefixing with a minus.
913 if (delta.ToInternalValue() < 0) {
914 delta *= -1;
915 str = "-";
916 }
917
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700918 // Canonicalize into days, hours, minutes, seconds and microseconds.
919 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800920 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700921 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800922 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700923 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800924 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700925 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800926 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700927 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800928
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700929 if (days)
930 base::StringAppendF(&str, "%ud", days);
931 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800932 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700933 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800934 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700935 base::StringAppendF(&str, "%u", secs);
936 if (usecs) {
937 int width = 6;
938 while ((usecs / 10) * 10 == usecs) {
939 usecs /= 10;
940 width--;
941 }
942 base::StringAppendF(&str, ".%0*u", width, usecs);
943 }
944 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800945 return str;
946}
947
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700948string ToString(const Time utc_time) {
949 Time::Exploded exp_time;
950 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700951 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700952 exp_time.month,
953 exp_time.day_of_month,
954 exp_time.year,
955 exp_time.hour,
956 exp_time.minute,
957 exp_time.second);
958}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000959
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700960string ToString(bool b) {
961 return (b ? "true" : "false");
962}
963
Alex Deymo1c656c42013-06-28 11:02:14 -0700964string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700965 switch (source) {
966 case kDownloadSourceHttpsServer: return "HttpsServer";
967 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700968 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -0700969 case kNumDownloadSources: return "Unknown";
970 // Don't add a default case to let the compiler warn about newly added
971 // download sources which should be added here.
972 }
973
974 return "Unknown";
975}
976
Alex Deymo1c656c42013-06-28 11:02:14 -0700977string ToString(PayloadType payload_type) {
978 switch (payload_type) {
979 case kPayloadTypeDelta: return "Delta";
980 case kPayloadTypeFull: return "Full";
981 case kPayloadTypeForcedFull: return "ForcedFull";
982 case kNumPayloadTypes: return "Unknown";
983 // Don't add a default case to let the compiler warn about newly added
984 // payload types which should be added here.
985 }
986
987 return "Unknown";
988}
989
David Zeuthena99981f2013-04-29 13:42:47 -0700990ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700991 // Ignore the higher order bits in the code by applying the mask as
992 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700993 // with values less than ErrorCode::kUmaReportedMax.
994 ErrorCode base_code = static_cast<ErrorCode>(
995 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -0700996
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800997 // Make additional adjustments required for UMA and error classification.
998 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
999 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001000 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -07001001 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001002 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001003 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001004 << " to ErrorCode::kOmahaErrorInHTTPResponse";
1005 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -07001006 }
1007
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001008 return base_code;
1009}
1010
David Zeuthen33bae492014-02-25 16:16:18 -08001011metrics::AttemptResult GetAttemptResult(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001012 ErrorCode base_code = static_cast<ErrorCode>(
1013 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -08001014
1015 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001016 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001017 return metrics::AttemptResult::kUpdateSucceeded;
1018
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001019 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -08001020 return metrics::AttemptResult::kPayloadDownloadError;
1021
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001022 case ErrorCode::kDownloadInvalidMetadataSize:
1023 case ErrorCode::kDownloadInvalidMetadataMagicString:
1024 case ErrorCode::kDownloadMetadataSignatureError:
1025 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1026 case ErrorCode::kPayloadMismatchedType:
1027 case ErrorCode::kUnsupportedMajorPayloadVersion:
1028 case ErrorCode::kUnsupportedMinorPayloadVersion:
1029 case ErrorCode::kDownloadNewPartitionInfoError:
1030 case ErrorCode::kDownloadSignatureMissingInManifest:
1031 case ErrorCode::kDownloadManifestParseError:
1032 case ErrorCode::kDownloadOperationHashMissingError:
David Zeuthen33bae492014-02-25 16:16:18 -08001033 return metrics::AttemptResult::kMetadataMalformed;
1034
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001035 case ErrorCode::kDownloadOperationHashMismatch:
1036 case ErrorCode::kDownloadOperationHashVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001037 return metrics::AttemptResult::kOperationMalformed;
1038
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001039 case ErrorCode::kDownloadOperationExecutionError:
1040 case ErrorCode::kInstallDeviceOpenError:
1041 case ErrorCode::kKernelDeviceOpenError:
1042 case ErrorCode::kDownloadWriteError:
1043 case ErrorCode::kFilesystemCopierError:
Allie Woodeb9e6d82015-04-17 13:55:30 -07001044 case ErrorCode::kFilesystemVerifierError:
David Zeuthen33bae492014-02-25 16:16:18 -08001045 return metrics::AttemptResult::kOperationExecutionError;
1046
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001047 case ErrorCode::kDownloadMetadataSignatureMismatch:
David Zeuthen33bae492014-02-25 16:16:18 -08001048 return metrics::AttemptResult::kMetadataVerificationFailed;
1049
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001050 case ErrorCode::kPayloadSizeMismatchError:
1051 case ErrorCode::kPayloadHashMismatchError:
1052 case ErrorCode::kDownloadPayloadVerificationError:
1053 case ErrorCode::kSignedDeltaPayloadExpectedError:
1054 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001055 return metrics::AttemptResult::kPayloadVerificationFailed;
1056
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001057 case ErrorCode::kNewRootfsVerificationError:
1058 case ErrorCode::kNewKernelVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001059 return metrics::AttemptResult::kVerificationFailed;
1060
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001061 case ErrorCode::kPostinstallRunnerError:
1062 case ErrorCode::kPostinstallBootedFromFirmwareB:
1063 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
David Zeuthen33bae492014-02-25 16:16:18 -08001064 return metrics::AttemptResult::kPostInstallFailed;
1065
1066 // We should never get these errors in the update-attempt stage so
1067 // return internal error if this happens.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001068 case ErrorCode::kError:
1069 case ErrorCode::kOmahaRequestXMLParseError:
1070 case ErrorCode::kOmahaRequestError:
1071 case ErrorCode::kOmahaResponseHandlerError:
1072 case ErrorCode::kDownloadStateInitializationError:
1073 case ErrorCode::kOmahaRequestEmptyResponseError:
1074 case ErrorCode::kDownloadInvalidMetadataSignature:
1075 case ErrorCode::kOmahaResponseInvalid:
1076 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1077 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1078 case ErrorCode::kOmahaErrorInHTTPResponse:
1079 case ErrorCode::kDownloadMetadataSignatureMissingError:
1080 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1081 case ErrorCode::kPostinstallPowerwashError:
1082 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -04001083 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
David Zeuthen33bae492014-02-25 16:16:18 -08001084 return metrics::AttemptResult::kInternalError;
1085
1086 // Special flags. These can't happen (we mask them out above) but
1087 // the compiler doesn't know that. Just break out so we can warn and
1088 // return |kInternalError|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001089 case ErrorCode::kUmaReportedMax:
1090 case ErrorCode::kOmahaRequestHTTPResponseBase:
1091 case ErrorCode::kDevModeFlag:
1092 case ErrorCode::kResumedFlag:
1093 case ErrorCode::kTestImageFlag:
1094 case ErrorCode::kTestOmahaUrlFlag:
1095 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001096 break;
1097 }
1098
1099 LOG(ERROR) << "Unexpected error code " << base_code;
1100 return metrics::AttemptResult::kInternalError;
1101}
1102
1103
1104metrics::DownloadErrorCode GetDownloadErrorCode(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001105 ErrorCode base_code = static_cast<ErrorCode>(
1106 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -08001107
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001108 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
1109 int http_status =
1110 static_cast<int>(base_code) -
1111 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase);
David Zeuthen33bae492014-02-25 16:16:18 -08001112 if (http_status >= 200 && http_status <= 599) {
1113 return static_cast<metrics::DownloadErrorCode>(
1114 static_cast<int>(metrics::DownloadErrorCode::kHttpStatus200) +
1115 http_status - 200);
1116 } else if (http_status == 0) {
1117 // The code is using HTTP Status 0 for "Unable to get http
1118 // response code."
1119 return metrics::DownloadErrorCode::kDownloadError;
1120 }
1121 LOG(WARNING) << "Unexpected HTTP status code " << http_status;
1122 return metrics::DownloadErrorCode::kHttpStatusOther;
1123 }
1124
1125 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001126 // Unfortunately, ErrorCode::kDownloadTransferError is returned for a wide
David Zeuthen33bae492014-02-25 16:16:18 -08001127 // variety of errors (proxy errors, host not reachable, timeouts etc.).
1128 //
1129 // For now just map that to kDownloading. See http://crbug.com/355745
1130 // for how we plan to add more detail in the future.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001131 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -08001132 return metrics::DownloadErrorCode::kDownloadError;
1133
1134 // All of these error codes are not related to downloading so break
1135 // out so we can warn and return InputMalformed.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001136 case ErrorCode::kSuccess:
1137 case ErrorCode::kError:
1138 case ErrorCode::kOmahaRequestError:
1139 case ErrorCode::kOmahaResponseHandlerError:
1140 case ErrorCode::kFilesystemCopierError:
1141 case ErrorCode::kPostinstallRunnerError:
1142 case ErrorCode::kPayloadMismatchedType:
1143 case ErrorCode::kInstallDeviceOpenError:
1144 case ErrorCode::kKernelDeviceOpenError:
1145 case ErrorCode::kPayloadHashMismatchError:
1146 case ErrorCode::kPayloadSizeMismatchError:
1147 case ErrorCode::kDownloadPayloadVerificationError:
1148 case ErrorCode::kDownloadNewPartitionInfoError:
1149 case ErrorCode::kDownloadWriteError:
1150 case ErrorCode::kNewRootfsVerificationError:
1151 case ErrorCode::kNewKernelVerificationError:
1152 case ErrorCode::kSignedDeltaPayloadExpectedError:
1153 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1154 case ErrorCode::kPostinstallBootedFromFirmwareB:
1155 case ErrorCode::kDownloadStateInitializationError:
1156 case ErrorCode::kDownloadInvalidMetadataMagicString:
1157 case ErrorCode::kDownloadSignatureMissingInManifest:
1158 case ErrorCode::kDownloadManifestParseError:
1159 case ErrorCode::kDownloadMetadataSignatureError:
1160 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1161 case ErrorCode::kDownloadMetadataSignatureMismatch:
1162 case ErrorCode::kDownloadOperationHashVerificationError:
1163 case ErrorCode::kDownloadOperationExecutionError:
1164 case ErrorCode::kDownloadOperationHashMismatch:
1165 case ErrorCode::kOmahaRequestEmptyResponseError:
1166 case ErrorCode::kOmahaRequestXMLParseError:
1167 case ErrorCode::kDownloadInvalidMetadataSize:
1168 case ErrorCode::kDownloadInvalidMetadataSignature:
1169 case ErrorCode::kOmahaResponseInvalid:
1170 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1171 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1172 case ErrorCode::kOmahaErrorInHTTPResponse:
1173 case ErrorCode::kDownloadOperationHashMissingError:
1174 case ErrorCode::kDownloadMetadataSignatureMissingError:
1175 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1176 case ErrorCode::kPostinstallPowerwashError:
1177 case ErrorCode::kUpdateCanceledByChannelChange:
1178 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1179 case ErrorCode::kUnsupportedMajorPayloadVersion:
1180 case ErrorCode::kUnsupportedMinorPayloadVersion:
David Zeuthenf3e28012014-08-26 18:23:52 -04001181 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -07001182 case ErrorCode::kFilesystemVerifierError:
David Zeuthen33bae492014-02-25 16:16:18 -08001183 break;
1184
1185 // Special flags. These can't happen (we mask them out above) but
1186 // the compiler doesn't know that. Just break out so we can warn and
1187 // return |kInputMalformed|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001188 case ErrorCode::kUmaReportedMax:
1189 case ErrorCode::kOmahaRequestHTTPResponseBase:
1190 case ErrorCode::kDevModeFlag:
1191 case ErrorCode::kResumedFlag:
1192 case ErrorCode::kTestImageFlag:
1193 case ErrorCode::kTestOmahaUrlFlag:
1194 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001195 LOG(ERROR) << "Unexpected error code " << base_code;
1196 break;
1197 }
1198
1199 return metrics::DownloadErrorCode::kInputMalformed;
1200}
1201
David Zeuthenb281f072014-04-02 10:20:19 -07001202metrics::ConnectionType GetConnectionType(
1203 NetworkConnectionType type,
1204 NetworkTethering tethering) {
1205 switch (type) {
Alex Deymo75eac7e2015-07-29 13:39:14 -07001206 case NetworkConnectionType::kUnknown:
David Zeuthenb281f072014-04-02 10:20:19 -07001207 return metrics::ConnectionType::kUnknown;
1208
Alex Deymo75eac7e2015-07-29 13:39:14 -07001209 case NetworkConnectionType::kEthernet:
David Zeuthenb281f072014-04-02 10:20:19 -07001210 if (tethering == NetworkTethering::kConfirmed)
1211 return metrics::ConnectionType::kTetheredEthernet;
1212 else
1213 return metrics::ConnectionType::kEthernet;
1214
Alex Deymo75eac7e2015-07-29 13:39:14 -07001215 case NetworkConnectionType::kWifi:
David Zeuthenb281f072014-04-02 10:20:19 -07001216 if (tethering == NetworkTethering::kConfirmed)
1217 return metrics::ConnectionType::kTetheredWifi;
1218 else
1219 return metrics::ConnectionType::kWifi;
1220
Alex Deymo75eac7e2015-07-29 13:39:14 -07001221 case NetworkConnectionType::kWimax:
David Zeuthenb281f072014-04-02 10:20:19 -07001222 return metrics::ConnectionType::kWimax;
1223
Alex Deymo75eac7e2015-07-29 13:39:14 -07001224 case NetworkConnectionType::kBluetooth:
David Zeuthenb281f072014-04-02 10:20:19 -07001225 return metrics::ConnectionType::kBluetooth;
1226
Alex Deymo75eac7e2015-07-29 13:39:14 -07001227 case NetworkConnectionType::kCellular:
David Zeuthenb281f072014-04-02 10:20:19 -07001228 return metrics::ConnectionType::kCellular;
1229 }
1230
Alex Deymo75eac7e2015-07-29 13:39:14 -07001231 LOG(ERROR) << "Unexpected network connection type: type="
1232 << static_cast<int>(type)
David Zeuthenb281f072014-04-02 10:20:19 -07001233 << ", tethering=" << static_cast<int>(tethering);
1234
1235 return metrics::ConnectionType::kUnknown;
1236}
1237
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001238// Returns a printable version of the various flags denoted in the higher order
1239// bits of the given code. Returns an empty string if none of those bits are
1240// set.
1241string GetFlagNames(uint32_t code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001242 uint32_t flags = (static_cast<uint32_t>(code) &
1243 static_cast<uint32_t>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001244 string flag_names;
1245 string separator = "";
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001246 for (size_t i = 0; i < sizeof(flags) * 8; i++) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001247 uint32_t flag = flags & (1 << i);
1248 if (flag) {
David Zeuthena99981f2013-04-29 13:42:47 -07001249 flag_names += separator + CodeToString(static_cast<ErrorCode>(flag));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001250 separator = ", ";
1251 }
1252 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001253
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001254 return flag_names;
Jay Srinivasanf0572052012-10-23 18:12:56 -07001255}
1256
David Zeuthena99981f2013-04-29 13:42:47 -07001257void SendErrorCodeToUma(SystemState* system_state, ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001258 if (!system_state)
1259 return;
1260
David Zeuthena99981f2013-04-29 13:42:47 -07001261 ErrorCode uma_error_code = GetBaseErrorCode(code);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001262
1263 // If the code doesn't have flags computed already, compute them now based on
1264 // the state of the current update attempt.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001265 uint32_t flags =
1266 static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001267 if (!flags)
1268 flags = system_state->update_attempter()->GetErrorCodeFlags();
1269
1270 // Determine the UMA bucket depending on the flags. But, ignore the resumed
1271 // flag, as it's perfectly normal for production devices to resume their
1272 // downloads and so we want to record those cases also in NormalErrorCodes
1273 // bucket.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001274 string metric =
1275 flags & ~static_cast<uint32_t>(ErrorCode::kResumedFlag) ?
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001276 "Installer.DevModeErrorCodes" : "Installer.NormalErrorCodes";
1277
1278 LOG(INFO) << "Sending error code " << uma_error_code
1279 << " (" << CodeToString(uma_error_code) << ")"
1280 << " to UMA metric: " << metric
1281 << ". Flags = " << (flags ? GetFlagNames(flags) : "None");
1282
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001283 system_state->metrics_lib()->SendEnumToUMA(
1284 metric, static_cast<int>(uma_error_code),
1285 static_cast<int>(ErrorCode::kUmaReportedMax));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001286}
1287
David Zeuthena99981f2013-04-29 13:42:47 -07001288string CodeToString(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001289 // If the given code has both parts (i.e. the error code part and the flags
1290 // part) then strip off the flags part since the switch statement below
1291 // has case statements only for the base error code or a single flag but
1292 // doesn't support any combinations of those.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001293 if ((static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags)) &&
1294 (static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags)))
1295 code = static_cast<ErrorCode>(
1296 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001297 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001298 case ErrorCode::kSuccess: return "ErrorCode::kSuccess";
1299 case ErrorCode::kError: return "ErrorCode::kError";
1300 case ErrorCode::kOmahaRequestError: return "ErrorCode::kOmahaRequestError";
1301 case ErrorCode::kOmahaResponseHandlerError:
1302 return "ErrorCode::kOmahaResponseHandlerError";
1303 case ErrorCode::kFilesystemCopierError:
1304 return "ErrorCode::kFilesystemCopierError";
1305 case ErrorCode::kPostinstallRunnerError:
1306 return "ErrorCode::kPostinstallRunnerError";
1307 case ErrorCode::kPayloadMismatchedType:
1308 return "ErrorCode::kPayloadMismatchedType";
1309 case ErrorCode::kInstallDeviceOpenError:
1310 return "ErrorCode::kInstallDeviceOpenError";
1311 case ErrorCode::kKernelDeviceOpenError:
1312 return "ErrorCode::kKernelDeviceOpenError";
1313 case ErrorCode::kDownloadTransferError:
1314 return "ErrorCode::kDownloadTransferError";
1315 case ErrorCode::kPayloadHashMismatchError:
1316 return "ErrorCode::kPayloadHashMismatchError";
1317 case ErrorCode::kPayloadSizeMismatchError:
1318 return "ErrorCode::kPayloadSizeMismatchError";
1319 case ErrorCode::kDownloadPayloadVerificationError:
1320 return "ErrorCode::kDownloadPayloadVerificationError";
1321 case ErrorCode::kDownloadNewPartitionInfoError:
1322 return "ErrorCode::kDownloadNewPartitionInfoError";
1323 case ErrorCode::kDownloadWriteError:
1324 return "ErrorCode::kDownloadWriteError";
1325 case ErrorCode::kNewRootfsVerificationError:
1326 return "ErrorCode::kNewRootfsVerificationError";
1327 case ErrorCode::kNewKernelVerificationError:
1328 return "ErrorCode::kNewKernelVerificationError";
1329 case ErrorCode::kSignedDeltaPayloadExpectedError:
1330 return "ErrorCode::kSignedDeltaPayloadExpectedError";
1331 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1332 return "ErrorCode::kDownloadPayloadPubKeyVerificationError";
1333 case ErrorCode::kPostinstallBootedFromFirmwareB:
1334 return "ErrorCode::kPostinstallBootedFromFirmwareB";
1335 case ErrorCode::kDownloadStateInitializationError:
1336 return "ErrorCode::kDownloadStateInitializationError";
1337 case ErrorCode::kDownloadInvalidMetadataMagicString:
1338 return "ErrorCode::kDownloadInvalidMetadataMagicString";
1339 case ErrorCode::kDownloadSignatureMissingInManifest:
1340 return "ErrorCode::kDownloadSignatureMissingInManifest";
1341 case ErrorCode::kDownloadManifestParseError:
1342 return "ErrorCode::kDownloadManifestParseError";
1343 case ErrorCode::kDownloadMetadataSignatureError:
1344 return "ErrorCode::kDownloadMetadataSignatureError";
1345 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1346 return "ErrorCode::kDownloadMetadataSignatureVerificationError";
1347 case ErrorCode::kDownloadMetadataSignatureMismatch:
1348 return "ErrorCode::kDownloadMetadataSignatureMismatch";
1349 case ErrorCode::kDownloadOperationHashVerificationError:
1350 return "ErrorCode::kDownloadOperationHashVerificationError";
1351 case ErrorCode::kDownloadOperationExecutionError:
1352 return "ErrorCode::kDownloadOperationExecutionError";
1353 case ErrorCode::kDownloadOperationHashMismatch:
1354 return "ErrorCode::kDownloadOperationHashMismatch";
1355 case ErrorCode::kOmahaRequestEmptyResponseError:
1356 return "ErrorCode::kOmahaRequestEmptyResponseError";
1357 case ErrorCode::kOmahaRequestXMLParseError:
1358 return "ErrorCode::kOmahaRequestXMLParseError";
1359 case ErrorCode::kDownloadInvalidMetadataSize:
1360 return "ErrorCode::kDownloadInvalidMetadataSize";
1361 case ErrorCode::kDownloadInvalidMetadataSignature:
1362 return "ErrorCode::kDownloadInvalidMetadataSignature";
1363 case ErrorCode::kOmahaResponseInvalid:
1364 return "ErrorCode::kOmahaResponseInvalid";
1365 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1366 return "ErrorCode::kOmahaUpdateIgnoredPerPolicy";
1367 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1368 return "ErrorCode::kOmahaUpdateDeferredPerPolicy";
1369 case ErrorCode::kOmahaErrorInHTTPResponse:
1370 return "ErrorCode::kOmahaErrorInHTTPResponse";
1371 case ErrorCode::kDownloadOperationHashMissingError:
1372 return "ErrorCode::kDownloadOperationHashMissingError";
1373 case ErrorCode::kDownloadMetadataSignatureMissingError:
1374 return "ErrorCode::kDownloadMetadataSignatureMissingError";
1375 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1376 return "ErrorCode::kOmahaUpdateDeferredForBackoff";
1377 case ErrorCode::kPostinstallPowerwashError:
1378 return "ErrorCode::kPostinstallPowerwashError";
1379 case ErrorCode::kUpdateCanceledByChannelChange:
1380 return "ErrorCode::kUpdateCanceledByChannelChange";
1381 case ErrorCode::kUmaReportedMax:
1382 return "ErrorCode::kUmaReportedMax";
1383 case ErrorCode::kOmahaRequestHTTPResponseBase:
1384 return "ErrorCode::kOmahaRequestHTTPResponseBase";
1385 case ErrorCode::kResumedFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001386 return "Resumed";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001387 case ErrorCode::kDevModeFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001388 return "DevMode";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001389 case ErrorCode::kTestImageFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001390 return "TestImage";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001391 case ErrorCode::kTestOmahaUrlFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001392 return "TestOmahaUrl";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001393 case ErrorCode::kSpecialFlags:
1394 return "ErrorCode::kSpecialFlags";
1395 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1396 return "ErrorCode::kPostinstallFirmwareRONotUpdatable";
1397 case ErrorCode::kUnsupportedMajorPayloadVersion:
1398 return "ErrorCode::kUnsupportedMajorPayloadVersion";
1399 case ErrorCode::kUnsupportedMinorPayloadVersion:
1400 return "ErrorCode::kUnsupportedMinorPayloadVersion";
David Zeuthenf3e28012014-08-26 18:23:52 -04001401 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
1402 return "ErrorCode::kOmahaRequestXMLHasEntityDecl";
Allie Woodeb9e6d82015-04-17 13:55:30 -07001403 case ErrorCode::kFilesystemVerifierError:
1404 return "ErrorCode::kFilesystemVerifierError";
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001405 // Don't add a default case to let the compiler warn about newly added
1406 // error codes which should be added here.
1407 }
1408
1409 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
1410}
Jay Srinivasanf0572052012-10-23 18:12:56 -07001411
Gilad Arnold30dedd82013-07-03 06:19:09 -07001412bool CreatePowerwashMarkerFile(const char* file_path) {
1413 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
1414 bool result = utils::WriteFile(marker_file,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001415 kPowerwashCommand,
1416 strlen(kPowerwashCommand));
Gilad Arnold30dedd82013-07-03 06:19:09 -07001417 if (result) {
1418 LOG(INFO) << "Created " << marker_file << " to powerwash on next reboot";
1419 } else {
1420 PLOG(ERROR) << "Error in creating powerwash marker file: " << marker_file;
1421 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001422
1423 return result;
1424}
1425
Gilad Arnold30dedd82013-07-03 06:19:09 -07001426bool DeletePowerwashMarkerFile(const char* file_path) {
1427 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
Alex Vakulenko75039d72014-03-25 12:36:28 -07001428 const base::FilePath kPowerwashMarkerPath(marker_file);
1429 bool result = base::DeleteFile(kPowerwashMarkerPath, false);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001430
1431 if (result)
1432 LOG(INFO) << "Successfully deleted the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001433 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001434 else
1435 PLOG(ERROR) << "Could not delete the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001436 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001437
1438 return result;
1439}
1440
David Zeuthen27a48bc2013-08-06 12:06:29 -07001441Time TimeFromStructTimespec(struct timespec *ts) {
Ben Chan9abb7632014-08-07 00:10:53 -07001442 int64_t us = static_cast<int64_t>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
1443 static_cast<int64_t>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
David Zeuthen27a48bc2013-08-06 12:06:29 -07001444 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
1445}
1446
Alex Deymof329b932014-10-30 01:37:48 -07001447string StringVectorToString(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -07001448 string str = "[";
Alex Deymof329b932014-10-30 01:37:48 -07001449 for (vector<string>::const_iterator i = vec_str.begin();
1450 i != vec_str.end(); ++i) {
1451 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -07001452 str += ", ";
1453 str += '"';
1454 str += *i;
1455 str += '"';
1456 }
1457 str += "]";
1458 return str;
1459}
1460
David Zeuthen8f191b22013-08-06 12:27:50 -07001461string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001462 string encoded_hash = chromeos::data_encoding::Base64Encode(payload_hash);
Alex Deymoc00c98a2015-03-17 17:38:00 -07001463 return base::StringPrintf("cros_update_size_%" PRIuS "_hash_%s",
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001464 payload_size,
1465 encoded_hash.c_str());
David Zeuthen8f191b22013-08-06 12:27:50 -07001466}
1467
Alex Deymof329b932014-10-30 01:37:48 -07001468bool DecodeAndStoreBase64String(const string& base64_encoded,
David Zeuthene7f89172013-10-31 10:21:04 -07001469 base::FilePath *out_path) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001470 chromeos::Blob contents;
David Zeuthene7f89172013-10-31 10:21:04 -07001471
1472 out_path->clear();
1473
1474 if (base64_encoded.size() == 0) {
1475 LOG(ERROR) << "Can't decode empty string.";
1476 return false;
1477 }
1478
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001479 if (!chromeos::data_encoding::Base64Decode(base64_encoded, &contents) ||
David Zeuthene7f89172013-10-31 10:21:04 -07001480 contents.size() == 0) {
1481 LOG(ERROR) << "Error decoding base64.";
1482 return false;
1483 }
1484
Alex Vakulenko75039d72014-03-25 12:36:28 -07001485 FILE *file = base::CreateAndOpenTemporaryFile(out_path);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001486 if (file == nullptr) {
David Zeuthene7f89172013-10-31 10:21:04 -07001487 LOG(ERROR) << "Error creating temporary file.";
1488 return false;
1489 }
1490
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001491 if (fwrite(contents.data(), 1, contents.size(), file) != contents.size()) {
David Zeuthene7f89172013-10-31 10:21:04 -07001492 PLOG(ERROR) << "Error writing to temporary file.";
1493 if (fclose(file) != 0)
1494 PLOG(ERROR) << "Error closing temporary file.";
1495 if (unlink(out_path->value().c_str()) != 0)
1496 PLOG(ERROR) << "Error unlinking temporary file.";
1497 out_path->clear();
1498 return false;
1499 }
1500
1501 if (fclose(file) != 0) {
1502 PLOG(ERROR) << "Error closing temporary file.";
1503 out_path->clear();
1504 return false;
1505 }
1506
1507 return true;
1508}
1509
Alex Deymof329b932014-10-30 01:37:48 -07001510bool ConvertToOmahaInstallDate(Time time, int *out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -08001511 time_t unix_time = time.ToTimeT();
1512 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
1513 const time_t kOmahaEpoch = 1167638400;
1514 const int64_t kNumSecondsPerWeek = 7*24*3600;
1515 const int64_t kNumDaysPerWeek = 7;
1516
1517 time_t omaha_time = unix_time - kOmahaEpoch;
1518
1519 if (omaha_time < 0)
1520 return false;
1521
1522 // Note, as per the comment in utils.h we are deliberately not
1523 // handling DST correctly.
1524
1525 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
1526 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
1527
1528 return true;
1529}
1530
David Zeuthen33bae492014-02-25 16:16:18 -08001531bool WallclockDurationHelper(SystemState* system_state,
Alex Deymof329b932014-10-30 01:37:48 -07001532 const string& state_variable_key,
1533 TimeDelta* out_duration) {
David Zeuthen33bae492014-02-25 16:16:18 -08001534 bool ret = false;
1535
Alex Deymof329b932014-10-30 01:37:48 -07001536 Time now = system_state->clock()->GetWallclockTime();
David Zeuthen33bae492014-02-25 16:16:18 -08001537 int64_t stored_value;
1538 if (system_state->prefs()->GetInt64(state_variable_key, &stored_value)) {
Alex Deymof329b932014-10-30 01:37:48 -07001539 Time stored_time = Time::FromInternalValue(stored_value);
David Zeuthen33bae492014-02-25 16:16:18 -08001540 if (stored_time > now) {
1541 LOG(ERROR) << "Stored time-stamp used for " << state_variable_key
1542 << " is in the future.";
1543 } else {
1544 *out_duration = now - stored_time;
1545 ret = true;
1546 }
1547 }
1548
1549 if (!system_state->prefs()->SetInt64(state_variable_key,
1550 now.ToInternalValue())) {
1551 LOG(ERROR) << "Error storing time-stamp in " << state_variable_key;
1552 }
1553
1554 return ret;
1555}
1556
1557bool MonotonicDurationHelper(SystemState* system_state,
1558 int64_t* storage,
Alex Deymof329b932014-10-30 01:37:48 -07001559 TimeDelta* out_duration) {
David Zeuthen33bae492014-02-25 16:16:18 -08001560 bool ret = false;
1561
Alex Deymof329b932014-10-30 01:37:48 -07001562 Time now = system_state->clock()->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -08001563 if (*storage != 0) {
Alex Deymof329b932014-10-30 01:37:48 -07001564 Time stored_time = Time::FromInternalValue(*storage);
David Zeuthen33bae492014-02-25 16:16:18 -08001565 *out_duration = now - stored_time;
1566 ret = true;
1567 }
1568 *storage = now.ToInternalValue();
1569
1570 return ret;
1571}
1572
Alex Deymob42b98d2015-07-06 17:42:38 -07001573bool GetMinorVersion(const chromeos::KeyValueStore& store,
1574 uint32_t* minor_version) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001575 string result;
Alex Deymob42b98d2015-07-06 17:42:38 -07001576 if (store.GetString("PAYLOAD_MINOR_VERSION", &result)) {
Allie Wood425aa972015-02-17 14:47:17 -08001577 if (!base::StringToUint(result, minor_version)) {
1578 LOG(ERROR) << "StringToUint failed when parsing delta minor version.";
1579 return false;
1580 }
Allie Wood78750a42015-02-11 15:42:11 -08001581 return true;
1582 }
1583 return false;
1584}
1585
Alex Deymo60ca1a72015-06-18 18:19:15 -07001586bool ReadExtents(const string& path, const vector<Extent>& extents,
Allie Wood56873452015-03-27 17:48:40 -07001587 chromeos::Blob* out_data, ssize_t out_data_size,
1588 size_t block_size) {
1589 chromeos::Blob data(out_data_size);
1590 ssize_t bytes_read = 0;
1591 int fd = open(path.c_str(), O_RDONLY);
1592 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
1593 ScopedFdCloser fd_closer(&fd);
1594
Gilad Arnold41e34742015-05-11 11:31:50 -07001595 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -07001596 ssize_t bytes_read_this_iteration = 0;
1597 ssize_t bytes = extent.num_blocks() * block_size;
1598 TEST_AND_RETURN_FALSE(bytes_read + bytes <= out_data_size);
1599 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
1600 &data[bytes_read],
1601 bytes,
1602 extent.start_block() * block_size,
1603 &bytes_read_this_iteration));
1604 TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes);
1605 bytes_read += bytes_read_this_iteration;
1606 }
1607 TEST_AND_RETURN_FALSE(out_data_size == bytes_read);
1608 *out_data = data;
1609 return true;
1610}
1611
adlr@google.com3defe6a2009-12-04 20:57:17 +00001612} // namespace utils
1613
1614} // namespace chromeos_update_engine