blob: 304aba2f856022382fbe5449d9d92fc09a43f04b [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
Alex Deymo39910dc2015-11-09 17:04:30 -080017#include "update_engine/common/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 Vakulenko3f39d5c2015-10-13 09:27:13 -070054#include <brillo/data_encoding.h>
55#include <brillo/message_loops/message_loop.h>
Will Drewry8f71da82010-08-30 14:07:11 -050056
Alex Deymo39910dc2015-11-09 17:04:30 -080057#include "update_engine/common/clock_interface.h"
58#include "update_engine/common/constants.h"
Sen Jiang9c123462015-11-19 13:16:23 -080059#include "update_engine/common/platform_constants.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080060#include "update_engine/common/prefs_interface.h"
61#include "update_engine/common/subprocess.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080062#include "update_engine/payload_consumer/file_descriptor.h"
63#include "update_engine/payload_consumer/file_writer.h"
Sen Jiang3a92aa22016-03-01 14:22:52 -080064#include "update_engine/payload_consumer/payload_constants.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000065
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070066using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080067using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000068using std::min;
Chris Sosac1972482013-04-30 22:31:10 -070069using std::pair;
adlr@google.com3defe6a2009-12-04 20:57:17 +000070using std::string;
71using std::vector;
72
73namespace chromeos_update_engine {
74
Ben Chan77a1eba2012-10-07 22:54:55 -070075namespace {
76
77// The following constants control how UnmountFilesystem should retry if
78// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
79// one second.
80const int kUnmountMaxNumOfRetries = 5;
81const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Alex Deymo032e7722014-03-25 17:53:56 -070082
83// Number of bytes to read from a file to attempt to detect its contents. Used
84// in GetFileFormat.
85const int kGetFileFormatMaxHeaderSize = 32;
86
Alex Deymodd132f32015-09-14 19:12:07 -070087// The path to the kernel's boot_id.
88const char kBootIdPath[] = "/proc/sys/kernel/random/boot_id";
89
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080090// Return true if |disk_name| is an MTD or a UBI device. Note that this test is
91// simply based on the name of the device.
92bool IsMtdDeviceName(const string& disk_name) {
Alex Vakulenko0103c362016-01-20 07:56:15 -080093 return base::StartsWith(disk_name, "/dev/ubi",
94 base::CompareCase::SENSITIVE) ||
95 base::StartsWith(disk_name, "/dev/mtd", base::CompareCase::SENSITIVE);
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080096}
97
98// Return the device name for the corresponding partition on a NAND device.
99// WARNING: This function returns device names that are not mountable.
100string MakeNandPartitionName(int partition_num) {
101 switch (partition_num) {
102 case 2:
103 case 4:
104 case 6: {
105 return base::StringPrintf("/dev/mtd%d", partition_num);
106 }
107 default: {
108 return base::StringPrintf("/dev/ubi%d_0", partition_num);
109 }
110 }
111}
112
113// Return the device name for the corresponding partition on a NAND device that
114// may be mountable (but may not be writable).
115string MakeNandPartitionNameForMount(int partition_num) {
116 switch (partition_num) {
117 case 2:
118 case 4:
119 case 6: {
120 return base::StringPrintf("/dev/mtd%d", partition_num);
121 }
122 case 3:
123 case 5:
124 case 7: {
125 return base::StringPrintf("/dev/ubiblock%d_0", partition_num);
126 }
127 default: {
128 return base::StringPrintf("/dev/ubi%d_0", partition_num);
129 }
130 }
131}
132
Alex Deymo5aa1c542015-09-18 01:02:33 -0700133// If |path| is absolute, or explicit relative to the current working directory,
134// leaves it as is. Otherwise, uses the system's temp directory, as defined by
135// base::GetTempDir() and prepends it to |path|. On success stores the full
136// temporary path in |template_path| and returns true.
137bool GetTempName(const string& path, base::FilePath* template_path) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800138 if (path[0] == '/' ||
139 base::StartsWith(path, "./", base::CompareCase::SENSITIVE) ||
140 base::StartsWith(path, "../", base::CompareCase::SENSITIVE)) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700141 *template_path = base::FilePath(path);
142 return true;
143 }
144
145 base::FilePath temp_dir;
Sen Jiang9c123462015-11-19 13:16:23 -0800146#ifdef __ANDROID__
147 temp_dir = base::FilePath(constants::kNonVolatileDirectory).Append("tmp");
148 if (!base::PathExists(temp_dir))
149 TEST_AND_RETURN_FALSE(base::CreateDirectory(temp_dir));
150#else
Alex Deymo5aa1c542015-09-18 01:02:33 -0700151 TEST_AND_RETURN_FALSE(base::GetTempDir(&temp_dir));
Sen Jiang9c123462015-11-19 13:16:23 -0800152#endif // __ANDROID__
Alex Deymo5aa1c542015-09-18 01:02:33 -0700153 *template_path = temp_dir.Append(path);
154 return true;
155}
156
Ben Chan77a1eba2012-10-07 22:54:55 -0700157} // namespace
158
adlr@google.com3defe6a2009-12-04 20:57:17 +0000159namespace utils {
160
J. Richard Barnette63137e52013-10-28 10:57:29 -0700161string ParseECVersion(string input_line) {
Ben Chan736fcb52014-05-21 18:28:22 -0700162 base::TrimWhitespaceASCII(input_line, base::TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -0700163
Alex Vakulenko75039d72014-03-25 12:36:28 -0700164 // At this point we want to convert the format key=value pair from mosys to
Chris Sosac1972482013-04-30 22:31:10 -0700165 // a vector of key value pairs.
Ben Chanf9cb98c2014-09-21 18:31:30 -0700166 vector<pair<string, string>> kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -0700167 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Alex Deymo020600d2014-11-05 21:05:55 -0800168 for (const pair<string, string>& kv_pair : kv_pairs) {
Chris Sosac1972482013-04-30 22:31:10 -0700169 // Finally match against the fw_verion which may have quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800170 if (kv_pair.first == "fw_version") {
Chris Sosac1972482013-04-30 22:31:10 -0700171 string output;
172 // Trim any quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800173 base::TrimString(kv_pair.second, "\"", &output);
Chris Sosac1972482013-04-30 22:31:10 -0700174 return output;
175 }
176 }
177 }
178 LOG(ERROR) << "Unable to parse fwid from ec info.";
179 return "";
180}
181
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800182bool WriteFile(const char* path, const void* data, int data_len) {
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800183 DirectFileWriter writer;
184 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
185 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700186 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800187 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800188 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800189 return true;
190}
191
Alex Deymo72ea95a2016-03-30 18:31:49 -0700192bool ReadAll(
193 int fd, void* buf, size_t count, size_t* out_bytes_read, bool* eof) {
194 char* c_buf = static_cast<char*>(buf);
195 size_t bytes_read = 0;
196 *eof = false;
197 while (bytes_read < count) {
198 ssize_t rc = HANDLE_EINTR(read(fd, c_buf + bytes_read, count - bytes_read));
199 if (rc < 0) {
200 // EAGAIN and EWOULDBLOCK are normal return values when there's no more
201 // input and we are in non-blocking mode.
202 if (errno != EWOULDBLOCK && errno != EAGAIN) {
203 PLOG(ERROR) << "Error reading fd " << fd;
204 *out_bytes_read = bytes_read;
205 return false;
206 }
207 break;
208 } else if (rc == 0) {
209 // A value of 0 means that we reached EOF and there is nothing else to
210 // read from this fd.
211 *eof = true;
212 break;
213 } else {
214 bytes_read += rc;
215 }
216 }
217 *out_bytes_read = bytes_read;
218 return true;
219}
220
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700221bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700222 const char* c_buf = static_cast<const char*>(buf);
223 ssize_t bytes_written = 0;
224 while (bytes_written < static_cast<ssize_t>(count)) {
225 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
226 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
227 bytes_written += rc;
228 }
229 return true;
230}
231
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700232bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
233 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700234 size_t bytes_written = 0;
235 int num_attempts = 0;
236 while (bytes_written < count) {
237 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700238 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
239 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700240 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
241 if (rc < 0) {
242 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
243 << " bytes_written=" << bytes_written
244 << " count=" << count << " offset=" << offset;
245 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700246 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
247 bytes_written += rc;
248 }
249 return true;
250}
251
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800252bool WriteAll(FileDescriptorPtr fd, const void* buf, size_t count) {
253 const char* c_buf = static_cast<const char*>(buf);
254 ssize_t bytes_written = 0;
255 while (bytes_written < static_cast<ssize_t>(count)) {
256 ssize_t rc = fd->Write(c_buf + bytes_written, count - bytes_written);
257 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
258 bytes_written += rc;
259 }
260 return true;
261}
262
263bool PWriteAll(FileDescriptorPtr fd,
264 const void* buf,
265 size_t count,
266 off_t offset) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700267 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
268 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800269 return WriteAll(fd, buf, count);
270}
271
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700272bool PReadAll(int fd, void* buf, size_t count, off_t offset,
273 ssize_t* out_bytes_read) {
274 char* c_buf = static_cast<char*>(buf);
275 ssize_t bytes_read = 0;
276 while (bytes_read < static_cast<ssize_t>(count)) {
277 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
278 offset + bytes_read);
279 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
280 if (rc == 0) {
281 break;
282 }
283 bytes_read += rc;
284 }
285 *out_bytes_read = bytes_read;
286 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700287}
288
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800289bool PReadAll(FileDescriptorPtr fd, void* buf, size_t count, off_t offset,
290 ssize_t* out_bytes_read) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700291 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
292 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800293 char* c_buf = static_cast<char*>(buf);
294 ssize_t bytes_read = 0;
295 while (bytes_read < static_cast<ssize_t>(count)) {
296 ssize_t rc = fd->Read(c_buf + bytes_read, count - bytes_read);
297 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
298 if (rc == 0) {
299 break;
300 }
301 bytes_read += rc;
302 }
303 *out_bytes_read = bytes_read;
304 return true;
305}
306
Gilad Arnold19a45f02012-07-19 12:36:10 -0700307// Append |nbytes| of content from |buf| to the vector pointed to by either
308// |vec_p| or |str_p|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800309static void AppendBytes(const uint8_t* buf, size_t nbytes,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700310 brillo::Blob* vec_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700311 CHECK(buf);
312 CHECK(vec_p);
313 vec_p->insert(vec_p->end(), buf, buf + nbytes);
314}
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800315static void AppendBytes(const uint8_t* buf, size_t nbytes,
Alex Deymof329b932014-10-30 01:37:48 -0700316 string* str_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700317 CHECK(buf);
318 CHECK(str_p);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800319 str_p->append(buf, buf + nbytes);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700320}
321
322// Reads from an open file |fp|, appending the read content to the container
323// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200324// file's content, false otherwise. If |size| is not -1, reads up to |size|
325// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700326template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200327static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700328 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200329 CHECK(size == -1 || size >= 0);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800330 uint8_t buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200331 while (size == -1 || size > 0) {
332 off_t bytes_to_read = sizeof(buf);
333 if (size > 0 && bytes_to_read > size) {
334 bytes_to_read = size;
335 }
336 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
337 if (!nbytes) {
338 break;
339 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700340 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200341 if (size != -1) {
342 CHECK(size >= static_cast<off_t>(nbytes));
343 size -= nbytes;
344 }
345 }
346 if (ferror(fp)) {
347 return false;
348 }
349 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700350}
351
Darin Petkov8e447e02013-04-16 16:23:50 +0200352// Opens a file |path| for reading and appends its the contents to a container
353// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
354// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700355template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700356static bool ReadFileChunkAndAppend(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200357 off_t offset,
358 off_t size,
359 T* out_p) {
360 CHECK_GE(offset, 0);
361 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700362 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200363 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000364 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200365 if (offset) {
366 // Return success without appending any data if a chunk beyond the end of
367 // the file is requested.
368 if (offset >= FileSize(path)) {
369 return true;
370 }
371 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
372 }
373 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000374}
375
Alex Deymo10875d92014-11-10 21:52:57 -0800376// TODO(deymo): This is only used in unittest, but requires the private
377// Read<string>() defined here. Expose Read<string>() or move to base/ version.
378bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700379 FILE* fp = popen(cmd.c_str(), "r");
380 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000381 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200382 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700383 return (success && pclose(fp) >= 0);
384}
385
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700386bool ReadFile(const string& path, brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200387 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700388}
389
Darin Petkov8e447e02013-04-16 16:23:50 +0200390bool ReadFile(const string& path, string* out_p) {
391 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700392}
393
Darin Petkov8e447e02013-04-16 16:23:50 +0200394bool ReadFileChunk(const string& path, off_t offset, off_t size,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700395 brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200396 return ReadFileChunkAndAppend(path, offset, size, out_p);
397}
398
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700399off_t BlockDevSize(int fd) {
400 uint64_t dev_size;
401 int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
402 if (rc == -1) {
403 dev_size = -1;
404 PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
405 }
406 return dev_size;
407}
408
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700409off_t FileSize(int fd) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700410 struct stat stbuf;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700411 int rc = fstat(fd, &stbuf);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700412 CHECK_EQ(rc, 0);
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700413 if (rc < 0) {
414 PLOG(ERROR) << "Error stat-ing " << fd;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700415 return rc;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700416 }
417 if (S_ISREG(stbuf.st_mode))
418 return stbuf.st_size;
419 if (S_ISBLK(stbuf.st_mode))
420 return BlockDevSize(fd);
421 LOG(ERROR) << "Couldn't determine the type of " << fd;
422 return -1;
423}
424
425off_t FileSize(const string& path) {
426 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
427 if (fd == -1) {
428 PLOG(ERROR) << "Error opening " << path;
429 return fd;
430 }
431 off_t size = FileSize(fd);
432 if (size == -1)
433 PLOG(ERROR) << "Error getting file size of " << path;
434 close(fd);
435 return size;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700436}
437
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800438void HexDumpArray(const uint8_t* const arr, const size_t length) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000439 LOG(INFO) << "Logging array of length: " << length;
440 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700441 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000442 const unsigned int bytes_remaining = length - i;
443 const unsigned int bytes_per_this_line = min(bytes_per_line,
444 bytes_remaining);
445 char header[100];
446 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
447 TEST_AND_RETURN(r == 13);
448 string line = header;
449 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
450 char buf[20];
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800451 uint8_t c = arr[i + j];
adlr@google.com3defe6a2009-12-04 20:57:17 +0000452 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
453 TEST_AND_RETURN(r == 3);
454 line += buf;
455 }
456 LOG(INFO) << line;
457 }
458}
459
Alex Deymof329b932014-10-30 01:37:48 -0700460bool SplitPartitionName(const string& partition_name,
461 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800462 int* out_partition_num) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800463 if (!base::StartsWith(partition_name, "/dev/",
464 base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800465 LOG(ERROR) << "Invalid partition device name: " << partition_name;
466 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700467 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800468
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700469 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
470 if (last_nondigit_pos == string::npos ||
471 (last_nondigit_pos + 1) == partition_name.size()) {
472 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800473 return false;
474 }
475
Alex Deymof329b932014-10-30 01:37:48 -0700476 size_t partition_name_len = string::npos;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700477 if (partition_name[last_nondigit_pos] == '_') {
478 // NAND block devices have weird naming which could be something
479 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
480 size_t prev_nondigit_pos =
481 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
482 if (prev_nondigit_pos == string::npos ||
483 (prev_nondigit_pos + 1) == last_nondigit_pos) {
484 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
485 return false;
486 }
487
488 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
489 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800490 }
491
492 if (out_disk_name) {
493 // Special case for MMC devices which have the following naming scheme:
494 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700495 size_t disk_name_len = last_nondigit_pos;
496 if (partition_name[last_nondigit_pos] != 'p' ||
497 last_nondigit_pos == 0 ||
498 !isdigit(partition_name[last_nondigit_pos - 1])) {
499 disk_name_len++;
500 }
501 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800502 }
503
504 if (out_partition_num) {
Alex Deymof329b932014-10-30 01:37:48 -0700505 string partition_str = partition_name.substr(last_nondigit_pos + 1,
506 partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800507 *out_partition_num = atoi(partition_str.c_str());
508 }
509 return true;
510}
511
Alex Deymof329b932014-10-30 01:37:48 -0700512string MakePartitionName(const string& disk_name, int partition_num) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800513 if (partition_num < 1) {
514 LOG(ERROR) << "Invalid partition number: " << partition_num;
515 return string();
516 }
517
Alex Vakulenko0103c362016-01-20 07:56:15 -0800518 if (!base::StartsWith(disk_name, "/dev/", base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800519 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700520 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800521 }
522
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800523 if (IsMtdDeviceName(disk_name)) {
524 // Special case for UBI block devices.
525 // 1. ubiblock is not writable, we need to use plain "ubi".
526 // 2. There is a "_0" suffix.
527 return MakeNandPartitionName(partition_num);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800528 }
529
Alex Deymof329b932014-10-30 01:37:48 -0700530 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700531 if (isdigit(partition_name.back())) {
532 // Special case for devices with names ending with a digit.
533 // Add "p" to separate the disk name from partition number,
534 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800535 partition_name += 'p';
536 }
537
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700538 partition_name += std::to_string(partition_num);
539
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800540 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700541}
542
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800543string MakePartitionNameForMount(const string& part_name) {
544 if (IsMtdDeviceName(part_name)) {
545 int partition_num;
546 if (!SplitPartitionName(part_name, nullptr, &partition_num)) {
547 return "";
548 }
549 return MakeNandPartitionNameForMount(partition_num);
550 }
551 return part_name;
552}
553
Alex Deymof329b932014-10-30 01:37:48 -0700554string ErrnoNumberAsString(int err) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000555 char buf[100];
556 buf[0] = '\0';
557 return strerror_r(err, buf, sizeof(buf));
558}
559
adlr@google.com3defe6a2009-12-04 20:57:17 +0000560bool FileExists(const char* path) {
561 struct stat stbuf;
562 return 0 == lstat(path, &stbuf);
563}
564
Darin Petkov30291ed2010-11-12 10:23:06 -0800565bool IsSymlink(const char* path) {
566 struct stat stbuf;
567 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
568}
569
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800570bool TryAttachingUbiVolume(int volume_num, int timeout) {
571 const string volume_path = base::StringPrintf("/dev/ubi%d_0", volume_num);
572 if (FileExists(volume_path.c_str())) {
573 return true;
574 }
575
576 int exit_code;
577 vector<string> cmd = {
578 "ubiattach",
579 "-m",
580 base::StringPrintf("%d", volume_num),
581 "-d",
582 base::StringPrintf("%d", volume_num)
583 };
584 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
585 TEST_AND_RETURN_FALSE(exit_code == 0);
586
587 cmd = {
588 "ubiblock",
589 "--create",
590 volume_path
591 };
592 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
593 TEST_AND_RETURN_FALSE(exit_code == 0);
594
595 while (timeout > 0 && !FileExists(volume_path.c_str())) {
596 sleep(1);
597 timeout--;
598 }
599
600 return FileExists(volume_path.c_str());
601}
602
Alex Deymof329b932014-10-30 01:37:48 -0700603bool MakeTempFile(const string& base_filename_template,
604 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700605 int* fd) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700606 base::FilePath filename_template;
607 TEST_AND_RETURN_FALSE(
608 GetTempName(base_filename_template, &filename_template));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700609 DCHECK(filename || fd);
Alex Deymo5aa1c542015-09-18 01:02:33 -0700610 vector<char> buf(filename_template.value().size() + 1);
611 memcpy(buf.data(), filename_template.value().data(),
612 filename_template.value().size());
613 buf[filename_template.value().size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700614
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800615 int mkstemp_fd = mkstemp(buf.data());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700616 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
617 if (filename) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800618 *filename = buf.data();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700619 }
620 if (fd) {
621 *fd = mkstemp_fd;
622 } else {
623 close(mkstemp_fd);
624 }
625 return true;
626}
627
Alex Deymof329b932014-10-30 01:37:48 -0700628bool MakeTempDirectory(const string& base_dirname_template,
629 string* dirname) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700630 base::FilePath dirname_template;
631 TEST_AND_RETURN_FALSE(GetTempName(base_dirname_template, &dirname_template));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700632 DCHECK(dirname);
Alex Deymo5aa1c542015-09-18 01:02:33 -0700633 vector<char> buf(dirname_template.value().size() + 1);
634 memcpy(buf.data(), dirname_template.value().data(),
635 dirname_template.value().size());
636 buf[dirname_template.value().size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700637
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800638 char* return_code = mkdtemp(buf.data());
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700639 TEST_AND_RETURN_FALSE_ERRNO(return_code != nullptr);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800640 *dirname = buf.data();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700641 return true;
642}
643
adlr@google.com3defe6a2009-12-04 20:57:17 +0000644bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700645 const string& mountpoint,
Alex Deymo390efed2016-02-18 11:00:40 -0800646 unsigned long mountflags, // NOLINT(runtime/int)
Alex Deymo14dbd332016-03-01 18:55:54 -0800647 const string& type,
648 const string& fs_mount_options) {
Alex Deymo390efed2016-02-18 11:00:40 -0800649 vector<const char*> fstypes;
650 if (type.empty()) {
651 fstypes = {"ext2", "ext3", "ext4", "squashfs"};
652 } else {
653 fstypes = {type.c_str()};
654 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800655 for (const char* fstype : fstypes) {
656 int rc = mount(device.c_str(), mountpoint.c_str(), fstype, mountflags,
Alex Deymo14dbd332016-03-01 18:55:54 -0800657 fs_mount_options.c_str());
Alex Deymo4c82df32014-11-10 22:25:57 -0800658 if (rc == 0)
659 return true;
660
661 PLOG(WARNING) << "Unable to mount destination device " << device
662 << " on " << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000663 }
Alex Deymo390efed2016-02-18 11:00:40 -0800664 if (!type.empty()) {
665 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
666 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800667 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000668}
669
670bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700671 for (int num_retries = 0; ; ++num_retries) {
672 if (umount(mountpoint.c_str()) == 0)
673 break;
674
675 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
676 num_retries < kUnmountMaxNumOfRetries);
Alex Deymo8d2bbe32015-06-23 16:28:59 -0700677 usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700678 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000679 return true;
680}
681
Alex Deymof329b932014-10-30 01:37:48 -0700682bool GetFilesystemSize(const string& device,
Darin Petkovd3f8c892010-10-12 21:38:45 -0700683 int* out_block_count,
684 int* out_block_size) {
685 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
Alex Deymoe7141c62014-10-17 14:03:01 -0700686 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700687 ScopedFdCloser fd_closer(&fd);
688 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
689}
690
691bool GetFilesystemSizeFromFD(int fd,
692 int* out_block_count,
693 int* out_block_size) {
694 TEST_AND_RETURN_FALSE(fd >= 0);
695
Alex Deymo192393b2014-11-10 15:58:38 -0800696 // Determine the filesystem size by directly reading the block count and
697 // block size information from the superblock. Supported FS are ext3 and
698 // squashfs.
699
700 // Read from the fd only once and detect in memory. The first 2 KiB is enough
701 // to read the ext2 superblock (located at offset 1024) and the squashfs
702 // superblock (located at offset 0).
703 const ssize_t kBufferSize = 2048;
704
705 uint8_t buffer[kBufferSize];
706 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, 0)) != kBufferSize) {
707 PLOG(ERROR) << "Unable to read the file system header:";
Darin Petkovd3f8c892010-10-12 21:38:45 -0700708 return false;
709 }
Alex Deymo192393b2014-11-10 15:58:38 -0800710
711 if (GetSquashfs4Size(buffer, kBufferSize, out_block_count, out_block_size))
712 return true;
713 if (GetExt3Size(buffer, kBufferSize, out_block_count, out_block_size))
714 return true;
715
716 LOG(ERROR) << "Unable to determine file system type.";
717 return false;
718}
719
720bool GetExt3Size(const uint8_t* buffer, size_t buffer_size,
721 int* out_block_count,
722 int* out_block_size) {
723 // See include/linux/ext2_fs.h for more details on the structure. We obtain
724 // ext2 constants from ext2fs/ext2fs.h header but we don't link with the
725 // library.
726 if (buffer_size < SUPERBLOCK_OFFSET + SUPERBLOCK_SIZE)
727 return false;
728
729 const uint8_t* superblock = buffer + SUPERBLOCK_OFFSET;
730
731 // ext3_fs.h: ext3_super_block.s_blocks_count
732 uint32_t block_count =
733 *reinterpret_cast<const uint32_t*>(superblock + 1 * sizeof(int32_t));
734
735 // ext3_fs.h: ext3_super_block.s_log_block_size
736 uint32_t log_block_size =
737 *reinterpret_cast<const uint32_t*>(superblock + 6 * sizeof(int32_t));
738
739 // ext3_fs.h: ext3_super_block.s_magic
740 uint16_t magic =
741 *reinterpret_cast<const uint16_t*>(superblock + 14 * sizeof(int32_t));
742
Darin Petkovd3f8c892010-10-12 21:38:45 -0700743 block_count = le32toh(block_count);
Alex Deymo192393b2014-11-10 15:58:38 -0800744 log_block_size = le32toh(log_block_size) + EXT2_MIN_BLOCK_LOG_SIZE;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700745 magic = le16toh(magic);
746
747 // Sanity check the parameters.
Alex Deymo192393b2014-11-10 15:58:38 -0800748 TEST_AND_RETURN_FALSE(magic == EXT2_SUPER_MAGIC);
749 TEST_AND_RETURN_FALSE(log_block_size >= EXT2_MIN_BLOCK_LOG_SIZE &&
750 log_block_size <= EXT2_MAX_BLOCK_LOG_SIZE);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700751 TEST_AND_RETURN_FALSE(block_count > 0);
752
Alex Deymo192393b2014-11-10 15:58:38 -0800753 if (out_block_count)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700754 *out_block_count = block_count;
Alex Deymo192393b2014-11-10 15:58:38 -0800755 if (out_block_size)
756 *out_block_size = 1 << log_block_size;
757 return true;
758}
759
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800760bool GetSquashfs4Size(const uint8_t* buffer, size_t buffer_size,
Alex Deymo192393b2014-11-10 15:58:38 -0800761 int* out_block_count,
762 int* out_block_size) {
763 // See fs/squashfs/squashfs_fs.h for format details. We only support
764 // Squashfs 4.x little endian.
765
766 // sizeof(struct squashfs_super_block)
767 const size_t kSquashfsSuperBlockSize = 96;
768 if (buffer_size < kSquashfsSuperBlockSize)
769 return false;
770
771 // Check magic, squashfs_fs.h: SQUASHFS_MAGIC
772 if (memcmp(buffer, "hsqs", 4) != 0)
773 return false; // Only little endian is supported.
774
775 // squashfs_fs.h: struct squashfs_super_block.s_major
776 uint16_t s_major = *reinterpret_cast<const uint16_t*>(
777 buffer + 5 * sizeof(uint32_t) + 4 * sizeof(uint16_t));
778
779 if (s_major != 4) {
780 LOG(ERROR) << "Found unsupported squashfs major version " << s_major;
781 return false;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700782 }
Alex Deymo192393b2014-11-10 15:58:38 -0800783
784 // squashfs_fs.h: struct squashfs_super_block.bytes_used
785 uint64_t bytes_used = *reinterpret_cast<const int64_t*>(
786 buffer + 5 * sizeof(uint32_t) + 6 * sizeof(uint16_t) + sizeof(uint64_t));
787
788 const int block_size = 4096;
789
790 // The squashfs' bytes_used doesn't need to be aligned with the block boundary
791 // so we round up to the nearest blocksize.
792 if (out_block_count)
793 *out_block_count = (bytes_used + block_size - 1) / block_size;
794 if (out_block_size)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700795 *out_block_size = block_size;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700796 return true;
797}
798
Alex Deymo60ca1a72015-06-18 18:19:15 -0700799bool IsExtFilesystem(const string& device) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700800 brillo::Blob header;
Alex Deymode942f32015-03-13 11:57:15 -0700801 // The first 2 KiB is enough to read the ext2 superblock (located at offset
802 // 1024).
803 if (!ReadFileChunk(device, 0, 2048, &header))
804 return false;
805 return GetExt3Size(header.data(), header.size(), nullptr, nullptr);
806}
807
Alex Deymo60ca1a72015-06-18 18:19:15 -0700808bool IsSquashfsFilesystem(const string& device) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700809 brillo::Blob header;
Alex Deymode942f32015-03-13 11:57:15 -0700810 // The first 96 is enough to read the squashfs superblock.
811 const ssize_t kSquashfsSuperBlockSize = 96;
812 if (!ReadFileChunk(device, 0, kSquashfsSuperBlockSize, &header))
813 return false;
814 return GetSquashfs4Size(header.data(), header.size(), nullptr, nullptr);
815}
816
Alex Deymo032e7722014-03-25 17:53:56 -0700817// Tries to parse the header of an ELF file to obtain a human-readable
818// description of it on the |output| string.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800819static bool GetFileFormatELF(const uint8_t* buffer, size_t size,
820 string* output) {
Alex Deymo032e7722014-03-25 17:53:56 -0700821 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700822 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700823 return false;
824 *output = "ELF";
825
826 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700827 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700828 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700829 switch (buffer[EI_CLASS]) {
830 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700831 *output += " 32-bit";
832 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700833 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700834 *output += " 64-bit";
835 break;
836 default:
837 *output += " ?-bit";
838 }
839
840 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700841 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700842 return true;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800843 uint8_t ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700844 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700845 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700846 *output += " little-endian";
847 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700848 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700849 *output += " big-endian";
850 break;
851 default:
852 *output += " ?-endian";
853 // Don't parse anything after the 0x10 offset if endianness is unknown.
854 return true;
855 }
856
Alex Deymoc1711e22014-08-08 13:16:23 -0700857 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
858 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
859 // and size is the same for both 32 and 64 bits.
860 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700861 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700862 uint16_t e_machine;
Alex Deymo032e7722014-03-25 17:53:56 -0700863 // Fix endianess regardless of the host endianess.
Alex Deymoc1711e22014-08-08 13:16:23 -0700864 if (ei_data == ELFDATA2LSB)
865 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700866 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700867 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700868
869 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700870 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700871 *output += " x86";
872 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700873 case EM_MIPS:
874 *output += " mips";
875 break;
876 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700877 *output += " arm";
878 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700879 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700880 *output += " x86-64";
881 break;
882 default:
883 *output += " unknown-arch";
884 }
885 return true;
886}
887
888string GetFileFormat(const string& path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700889 brillo::Blob buffer;
Alex Deymo032e7722014-03-25 17:53:56 -0700890 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
891 return "File not found.";
892
893 string result;
894 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
895 return result;
896
897 return "data";
898}
899
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800900namespace {
901// Do the actual trigger. We do it as a main-loop callback to (try to) get a
902// consistent stack trace.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700903void TriggerCrashReporterUpload() {
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800904 pid_t pid = fork();
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700905 CHECK_GE(pid, 0) << "fork failed"; // fork() failed. Something is very wrong.
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800906 if (pid == 0) {
907 // We are the child. Crash.
908 abort(); // never returns
909 }
910 // We are the parent. Wait for child to terminate.
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700911 pid_t result = waitpid(pid, nullptr, 0);
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800912 LOG_IF(ERROR, result < 0) << "waitpid() failed";
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800913}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700914} // namespace
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800915
916void ScheduleCrashReporterUpload() {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700917 brillo::MessageLoop::current()->PostTask(
Alex Deymo60ca1a72015-06-18 18:19:15 -0700918 FROM_HERE,
919 base::Bind(&TriggerCrashReporterUpload));
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800920}
921
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700922int FuzzInt(int value, unsigned int range) {
923 int min = value - range / 2;
924 int max = value + range - range / 2;
925 return base::RandInt(min, max);
926}
927
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700928string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800929 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700930}
931
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800932string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400933 string str;
934
935 // Handle negative durations by prefixing with a minus.
936 if (delta.ToInternalValue() < 0) {
937 delta *= -1;
938 str = "-";
939 }
940
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700941 // Canonicalize into days, hours, minutes, seconds and microseconds.
942 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800943 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700944 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800945 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700946 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800947 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700948 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800949 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700950 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800951
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700952 if (days)
953 base::StringAppendF(&str, "%ud", days);
954 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800955 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700956 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800957 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700958 base::StringAppendF(&str, "%u", secs);
959 if (usecs) {
960 int width = 6;
961 while ((usecs / 10) * 10 == usecs) {
962 usecs /= 10;
963 width--;
964 }
965 base::StringAppendF(&str, ".%0*u", width, usecs);
966 }
967 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800968 return str;
969}
970
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700971string ToString(const Time utc_time) {
972 Time::Exploded exp_time;
973 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700974 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700975 exp_time.month,
976 exp_time.day_of_month,
977 exp_time.year,
978 exp_time.hour,
979 exp_time.minute,
980 exp_time.second);
981}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000982
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700983string ToString(bool b) {
984 return (b ? "true" : "false");
985}
986
Alex Deymo1c656c42013-06-28 11:02:14 -0700987string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700988 switch (source) {
989 case kDownloadSourceHttpsServer: return "HttpsServer";
990 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700991 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -0700992 case kNumDownloadSources: return "Unknown";
993 // Don't add a default case to let the compiler warn about newly added
994 // download sources which should be added here.
995 }
996
997 return "Unknown";
998}
999
Alex Deymo1c656c42013-06-28 11:02:14 -07001000string ToString(PayloadType payload_type) {
1001 switch (payload_type) {
1002 case kPayloadTypeDelta: return "Delta";
1003 case kPayloadTypeFull: return "Full";
1004 case kPayloadTypeForcedFull: return "ForcedFull";
1005 case kNumPayloadTypes: return "Unknown";
1006 // Don't add a default case to let the compiler warn about newly added
1007 // payload types which should be added here.
1008 }
1009
1010 return "Unknown";
1011}
1012
David Zeuthena99981f2013-04-29 13:42:47 -07001013ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -07001014 // Ignore the higher order bits in the code by applying the mask as
1015 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001016 // with values less than ErrorCode::kUmaReportedMax.
1017 ErrorCode base_code = static_cast<ErrorCode>(
1018 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -07001019
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001020 // Make additional adjustments required for UMA and error classification.
1021 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
1022 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001023 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -07001024 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001025 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001026 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001027 << " to ErrorCode::kOmahaErrorInHTTPResponse";
1028 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -07001029 }
1030
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001031 return base_code;
1032}
1033
Gilad Arnold30dedd82013-07-03 06:19:09 -07001034bool CreatePowerwashMarkerFile(const char* file_path) {
1035 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
1036 bool result = utils::WriteFile(marker_file,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001037 kPowerwashCommand,
1038 strlen(kPowerwashCommand));
Gilad Arnold30dedd82013-07-03 06:19:09 -07001039 if (result) {
1040 LOG(INFO) << "Created " << marker_file << " to powerwash on next reboot";
1041 } else {
1042 PLOG(ERROR) << "Error in creating powerwash marker file: " << marker_file;
1043 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001044
1045 return result;
1046}
1047
Gilad Arnold30dedd82013-07-03 06:19:09 -07001048bool DeletePowerwashMarkerFile(const char* file_path) {
1049 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
Alex Vakulenko75039d72014-03-25 12:36:28 -07001050 const base::FilePath kPowerwashMarkerPath(marker_file);
1051 bool result = base::DeleteFile(kPowerwashMarkerPath, false);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001052
1053 if (result)
1054 LOG(INFO) << "Successfully deleted the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001055 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001056 else
1057 PLOG(ERROR) << "Could not delete the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001058 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001059
1060 return result;
1061}
1062
David Zeuthen27a48bc2013-08-06 12:06:29 -07001063Time TimeFromStructTimespec(struct timespec *ts) {
Ben Chan9abb7632014-08-07 00:10:53 -07001064 int64_t us = static_cast<int64_t>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
1065 static_cast<int64_t>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
David Zeuthen27a48bc2013-08-06 12:06:29 -07001066 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
1067}
1068
Alex Deymof329b932014-10-30 01:37:48 -07001069string StringVectorToString(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -07001070 string str = "[";
Alex Deymof329b932014-10-30 01:37:48 -07001071 for (vector<string>::const_iterator i = vec_str.begin();
1072 i != vec_str.end(); ++i) {
1073 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -07001074 str += ", ";
1075 str += '"';
1076 str += *i;
1077 str += '"';
1078 }
1079 str += "]";
1080 return str;
1081}
1082
David Zeuthen8f191b22013-08-06 12:27:50 -07001083string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001084 string encoded_hash = brillo::data_encoding::Base64Encode(payload_hash);
Alex Deymoc00c98a2015-03-17 17:38:00 -07001085 return base::StringPrintf("cros_update_size_%" PRIuS "_hash_%s",
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001086 payload_size,
1087 encoded_hash.c_str());
David Zeuthen8f191b22013-08-06 12:27:50 -07001088}
1089
Alex Deymof329b932014-10-30 01:37:48 -07001090bool DecodeAndStoreBase64String(const string& base64_encoded,
David Zeuthene7f89172013-10-31 10:21:04 -07001091 base::FilePath *out_path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001092 brillo::Blob contents;
David Zeuthene7f89172013-10-31 10:21:04 -07001093
1094 out_path->clear();
1095
1096 if (base64_encoded.size() == 0) {
1097 LOG(ERROR) << "Can't decode empty string.";
1098 return false;
1099 }
1100
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001101 if (!brillo::data_encoding::Base64Decode(base64_encoded, &contents) ||
David Zeuthene7f89172013-10-31 10:21:04 -07001102 contents.size() == 0) {
1103 LOG(ERROR) << "Error decoding base64.";
1104 return false;
1105 }
1106
Alex Vakulenko75039d72014-03-25 12:36:28 -07001107 FILE *file = base::CreateAndOpenTemporaryFile(out_path);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001108 if (file == nullptr) {
David Zeuthene7f89172013-10-31 10:21:04 -07001109 LOG(ERROR) << "Error creating temporary file.";
1110 return false;
1111 }
1112
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001113 if (fwrite(contents.data(), 1, contents.size(), file) != contents.size()) {
David Zeuthene7f89172013-10-31 10:21:04 -07001114 PLOG(ERROR) << "Error writing to temporary file.";
1115 if (fclose(file) != 0)
1116 PLOG(ERROR) << "Error closing temporary file.";
1117 if (unlink(out_path->value().c_str()) != 0)
1118 PLOG(ERROR) << "Error unlinking temporary file.";
1119 out_path->clear();
1120 return false;
1121 }
1122
1123 if (fclose(file) != 0) {
1124 PLOG(ERROR) << "Error closing temporary file.";
1125 out_path->clear();
1126 return false;
1127 }
1128
1129 return true;
1130}
1131
Alex Deymof329b932014-10-30 01:37:48 -07001132bool ConvertToOmahaInstallDate(Time time, int *out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -08001133 time_t unix_time = time.ToTimeT();
1134 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
1135 const time_t kOmahaEpoch = 1167638400;
1136 const int64_t kNumSecondsPerWeek = 7*24*3600;
1137 const int64_t kNumDaysPerWeek = 7;
1138
1139 time_t omaha_time = unix_time - kOmahaEpoch;
1140
1141 if (omaha_time < 0)
1142 return false;
1143
1144 // Note, as per the comment in utils.h we are deliberately not
1145 // handling DST correctly.
1146
1147 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
1148 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
1149
1150 return true;
1151}
1152
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001153bool GetMinorVersion(const brillo::KeyValueStore& store,
Alex Deymob42b98d2015-07-06 17:42:38 -07001154 uint32_t* minor_version) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001155 string result;
Alex Deymob42b98d2015-07-06 17:42:38 -07001156 if (store.GetString("PAYLOAD_MINOR_VERSION", &result)) {
Allie Wood425aa972015-02-17 14:47:17 -08001157 if (!base::StringToUint(result, minor_version)) {
1158 LOG(ERROR) << "StringToUint failed when parsing delta minor version.";
1159 return false;
1160 }
Allie Wood78750a42015-02-11 15:42:11 -08001161 return true;
1162 }
1163 return false;
1164}
1165
Sen Jiang3a92aa22016-03-01 14:22:52 -08001166bool IsZlibCompatible(const string& fingerprint) {
1167 if (fingerprint.size() != sizeof(kCompatibleZlibFingerprint[0]) - 1) {
1168 LOG(ERROR) << "Invalid fingerprint: " << fingerprint;
1169 return false;
1170 }
1171 for (auto& f : kCompatibleZlibFingerprint) {
1172 if (base::CompareCaseInsensitiveASCII(fingerprint, f) == 0) {
1173 return true;
1174 }
1175 }
1176 return false;
1177}
1178
Alex Deymo60ca1a72015-06-18 18:19:15 -07001179bool ReadExtents(const string& path, const vector<Extent>& extents,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001180 brillo::Blob* out_data, ssize_t out_data_size,
Allie Wood56873452015-03-27 17:48:40 -07001181 size_t block_size) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001182 brillo::Blob data(out_data_size);
Allie Wood56873452015-03-27 17:48:40 -07001183 ssize_t bytes_read = 0;
1184 int fd = open(path.c_str(), O_RDONLY);
1185 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
1186 ScopedFdCloser fd_closer(&fd);
1187
Gilad Arnold41e34742015-05-11 11:31:50 -07001188 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -07001189 ssize_t bytes_read_this_iteration = 0;
1190 ssize_t bytes = extent.num_blocks() * block_size;
1191 TEST_AND_RETURN_FALSE(bytes_read + bytes <= out_data_size);
1192 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
1193 &data[bytes_read],
1194 bytes,
1195 extent.start_block() * block_size,
1196 &bytes_read_this_iteration));
1197 TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes);
1198 bytes_read += bytes_read_this_iteration;
1199 }
1200 TEST_AND_RETURN_FALSE(out_data_size == bytes_read);
1201 *out_data = data;
1202 return true;
1203}
1204
Alex Deymodd132f32015-09-14 19:12:07 -07001205bool GetBootId(string* boot_id) {
1206 TEST_AND_RETURN_FALSE(
1207 base::ReadFileToString(base::FilePath(kBootIdPath), boot_id));
1208 base::TrimWhitespaceASCII(*boot_id, base::TRIM_TRAILING, boot_id);
1209 return true;
1210}
1211
adlr@google.com3defe6a2009-12-04 20:57:17 +00001212} // namespace utils
1213
1214} // namespace chromeos_update_engine