blob: 166cfb4947903e24196504fd10dc0e7df859f4ff [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
Alex Deymo9629bbc2016-08-10 17:02:49 -070090// A pointer to a null-terminated string containing the root directory where all
91// the temporary files should be created. If null, the system default is used
92// instead.
93const char* root_temp_dir = nullptr;
94
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080095// Return true if |disk_name| is an MTD or a UBI device. Note that this test is
96// simply based on the name of the device.
97bool IsMtdDeviceName(const string& disk_name) {
Alex Vakulenko0103c362016-01-20 07:56:15 -080098 return base::StartsWith(disk_name, "/dev/ubi",
99 base::CompareCase::SENSITIVE) ||
100 base::StartsWith(disk_name, "/dev/mtd", base::CompareCase::SENSITIVE);
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800101}
102
103// Return the device name for the corresponding partition on a NAND device.
104// WARNING: This function returns device names that are not mountable.
105string MakeNandPartitionName(int partition_num) {
106 switch (partition_num) {
107 case 2:
108 case 4:
109 case 6: {
110 return base::StringPrintf("/dev/mtd%d", partition_num);
111 }
112 default: {
113 return base::StringPrintf("/dev/ubi%d_0", partition_num);
114 }
115 }
116}
117
118// Return the device name for the corresponding partition on a NAND device that
119// may be mountable (but may not be writable).
120string MakeNandPartitionNameForMount(int partition_num) {
121 switch (partition_num) {
122 case 2:
123 case 4:
124 case 6: {
125 return base::StringPrintf("/dev/mtd%d", partition_num);
126 }
127 case 3:
128 case 5:
129 case 7: {
130 return base::StringPrintf("/dev/ubiblock%d_0", partition_num);
131 }
132 default: {
133 return base::StringPrintf("/dev/ubi%d_0", partition_num);
134 }
135 }
136}
137
Alex Deymo5aa1c542015-09-18 01:02:33 -0700138// If |path| is absolute, or explicit relative to the current working directory,
139// leaves it as is. Otherwise, uses the system's temp directory, as defined by
140// base::GetTempDir() and prepends it to |path|. On success stores the full
141// temporary path in |template_path| and returns true.
142bool GetTempName(const string& path, base::FilePath* template_path) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800143 if (path[0] == '/' ||
144 base::StartsWith(path, "./", base::CompareCase::SENSITIVE) ||
145 base::StartsWith(path, "../", base::CompareCase::SENSITIVE)) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700146 *template_path = base::FilePath(path);
147 return true;
148 }
149
150 base::FilePath temp_dir;
Alex Deymo9629bbc2016-08-10 17:02:49 -0700151 if (root_temp_dir) {
152 temp_dir = base::FilePath(root_temp_dir);
153 } else {
Sen Jiang9c123462015-11-19 13:16:23 -0800154#ifdef __ANDROID__
Alex Deymo9629bbc2016-08-10 17:02:49 -0700155 temp_dir = base::FilePath(constants::kNonVolatileDirectory).Append("tmp");
156#else
157 TEST_AND_RETURN_FALSE(base::GetTempDir(&temp_dir));
158#endif // __ANDROID__
159 }
Sen Jiang9c123462015-11-19 13:16:23 -0800160 if (!base::PathExists(temp_dir))
161 TEST_AND_RETURN_FALSE(base::CreateDirectory(temp_dir));
Alex Deymo5aa1c542015-09-18 01:02:33 -0700162 *template_path = temp_dir.Append(path);
163 return true;
164}
165
Ben Chan77a1eba2012-10-07 22:54:55 -0700166} // namespace
167
adlr@google.com3defe6a2009-12-04 20:57:17 +0000168namespace utils {
169
Alex Deymo9629bbc2016-08-10 17:02:49 -0700170void SetRootTempDir(const char* new_root_temp_dir) {
171 root_temp_dir = new_root_temp_dir;
172}
173
J. Richard Barnette63137e52013-10-28 10:57:29 -0700174string ParseECVersion(string input_line) {
Ben Chan736fcb52014-05-21 18:28:22 -0700175 base::TrimWhitespaceASCII(input_line, base::TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -0700176
Alex Vakulenko75039d72014-03-25 12:36:28 -0700177 // At this point we want to convert the format key=value pair from mosys to
Chris Sosac1972482013-04-30 22:31:10 -0700178 // a vector of key value pairs.
Ben Chanf9cb98c2014-09-21 18:31:30 -0700179 vector<pair<string, string>> kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -0700180 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Alex Deymo020600d2014-11-05 21:05:55 -0800181 for (const pair<string, string>& kv_pair : kv_pairs) {
Chris Sosac1972482013-04-30 22:31:10 -0700182 // Finally match against the fw_verion which may have quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800183 if (kv_pair.first == "fw_version") {
Chris Sosac1972482013-04-30 22:31:10 -0700184 string output;
185 // Trim any quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800186 base::TrimString(kv_pair.second, "\"", &output);
Chris Sosac1972482013-04-30 22:31:10 -0700187 return output;
188 }
189 }
190 }
191 LOG(ERROR) << "Unable to parse fwid from ec info.";
192 return "";
193}
194
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800195bool WriteFile(const char* path, const void* data, int data_len) {
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800196 DirectFileWriter writer;
197 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
198 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700199 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800200 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800201 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800202 return true;
203}
204
Alex Deymo72ea95a2016-03-30 18:31:49 -0700205bool ReadAll(
206 int fd, void* buf, size_t count, size_t* out_bytes_read, bool* eof) {
207 char* c_buf = static_cast<char*>(buf);
208 size_t bytes_read = 0;
209 *eof = false;
210 while (bytes_read < count) {
211 ssize_t rc = HANDLE_EINTR(read(fd, c_buf + bytes_read, count - bytes_read));
212 if (rc < 0) {
213 // EAGAIN and EWOULDBLOCK are normal return values when there's no more
214 // input and we are in non-blocking mode.
215 if (errno != EWOULDBLOCK && errno != EAGAIN) {
216 PLOG(ERROR) << "Error reading fd " << fd;
217 *out_bytes_read = bytes_read;
218 return false;
219 }
220 break;
221 } else if (rc == 0) {
222 // A value of 0 means that we reached EOF and there is nothing else to
223 // read from this fd.
224 *eof = true;
225 break;
226 } else {
227 bytes_read += rc;
228 }
229 }
230 *out_bytes_read = bytes_read;
231 return true;
232}
233
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700234bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700235 const char* c_buf = static_cast<const char*>(buf);
236 ssize_t bytes_written = 0;
237 while (bytes_written < static_cast<ssize_t>(count)) {
238 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
239 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
240 bytes_written += rc;
241 }
242 return true;
243}
244
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700245bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
246 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700247 size_t bytes_written = 0;
248 int num_attempts = 0;
249 while (bytes_written < count) {
250 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700251 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
252 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700253 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
254 if (rc < 0) {
255 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
256 << " bytes_written=" << bytes_written
257 << " count=" << count << " offset=" << offset;
258 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700259 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
260 bytes_written += rc;
261 }
262 return true;
263}
264
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800265bool WriteAll(FileDescriptorPtr fd, const void* buf, size_t count) {
266 const char* c_buf = static_cast<const char*>(buf);
267 ssize_t bytes_written = 0;
268 while (bytes_written < static_cast<ssize_t>(count)) {
269 ssize_t rc = fd->Write(c_buf + bytes_written, count - bytes_written);
270 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
271 bytes_written += rc;
272 }
273 return true;
274}
275
276bool PWriteAll(FileDescriptorPtr fd,
277 const void* buf,
278 size_t count,
279 off_t offset) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700280 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
281 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800282 return WriteAll(fd, buf, count);
283}
284
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700285bool PReadAll(int fd, void* buf, size_t count, off_t offset,
286 ssize_t* out_bytes_read) {
287 char* c_buf = static_cast<char*>(buf);
288 ssize_t bytes_read = 0;
289 while (bytes_read < static_cast<ssize_t>(count)) {
290 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
291 offset + bytes_read);
292 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
293 if (rc == 0) {
294 break;
295 }
296 bytes_read += rc;
297 }
298 *out_bytes_read = bytes_read;
299 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700300}
301
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800302bool PReadAll(FileDescriptorPtr fd, void* buf, size_t count, off_t offset,
303 ssize_t* out_bytes_read) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700304 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
305 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800306 char* c_buf = static_cast<char*>(buf);
307 ssize_t bytes_read = 0;
308 while (bytes_read < static_cast<ssize_t>(count)) {
309 ssize_t rc = fd->Read(c_buf + bytes_read, count - bytes_read);
310 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
311 if (rc == 0) {
312 break;
313 }
314 bytes_read += rc;
315 }
316 *out_bytes_read = bytes_read;
317 return true;
318}
319
Gilad Arnold19a45f02012-07-19 12:36:10 -0700320// Append |nbytes| of content from |buf| to the vector pointed to by either
321// |vec_p| or |str_p|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800322static void AppendBytes(const uint8_t* buf, size_t nbytes,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700323 brillo::Blob* vec_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700324 CHECK(buf);
325 CHECK(vec_p);
326 vec_p->insert(vec_p->end(), buf, buf + nbytes);
327}
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800328static void AppendBytes(const uint8_t* buf, size_t nbytes,
Alex Deymof329b932014-10-30 01:37:48 -0700329 string* str_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700330 CHECK(buf);
331 CHECK(str_p);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800332 str_p->append(buf, buf + nbytes);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700333}
334
335// Reads from an open file |fp|, appending the read content to the container
336// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200337// file's content, false otherwise. If |size| is not -1, reads up to |size|
338// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700339template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200340static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700341 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200342 CHECK(size == -1 || size >= 0);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800343 uint8_t buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200344 while (size == -1 || size > 0) {
345 off_t bytes_to_read = sizeof(buf);
346 if (size > 0 && bytes_to_read > size) {
347 bytes_to_read = size;
348 }
349 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
350 if (!nbytes) {
351 break;
352 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700353 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200354 if (size != -1) {
355 CHECK(size >= static_cast<off_t>(nbytes));
356 size -= nbytes;
357 }
358 }
359 if (ferror(fp)) {
360 return false;
361 }
362 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700363}
364
Darin Petkov8e447e02013-04-16 16:23:50 +0200365// Opens a file |path| for reading and appends its the contents to a container
366// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
367// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700368template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700369static bool ReadFileChunkAndAppend(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200370 off_t offset,
371 off_t size,
372 T* out_p) {
373 CHECK_GE(offset, 0);
374 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700375 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200376 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000377 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200378 if (offset) {
379 // Return success without appending any data if a chunk beyond the end of
380 // the file is requested.
381 if (offset >= FileSize(path)) {
382 return true;
383 }
384 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
385 }
386 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000387}
388
Alex Deymo10875d92014-11-10 21:52:57 -0800389// TODO(deymo): This is only used in unittest, but requires the private
390// Read<string>() defined here. Expose Read<string>() or move to base/ version.
391bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700392 FILE* fp = popen(cmd.c_str(), "r");
393 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000394 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200395 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700396 return (success && pclose(fp) >= 0);
397}
398
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700399bool ReadFile(const string& path, brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200400 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700401}
402
Darin Petkov8e447e02013-04-16 16:23:50 +0200403bool ReadFile(const string& path, string* out_p) {
404 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700405}
406
Darin Petkov8e447e02013-04-16 16:23:50 +0200407bool ReadFileChunk(const string& path, off_t offset, off_t size,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700408 brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200409 return ReadFileChunkAndAppend(path, offset, size, out_p);
410}
411
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700412off_t BlockDevSize(int fd) {
413 uint64_t dev_size;
414 int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
415 if (rc == -1) {
416 dev_size = -1;
417 PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
418 }
419 return dev_size;
420}
421
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700422off_t FileSize(int fd) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700423 struct stat stbuf;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700424 int rc = fstat(fd, &stbuf);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700425 CHECK_EQ(rc, 0);
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700426 if (rc < 0) {
427 PLOG(ERROR) << "Error stat-ing " << fd;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700428 return rc;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700429 }
430 if (S_ISREG(stbuf.st_mode))
431 return stbuf.st_size;
432 if (S_ISBLK(stbuf.st_mode))
433 return BlockDevSize(fd);
434 LOG(ERROR) << "Couldn't determine the type of " << fd;
435 return -1;
436}
437
438off_t FileSize(const string& path) {
439 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
440 if (fd == -1) {
441 PLOG(ERROR) << "Error opening " << path;
442 return fd;
443 }
444 off_t size = FileSize(fd);
445 if (size == -1)
446 PLOG(ERROR) << "Error getting file size of " << path;
447 close(fd);
448 return size;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700449}
450
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800451void HexDumpArray(const uint8_t* const arr, const size_t length) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000452 LOG(INFO) << "Logging array of length: " << length;
453 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700454 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000455 const unsigned int bytes_remaining = length - i;
456 const unsigned int bytes_per_this_line = min(bytes_per_line,
457 bytes_remaining);
458 char header[100];
459 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
460 TEST_AND_RETURN(r == 13);
461 string line = header;
462 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
463 char buf[20];
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800464 uint8_t c = arr[i + j];
adlr@google.com3defe6a2009-12-04 20:57:17 +0000465 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
466 TEST_AND_RETURN(r == 3);
467 line += buf;
468 }
469 LOG(INFO) << line;
470 }
471}
472
Alex Deymof329b932014-10-30 01:37:48 -0700473bool SplitPartitionName(const string& partition_name,
474 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800475 int* out_partition_num) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800476 if (!base::StartsWith(partition_name, "/dev/",
477 base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800478 LOG(ERROR) << "Invalid partition device name: " << partition_name;
479 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700480 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800481
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700482 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
483 if (last_nondigit_pos == string::npos ||
484 (last_nondigit_pos + 1) == partition_name.size()) {
485 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800486 return false;
487 }
488
Alex Deymof329b932014-10-30 01:37:48 -0700489 size_t partition_name_len = string::npos;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700490 if (partition_name[last_nondigit_pos] == '_') {
491 // NAND block devices have weird naming which could be something
492 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
493 size_t prev_nondigit_pos =
494 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
495 if (prev_nondigit_pos == string::npos ||
496 (prev_nondigit_pos + 1) == last_nondigit_pos) {
497 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
498 return false;
499 }
500
501 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
502 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800503 }
504
505 if (out_disk_name) {
506 // Special case for MMC devices which have the following naming scheme:
507 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700508 size_t disk_name_len = last_nondigit_pos;
509 if (partition_name[last_nondigit_pos] != 'p' ||
510 last_nondigit_pos == 0 ||
511 !isdigit(partition_name[last_nondigit_pos - 1])) {
512 disk_name_len++;
513 }
514 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800515 }
516
517 if (out_partition_num) {
Alex Deymof329b932014-10-30 01:37:48 -0700518 string partition_str = partition_name.substr(last_nondigit_pos + 1,
519 partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800520 *out_partition_num = atoi(partition_str.c_str());
521 }
522 return true;
523}
524
Alex Deymof329b932014-10-30 01:37:48 -0700525string MakePartitionName(const string& disk_name, int partition_num) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800526 if (partition_num < 1) {
527 LOG(ERROR) << "Invalid partition number: " << partition_num;
528 return string();
529 }
530
Alex Vakulenko0103c362016-01-20 07:56:15 -0800531 if (!base::StartsWith(disk_name, "/dev/", base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800532 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700533 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800534 }
535
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800536 if (IsMtdDeviceName(disk_name)) {
537 // Special case for UBI block devices.
538 // 1. ubiblock is not writable, we need to use plain "ubi".
539 // 2. There is a "_0" suffix.
540 return MakeNandPartitionName(partition_num);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800541 }
542
Alex Deymof329b932014-10-30 01:37:48 -0700543 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700544 if (isdigit(partition_name.back())) {
545 // Special case for devices with names ending with a digit.
546 // Add "p" to separate the disk name from partition number,
547 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800548 partition_name += 'p';
549 }
550
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700551 partition_name += std::to_string(partition_num);
552
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800553 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700554}
555
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800556string MakePartitionNameForMount(const string& part_name) {
557 if (IsMtdDeviceName(part_name)) {
558 int partition_num;
559 if (!SplitPartitionName(part_name, nullptr, &partition_num)) {
560 return "";
561 }
562 return MakeNandPartitionNameForMount(partition_num);
563 }
564 return part_name;
565}
566
Alex Deymof329b932014-10-30 01:37:48 -0700567string ErrnoNumberAsString(int err) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000568 char buf[100];
569 buf[0] = '\0';
570 return strerror_r(err, buf, sizeof(buf));
571}
572
adlr@google.com3defe6a2009-12-04 20:57:17 +0000573bool FileExists(const char* path) {
574 struct stat stbuf;
575 return 0 == lstat(path, &stbuf);
576}
577
Darin Petkov30291ed2010-11-12 10:23:06 -0800578bool IsSymlink(const char* path) {
579 struct stat stbuf;
580 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
581}
582
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800583bool TryAttachingUbiVolume(int volume_num, int timeout) {
584 const string volume_path = base::StringPrintf("/dev/ubi%d_0", volume_num);
585 if (FileExists(volume_path.c_str())) {
586 return true;
587 }
588
589 int exit_code;
590 vector<string> cmd = {
591 "ubiattach",
592 "-m",
593 base::StringPrintf("%d", volume_num),
594 "-d",
595 base::StringPrintf("%d", volume_num)
596 };
597 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
598 TEST_AND_RETURN_FALSE(exit_code == 0);
599
600 cmd = {
601 "ubiblock",
602 "--create",
603 volume_path
604 };
605 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
606 TEST_AND_RETURN_FALSE(exit_code == 0);
607
608 while (timeout > 0 && !FileExists(volume_path.c_str())) {
609 sleep(1);
610 timeout--;
611 }
612
613 return FileExists(volume_path.c_str());
614}
615
Alex Deymof329b932014-10-30 01:37:48 -0700616bool MakeTempFile(const string& base_filename_template,
617 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700618 int* fd) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700619 base::FilePath filename_template;
620 TEST_AND_RETURN_FALSE(
621 GetTempName(base_filename_template, &filename_template));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700622 DCHECK(filename || fd);
Alex Deymo5aa1c542015-09-18 01:02:33 -0700623 vector<char> buf(filename_template.value().size() + 1);
624 memcpy(buf.data(), filename_template.value().data(),
625 filename_template.value().size());
626 buf[filename_template.value().size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700627
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800628 int mkstemp_fd = mkstemp(buf.data());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700629 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
630 if (filename) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800631 *filename = buf.data();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700632 }
633 if (fd) {
634 *fd = mkstemp_fd;
635 } else {
636 close(mkstemp_fd);
637 }
638 return true;
639}
640
Alex Deymof329b932014-10-30 01:37:48 -0700641bool MakeTempDirectory(const string& base_dirname_template,
642 string* dirname) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700643 base::FilePath dirname_template;
644 TEST_AND_RETURN_FALSE(GetTempName(base_dirname_template, &dirname_template));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700645 DCHECK(dirname);
Alex Deymo5aa1c542015-09-18 01:02:33 -0700646 vector<char> buf(dirname_template.value().size() + 1);
647 memcpy(buf.data(), dirname_template.value().data(),
648 dirname_template.value().size());
649 buf[dirname_template.value().size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700650
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800651 char* return_code = mkdtemp(buf.data());
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700652 TEST_AND_RETURN_FALSE_ERRNO(return_code != nullptr);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800653 *dirname = buf.data();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700654 return true;
655}
656
Alex Deymo2e1de4f2016-03-25 18:48:22 -0700657bool SetBlockDeviceReadOnly(const string& device, bool read_only) {
658 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY | O_CLOEXEC));
659 if (fd < 0) {
660 PLOG(ERROR) << "Opening block device " << device;
661 return false;
662 }
663 ScopedFdCloser fd_closer(&fd);
664 // We take no action if not needed.
665 int read_only_flag;
666 int expected_flag = read_only ? 1 : 0;
667 int rc = ioctl(fd, BLKROGET, &read_only_flag);
668 // In case of failure reading the setting we will try to set it anyway.
669 if (rc == 0 && read_only_flag == expected_flag)
670 return true;
671
672 rc = ioctl(fd, BLKROSET, &expected_flag);
673 if (rc != 0) {
674 PLOG(ERROR) << "Marking block device " << device << " as read_only="
675 << expected_flag;
676 return false;
677 }
678 return true;
679}
680
adlr@google.com3defe6a2009-12-04 20:57:17 +0000681bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700682 const string& mountpoint,
Alex Deymo390efed2016-02-18 11:00:40 -0800683 unsigned long mountflags, // NOLINT(runtime/int)
Alex Deymo14dbd332016-03-01 18:55:54 -0800684 const string& type,
685 const string& fs_mount_options) {
Alex Deymo390efed2016-02-18 11:00:40 -0800686 vector<const char*> fstypes;
687 if (type.empty()) {
688 fstypes = {"ext2", "ext3", "ext4", "squashfs"};
689 } else {
690 fstypes = {type.c_str()};
691 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800692 for (const char* fstype : fstypes) {
693 int rc = mount(device.c_str(), mountpoint.c_str(), fstype, mountflags,
Alex Deymo14dbd332016-03-01 18:55:54 -0800694 fs_mount_options.c_str());
Alex Deymo4c82df32014-11-10 22:25:57 -0800695 if (rc == 0)
696 return true;
697
698 PLOG(WARNING) << "Unable to mount destination device " << device
699 << " on " << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000700 }
Alex Deymo390efed2016-02-18 11:00:40 -0800701 if (!type.empty()) {
702 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
703 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800704 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000705}
706
707bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700708 for (int num_retries = 0; ; ++num_retries) {
709 if (umount(mountpoint.c_str()) == 0)
710 break;
711
712 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
713 num_retries < kUnmountMaxNumOfRetries);
Alex Deymo8d2bbe32015-06-23 16:28:59 -0700714 usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700715 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000716 return true;
717}
718
Alex Deymof329b932014-10-30 01:37:48 -0700719bool GetFilesystemSize(const string& device,
Darin Petkovd3f8c892010-10-12 21:38:45 -0700720 int* out_block_count,
721 int* out_block_size) {
722 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
Alex Deymoe7141c62014-10-17 14:03:01 -0700723 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700724 ScopedFdCloser fd_closer(&fd);
725 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
726}
727
728bool GetFilesystemSizeFromFD(int fd,
729 int* out_block_count,
730 int* out_block_size) {
731 TEST_AND_RETURN_FALSE(fd >= 0);
732
Alex Deymo192393b2014-11-10 15:58:38 -0800733 // Determine the filesystem size by directly reading the block count and
734 // block size information from the superblock. Supported FS are ext3 and
735 // squashfs.
736
737 // Read from the fd only once and detect in memory. The first 2 KiB is enough
738 // to read the ext2 superblock (located at offset 1024) and the squashfs
739 // superblock (located at offset 0).
740 const ssize_t kBufferSize = 2048;
741
742 uint8_t buffer[kBufferSize];
743 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, 0)) != kBufferSize) {
744 PLOG(ERROR) << "Unable to read the file system header:";
Darin Petkovd3f8c892010-10-12 21:38:45 -0700745 return false;
746 }
Alex Deymo192393b2014-11-10 15:58:38 -0800747
748 if (GetSquashfs4Size(buffer, kBufferSize, out_block_count, out_block_size))
749 return true;
750 if (GetExt3Size(buffer, kBufferSize, out_block_count, out_block_size))
751 return true;
752
753 LOG(ERROR) << "Unable to determine file system type.";
754 return false;
755}
756
757bool GetExt3Size(const uint8_t* buffer, size_t buffer_size,
758 int* out_block_count,
759 int* out_block_size) {
760 // See include/linux/ext2_fs.h for more details on the structure. We obtain
761 // ext2 constants from ext2fs/ext2fs.h header but we don't link with the
762 // library.
763 if (buffer_size < SUPERBLOCK_OFFSET + SUPERBLOCK_SIZE)
764 return false;
765
766 const uint8_t* superblock = buffer + SUPERBLOCK_OFFSET;
767
768 // ext3_fs.h: ext3_super_block.s_blocks_count
769 uint32_t block_count =
770 *reinterpret_cast<const uint32_t*>(superblock + 1 * sizeof(int32_t));
771
772 // ext3_fs.h: ext3_super_block.s_log_block_size
773 uint32_t log_block_size =
774 *reinterpret_cast<const uint32_t*>(superblock + 6 * sizeof(int32_t));
775
776 // ext3_fs.h: ext3_super_block.s_magic
777 uint16_t magic =
778 *reinterpret_cast<const uint16_t*>(superblock + 14 * sizeof(int32_t));
779
Darin Petkovd3f8c892010-10-12 21:38:45 -0700780 block_count = le32toh(block_count);
Alex Deymo192393b2014-11-10 15:58:38 -0800781 log_block_size = le32toh(log_block_size) + EXT2_MIN_BLOCK_LOG_SIZE;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700782 magic = le16toh(magic);
783
784 // Sanity check the parameters.
Alex Deymo192393b2014-11-10 15:58:38 -0800785 TEST_AND_RETURN_FALSE(magic == EXT2_SUPER_MAGIC);
786 TEST_AND_RETURN_FALSE(log_block_size >= EXT2_MIN_BLOCK_LOG_SIZE &&
787 log_block_size <= EXT2_MAX_BLOCK_LOG_SIZE);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700788 TEST_AND_RETURN_FALSE(block_count > 0);
789
Alex Deymo192393b2014-11-10 15:58:38 -0800790 if (out_block_count)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700791 *out_block_count = block_count;
Alex Deymo192393b2014-11-10 15:58:38 -0800792 if (out_block_size)
793 *out_block_size = 1 << log_block_size;
794 return true;
795}
796
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800797bool GetSquashfs4Size(const uint8_t* buffer, size_t buffer_size,
Alex Deymo192393b2014-11-10 15:58:38 -0800798 int* out_block_count,
799 int* out_block_size) {
800 // See fs/squashfs/squashfs_fs.h for format details. We only support
801 // Squashfs 4.x little endian.
802
803 // sizeof(struct squashfs_super_block)
804 const size_t kSquashfsSuperBlockSize = 96;
805 if (buffer_size < kSquashfsSuperBlockSize)
806 return false;
807
808 // Check magic, squashfs_fs.h: SQUASHFS_MAGIC
809 if (memcmp(buffer, "hsqs", 4) != 0)
810 return false; // Only little endian is supported.
811
812 // squashfs_fs.h: struct squashfs_super_block.s_major
813 uint16_t s_major = *reinterpret_cast<const uint16_t*>(
814 buffer + 5 * sizeof(uint32_t) + 4 * sizeof(uint16_t));
815
816 if (s_major != 4) {
817 LOG(ERROR) << "Found unsupported squashfs major version " << s_major;
818 return false;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700819 }
Alex Deymo192393b2014-11-10 15:58:38 -0800820
821 // squashfs_fs.h: struct squashfs_super_block.bytes_used
822 uint64_t bytes_used = *reinterpret_cast<const int64_t*>(
823 buffer + 5 * sizeof(uint32_t) + 6 * sizeof(uint16_t) + sizeof(uint64_t));
824
825 const int block_size = 4096;
826
827 // The squashfs' bytes_used doesn't need to be aligned with the block boundary
828 // so we round up to the nearest blocksize.
829 if (out_block_count)
830 *out_block_count = (bytes_used + block_size - 1) / block_size;
831 if (out_block_size)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700832 *out_block_size = block_size;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700833 return true;
834}
835
Alex Deymo60ca1a72015-06-18 18:19:15 -0700836bool IsExtFilesystem(const string& device) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700837 brillo::Blob header;
Alex Deymode942f32015-03-13 11:57:15 -0700838 // The first 2 KiB is enough to read the ext2 superblock (located at offset
839 // 1024).
840 if (!ReadFileChunk(device, 0, 2048, &header))
841 return false;
842 return GetExt3Size(header.data(), header.size(), nullptr, nullptr);
843}
844
Alex Deymo60ca1a72015-06-18 18:19:15 -0700845bool IsSquashfsFilesystem(const string& device) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700846 brillo::Blob header;
Alex Deymode942f32015-03-13 11:57:15 -0700847 // The first 96 is enough to read the squashfs superblock.
848 const ssize_t kSquashfsSuperBlockSize = 96;
849 if (!ReadFileChunk(device, 0, kSquashfsSuperBlockSize, &header))
850 return false;
851 return GetSquashfs4Size(header.data(), header.size(), nullptr, nullptr);
852}
853
Alex Deymo032e7722014-03-25 17:53:56 -0700854// Tries to parse the header of an ELF file to obtain a human-readable
855// description of it on the |output| string.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800856static bool GetFileFormatELF(const uint8_t* buffer, size_t size,
857 string* output) {
Alex Deymo032e7722014-03-25 17:53:56 -0700858 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700859 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700860 return false;
861 *output = "ELF";
862
863 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700864 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700865 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700866 switch (buffer[EI_CLASS]) {
867 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700868 *output += " 32-bit";
869 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700870 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700871 *output += " 64-bit";
872 break;
873 default:
874 *output += " ?-bit";
875 }
876
877 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700878 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700879 return true;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800880 uint8_t ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700881 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700882 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700883 *output += " little-endian";
884 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700885 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700886 *output += " big-endian";
887 break;
888 default:
889 *output += " ?-endian";
890 // Don't parse anything after the 0x10 offset if endianness is unknown.
891 return true;
892 }
893
Alex Deymoc1711e22014-08-08 13:16:23 -0700894 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
895 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
896 // and size is the same for both 32 and 64 bits.
897 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700898 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700899 uint16_t e_machine;
Alex Deymo032e7722014-03-25 17:53:56 -0700900 // Fix endianess regardless of the host endianess.
Alex Deymoc1711e22014-08-08 13:16:23 -0700901 if (ei_data == ELFDATA2LSB)
902 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700903 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700904 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700905
906 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700907 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700908 *output += " x86";
909 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700910 case EM_MIPS:
911 *output += " mips";
912 break;
913 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700914 *output += " arm";
915 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700916 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700917 *output += " x86-64";
918 break;
919 default:
920 *output += " unknown-arch";
921 }
922 return true;
923}
924
925string GetFileFormat(const string& path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700926 brillo::Blob buffer;
Alex Deymo032e7722014-03-25 17:53:56 -0700927 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
928 return "File not found.";
929
930 string result;
931 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
932 return result;
933
934 return "data";
935}
936
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800937namespace {
938// Do the actual trigger. We do it as a main-loop callback to (try to) get a
939// consistent stack trace.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700940void TriggerCrashReporterUpload() {
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800941 pid_t pid = fork();
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700942 CHECK_GE(pid, 0) << "fork failed"; // fork() failed. Something is very wrong.
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800943 if (pid == 0) {
944 // We are the child. Crash.
945 abort(); // never returns
946 }
947 // We are the parent. Wait for child to terminate.
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700948 pid_t result = waitpid(pid, nullptr, 0);
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800949 LOG_IF(ERROR, result < 0) << "waitpid() failed";
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800950}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700951} // namespace
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800952
953void ScheduleCrashReporterUpload() {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700954 brillo::MessageLoop::current()->PostTask(
Alex Deymo60ca1a72015-06-18 18:19:15 -0700955 FROM_HERE,
956 base::Bind(&TriggerCrashReporterUpload));
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800957}
958
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700959int FuzzInt(int value, unsigned int range) {
960 int min = value - range / 2;
961 int max = value + range - range / 2;
962 return base::RandInt(min, max);
963}
964
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700965string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800966 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700967}
968
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800969string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400970 string str;
971
972 // Handle negative durations by prefixing with a minus.
973 if (delta.ToInternalValue() < 0) {
974 delta *= -1;
975 str = "-";
976 }
977
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700978 // Canonicalize into days, hours, minutes, seconds and microseconds.
979 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800980 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700981 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800982 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700983 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800984 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700985 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800986 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700987 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800988
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700989 if (days)
990 base::StringAppendF(&str, "%ud", days);
991 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800992 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700993 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800994 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700995 base::StringAppendF(&str, "%u", secs);
996 if (usecs) {
997 int width = 6;
998 while ((usecs / 10) * 10 == usecs) {
999 usecs /= 10;
1000 width--;
1001 }
1002 base::StringAppendF(&str, ".%0*u", width, usecs);
1003 }
1004 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -08001005 return str;
1006}
1007
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001008string ToString(const Time utc_time) {
1009 Time::Exploded exp_time;
1010 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -07001011 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001012 exp_time.month,
1013 exp_time.day_of_month,
1014 exp_time.year,
1015 exp_time.hour,
1016 exp_time.minute,
1017 exp_time.second);
1018}
adlr@google.com3defe6a2009-12-04 20:57:17 +00001019
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001020string ToString(bool b) {
1021 return (b ? "true" : "false");
1022}
1023
Alex Deymo1c656c42013-06-28 11:02:14 -07001024string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -07001025 switch (source) {
1026 case kDownloadSourceHttpsServer: return "HttpsServer";
1027 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -07001028 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -07001029 case kNumDownloadSources: return "Unknown";
1030 // Don't add a default case to let the compiler warn about newly added
1031 // download sources which should be added here.
1032 }
1033
1034 return "Unknown";
1035}
1036
Alex Deymo1c656c42013-06-28 11:02:14 -07001037string ToString(PayloadType payload_type) {
1038 switch (payload_type) {
1039 case kPayloadTypeDelta: return "Delta";
1040 case kPayloadTypeFull: return "Full";
1041 case kPayloadTypeForcedFull: return "ForcedFull";
1042 case kNumPayloadTypes: return "Unknown";
1043 // Don't add a default case to let the compiler warn about newly added
1044 // payload types which should be added here.
1045 }
1046
1047 return "Unknown";
1048}
1049
David Zeuthena99981f2013-04-29 13:42:47 -07001050ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -07001051 // Ignore the higher order bits in the code by applying the mask as
1052 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001053 // with values less than ErrorCode::kUmaReportedMax.
1054 ErrorCode base_code = static_cast<ErrorCode>(
1055 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -07001056
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001057 // Make additional adjustments required for UMA and error classification.
1058 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
1059 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001060 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -07001061 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001062 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001063 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001064 << " to ErrorCode::kOmahaErrorInHTTPResponse";
1065 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -07001066 }
1067
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001068 return base_code;
1069}
1070
David Zeuthen27a48bc2013-08-06 12:06:29 -07001071Time TimeFromStructTimespec(struct timespec *ts) {
Ben Chan9abb7632014-08-07 00:10:53 -07001072 int64_t us = static_cast<int64_t>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
1073 static_cast<int64_t>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
David Zeuthen27a48bc2013-08-06 12:06:29 -07001074 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
1075}
1076
Alex Deymof329b932014-10-30 01:37:48 -07001077string StringVectorToString(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -07001078 string str = "[";
Alex Deymof329b932014-10-30 01:37:48 -07001079 for (vector<string>::const_iterator i = vec_str.begin();
1080 i != vec_str.end(); ++i) {
1081 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -07001082 str += ", ";
1083 str += '"';
1084 str += *i;
1085 str += '"';
1086 }
1087 str += "]";
1088 return str;
1089}
1090
David Zeuthen8f191b22013-08-06 12:27:50 -07001091string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001092 string encoded_hash = brillo::data_encoding::Base64Encode(payload_hash);
Alex Deymoc00c98a2015-03-17 17:38:00 -07001093 return base::StringPrintf("cros_update_size_%" PRIuS "_hash_%s",
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001094 payload_size,
1095 encoded_hash.c_str());
David Zeuthen8f191b22013-08-06 12:27:50 -07001096}
1097
Alex Deymof329b932014-10-30 01:37:48 -07001098bool DecodeAndStoreBase64String(const string& base64_encoded,
David Zeuthene7f89172013-10-31 10:21:04 -07001099 base::FilePath *out_path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001100 brillo::Blob contents;
David Zeuthene7f89172013-10-31 10:21:04 -07001101
1102 out_path->clear();
1103
1104 if (base64_encoded.size() == 0) {
1105 LOG(ERROR) << "Can't decode empty string.";
1106 return false;
1107 }
1108
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001109 if (!brillo::data_encoding::Base64Decode(base64_encoded, &contents) ||
David Zeuthene7f89172013-10-31 10:21:04 -07001110 contents.size() == 0) {
1111 LOG(ERROR) << "Error decoding base64.";
1112 return false;
1113 }
1114
Alex Vakulenko75039d72014-03-25 12:36:28 -07001115 FILE *file = base::CreateAndOpenTemporaryFile(out_path);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001116 if (file == nullptr) {
David Zeuthene7f89172013-10-31 10:21:04 -07001117 LOG(ERROR) << "Error creating temporary file.";
1118 return false;
1119 }
1120
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001121 if (fwrite(contents.data(), 1, contents.size(), file) != contents.size()) {
David Zeuthene7f89172013-10-31 10:21:04 -07001122 PLOG(ERROR) << "Error writing to temporary file.";
1123 if (fclose(file) != 0)
1124 PLOG(ERROR) << "Error closing temporary file.";
1125 if (unlink(out_path->value().c_str()) != 0)
1126 PLOG(ERROR) << "Error unlinking temporary file.";
1127 out_path->clear();
1128 return false;
1129 }
1130
1131 if (fclose(file) != 0) {
1132 PLOG(ERROR) << "Error closing temporary file.";
1133 out_path->clear();
1134 return false;
1135 }
1136
1137 return true;
1138}
1139
Alex Deymof329b932014-10-30 01:37:48 -07001140bool ConvertToOmahaInstallDate(Time time, int *out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -08001141 time_t unix_time = time.ToTimeT();
1142 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
1143 const time_t kOmahaEpoch = 1167638400;
1144 const int64_t kNumSecondsPerWeek = 7*24*3600;
1145 const int64_t kNumDaysPerWeek = 7;
1146
1147 time_t omaha_time = unix_time - kOmahaEpoch;
1148
1149 if (omaha_time < 0)
1150 return false;
1151
1152 // Note, as per the comment in utils.h we are deliberately not
1153 // handling DST correctly.
1154
1155 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
1156 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
1157
1158 return true;
1159}
1160
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001161bool GetMinorVersion(const brillo::KeyValueStore& store,
Alex Deymob42b98d2015-07-06 17:42:38 -07001162 uint32_t* minor_version) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001163 string result;
Alex Deymob42b98d2015-07-06 17:42:38 -07001164 if (store.GetString("PAYLOAD_MINOR_VERSION", &result)) {
Allie Wood425aa972015-02-17 14:47:17 -08001165 if (!base::StringToUint(result, minor_version)) {
1166 LOG(ERROR) << "StringToUint failed when parsing delta minor version.";
1167 return false;
1168 }
Allie Wood78750a42015-02-11 15:42:11 -08001169 return true;
1170 }
1171 return false;
1172}
1173
Sen Jiang3a92aa22016-03-01 14:22:52 -08001174bool IsZlibCompatible(const string& fingerprint) {
1175 if (fingerprint.size() != sizeof(kCompatibleZlibFingerprint[0]) - 1) {
1176 LOG(ERROR) << "Invalid fingerprint: " << fingerprint;
1177 return false;
1178 }
1179 for (auto& f : kCompatibleZlibFingerprint) {
1180 if (base::CompareCaseInsensitiveASCII(fingerprint, f) == 0) {
1181 return true;
1182 }
1183 }
1184 return false;
1185}
1186
Alex Deymo60ca1a72015-06-18 18:19:15 -07001187bool ReadExtents(const string& path, const vector<Extent>& extents,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001188 brillo::Blob* out_data, ssize_t out_data_size,
Allie Wood56873452015-03-27 17:48:40 -07001189 size_t block_size) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001190 brillo::Blob data(out_data_size);
Allie Wood56873452015-03-27 17:48:40 -07001191 ssize_t bytes_read = 0;
1192 int fd = open(path.c_str(), O_RDONLY);
1193 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
1194 ScopedFdCloser fd_closer(&fd);
1195
Gilad Arnold41e34742015-05-11 11:31:50 -07001196 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -07001197 ssize_t bytes_read_this_iteration = 0;
1198 ssize_t bytes = extent.num_blocks() * block_size;
1199 TEST_AND_RETURN_FALSE(bytes_read + bytes <= out_data_size);
1200 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
1201 &data[bytes_read],
1202 bytes,
1203 extent.start_block() * block_size,
1204 &bytes_read_this_iteration));
1205 TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes);
1206 bytes_read += bytes_read_this_iteration;
1207 }
1208 TEST_AND_RETURN_FALSE(out_data_size == bytes_read);
1209 *out_data = data;
1210 return true;
1211}
1212
Alex Deymodd132f32015-09-14 19:12:07 -07001213bool GetBootId(string* boot_id) {
1214 TEST_AND_RETURN_FALSE(
1215 base::ReadFileToString(base::FilePath(kBootIdPath), boot_id));
1216 base::TrimWhitespaceASCII(*boot_id, base::TRIM_TRAILING, boot_id);
1217 return true;
1218}
1219
adlr@google.com3defe6a2009-12-04 20:57:17 +00001220} // namespace utils
1221
1222} // namespace chromeos_update_engine