blob: 079645959950d4c36d2c69aba20a35359cdb7bdc [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"
Darin Petkov33d30642010-08-04 10:18:57 -070062#include "update_engine/omaha_request_params.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080063#include "update_engine/payload_consumer/file_descriptor.h"
64#include "update_engine/payload_consumer/file_writer.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080065#include "update_engine/update_attempter.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000066
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070067using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080068using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000069using std::min;
Chris Sosac1972482013-04-30 22:31:10 -070070using std::pair;
adlr@google.com3defe6a2009-12-04 20:57:17 +000071using std::string;
72using std::vector;
73
74namespace chromeos_update_engine {
75
Ben Chan77a1eba2012-10-07 22:54:55 -070076namespace {
77
78// The following constants control how UnmountFilesystem should retry if
79// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
80// one second.
81const int kUnmountMaxNumOfRetries = 5;
82const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Alex Deymo032e7722014-03-25 17:53:56 -070083
84// Number of bytes to read from a file to attempt to detect its contents. Used
85// in GetFileFormat.
86const int kGetFileFormatMaxHeaderSize = 32;
87
Alex Deymodd132f32015-09-14 19:12:07 -070088// The path to the kernel's boot_id.
89const char kBootIdPath[] = "/proc/sys/kernel/random/boot_id";
90
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080091// Return true if |disk_name| is an MTD or a UBI device. Note that this test is
92// simply based on the name of the device.
93bool IsMtdDeviceName(const string& disk_name) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -070094 return base::StartsWithASCII(disk_name, "/dev/ubi", true) ||
95 base::StartsWithASCII(disk_name, "/dev/mtd", true);
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) {
138 if (path[0] == '/' || base::StartsWithASCII(path, "./", true) ||
139 base::StartsWithASCII(path, "../", true)) {
140 *template_path = base::FilePath(path);
141 return true;
142 }
143
144 base::FilePath temp_dir;
Sen Jiang9c123462015-11-19 13:16:23 -0800145#ifdef __ANDROID__
146 temp_dir = base::FilePath(constants::kNonVolatileDirectory).Append("tmp");
147 if (!base::PathExists(temp_dir))
148 TEST_AND_RETURN_FALSE(base::CreateDirectory(temp_dir));
149#else
Alex Deymo5aa1c542015-09-18 01:02:33 -0700150 TEST_AND_RETURN_FALSE(base::GetTempDir(&temp_dir));
Sen Jiang9c123462015-11-19 13:16:23 -0800151#endif // __ANDROID__
Alex Deymo5aa1c542015-09-18 01:02:33 -0700152 *template_path = temp_dir.Append(path);
153 return true;
154}
155
Ben Chan77a1eba2012-10-07 22:54:55 -0700156} // namespace
157
adlr@google.com3defe6a2009-12-04 20:57:17 +0000158namespace utils {
159
Chris Sosa4f8ee272012-11-30 13:01:54 -0800160// Cgroup container is created in update-engine's upstart script located at
161// /etc/init/update-engine.conf.
162static const char kCGroupDir[] = "/sys/fs/cgroup/cpu/update-engine";
163
J. Richard Barnette63137e52013-10-28 10:57:29 -0700164string ParseECVersion(string input_line) {
Ben Chan736fcb52014-05-21 18:28:22 -0700165 base::TrimWhitespaceASCII(input_line, base::TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -0700166
Alex Vakulenko75039d72014-03-25 12:36:28 -0700167 // At this point we want to convert the format key=value pair from mosys to
Chris Sosac1972482013-04-30 22:31:10 -0700168 // a vector of key value pairs.
Ben Chanf9cb98c2014-09-21 18:31:30 -0700169 vector<pair<string, string>> kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -0700170 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Alex Deymo020600d2014-11-05 21:05:55 -0800171 for (const pair<string, string>& kv_pair : kv_pairs) {
Chris Sosac1972482013-04-30 22:31:10 -0700172 // Finally match against the fw_verion which may have quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800173 if (kv_pair.first == "fw_version") {
Chris Sosac1972482013-04-30 22:31:10 -0700174 string output;
175 // Trim any quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800176 base::TrimString(kv_pair.second, "\"", &output);
Chris Sosac1972482013-04-30 22:31:10 -0700177 return output;
178 }
179 }
180 }
181 LOG(ERROR) << "Unable to parse fwid from ec info.";
182 return "";
183}
184
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800185bool WriteFile(const char* path, const void* data, int data_len) {
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800186 DirectFileWriter writer;
187 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
188 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700189 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800190 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800191 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800192 return true;
193}
194
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700195bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700196 const char* c_buf = static_cast<const char*>(buf);
197 ssize_t bytes_written = 0;
198 while (bytes_written < static_cast<ssize_t>(count)) {
199 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
200 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
201 bytes_written += rc;
202 }
203 return true;
204}
205
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700206bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
207 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700208 size_t bytes_written = 0;
209 int num_attempts = 0;
210 while (bytes_written < count) {
211 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700212 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
213 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700214 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
215 if (rc < 0) {
216 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
217 << " bytes_written=" << bytes_written
218 << " count=" << count << " offset=" << offset;
219 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700220 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
221 bytes_written += rc;
222 }
223 return true;
224}
225
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800226bool WriteAll(FileDescriptorPtr fd, const void* buf, size_t count) {
227 const char* c_buf = static_cast<const char*>(buf);
228 ssize_t bytes_written = 0;
229 while (bytes_written < static_cast<ssize_t>(count)) {
230 ssize_t rc = fd->Write(c_buf + bytes_written, count - bytes_written);
231 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
232 bytes_written += rc;
233 }
234 return true;
235}
236
237bool PWriteAll(FileDescriptorPtr fd,
238 const void* buf,
239 size_t count,
240 off_t offset) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700241 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
242 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800243 return WriteAll(fd, buf, count);
244}
245
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700246bool PReadAll(int fd, void* buf, size_t count, off_t offset,
247 ssize_t* out_bytes_read) {
248 char* c_buf = static_cast<char*>(buf);
249 ssize_t bytes_read = 0;
250 while (bytes_read < static_cast<ssize_t>(count)) {
251 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
252 offset + bytes_read);
253 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
254 if (rc == 0) {
255 break;
256 }
257 bytes_read += rc;
258 }
259 *out_bytes_read = bytes_read;
260 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700261}
262
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800263bool PReadAll(FileDescriptorPtr fd, void* buf, size_t count, off_t offset,
264 ssize_t* out_bytes_read) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700265 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
266 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800267 char* c_buf = static_cast<char*>(buf);
268 ssize_t bytes_read = 0;
269 while (bytes_read < static_cast<ssize_t>(count)) {
270 ssize_t rc = fd->Read(c_buf + bytes_read, count - bytes_read);
271 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
272 if (rc == 0) {
273 break;
274 }
275 bytes_read += rc;
276 }
277 *out_bytes_read = bytes_read;
278 return true;
279}
280
Gilad Arnold19a45f02012-07-19 12:36:10 -0700281// Append |nbytes| of content from |buf| to the vector pointed to by either
282// |vec_p| or |str_p|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800283static void AppendBytes(const uint8_t* buf, size_t nbytes,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700284 brillo::Blob* vec_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700285 CHECK(buf);
286 CHECK(vec_p);
287 vec_p->insert(vec_p->end(), buf, buf + nbytes);
288}
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800289static void AppendBytes(const uint8_t* buf, size_t nbytes,
Alex Deymof329b932014-10-30 01:37:48 -0700290 string* str_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700291 CHECK(buf);
292 CHECK(str_p);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800293 str_p->append(buf, buf + nbytes);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700294}
295
296// Reads from an open file |fp|, appending the read content to the container
297// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200298// file's content, false otherwise. If |size| is not -1, reads up to |size|
299// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700300template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200301static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700302 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200303 CHECK(size == -1 || size >= 0);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800304 uint8_t buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200305 while (size == -1 || size > 0) {
306 off_t bytes_to_read = sizeof(buf);
307 if (size > 0 && bytes_to_read > size) {
308 bytes_to_read = size;
309 }
310 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
311 if (!nbytes) {
312 break;
313 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700314 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200315 if (size != -1) {
316 CHECK(size >= static_cast<off_t>(nbytes));
317 size -= nbytes;
318 }
319 }
320 if (ferror(fp)) {
321 return false;
322 }
323 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700324}
325
Darin Petkov8e447e02013-04-16 16:23:50 +0200326// Opens a file |path| for reading and appends its the contents to a container
327// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
328// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700329template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700330static bool ReadFileChunkAndAppend(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200331 off_t offset,
332 off_t size,
333 T* out_p) {
334 CHECK_GE(offset, 0);
335 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700336 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200337 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000338 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200339 if (offset) {
340 // Return success without appending any data if a chunk beyond the end of
341 // the file is requested.
342 if (offset >= FileSize(path)) {
343 return true;
344 }
345 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
346 }
347 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000348}
349
Alex Deymo10875d92014-11-10 21:52:57 -0800350// TODO(deymo): This is only used in unittest, but requires the private
351// Read<string>() defined here. Expose Read<string>() or move to base/ version.
352bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700353 FILE* fp = popen(cmd.c_str(), "r");
354 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000355 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200356 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700357 return (success && pclose(fp) >= 0);
358}
359
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700360bool ReadFile(const string& path, brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200361 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700362}
363
Darin Petkov8e447e02013-04-16 16:23:50 +0200364bool ReadFile(const string& path, string* out_p) {
365 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700366}
367
Darin Petkov8e447e02013-04-16 16:23:50 +0200368bool ReadFileChunk(const string& path, off_t offset, off_t size,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700369 brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200370 return ReadFileChunkAndAppend(path, offset, size, out_p);
371}
372
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700373off_t BlockDevSize(int fd) {
374 uint64_t dev_size;
375 int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
376 if (rc == -1) {
377 dev_size = -1;
378 PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
379 }
380 return dev_size;
381}
382
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700383off_t FileSize(int fd) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700384 struct stat stbuf;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700385 int rc = fstat(fd, &stbuf);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700386 CHECK_EQ(rc, 0);
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700387 if (rc < 0) {
388 PLOG(ERROR) << "Error stat-ing " << fd;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700389 return rc;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700390 }
391 if (S_ISREG(stbuf.st_mode))
392 return stbuf.st_size;
393 if (S_ISBLK(stbuf.st_mode))
394 return BlockDevSize(fd);
395 LOG(ERROR) << "Couldn't determine the type of " << fd;
396 return -1;
397}
398
399off_t FileSize(const string& path) {
400 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
401 if (fd == -1) {
402 PLOG(ERROR) << "Error opening " << path;
403 return fd;
404 }
405 off_t size = FileSize(fd);
406 if (size == -1)
407 PLOG(ERROR) << "Error getting file size of " << path;
408 close(fd);
409 return size;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700410}
411
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800412void HexDumpArray(const uint8_t* const arr, const size_t length) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000413 LOG(INFO) << "Logging array of length: " << length;
414 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700415 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000416 const unsigned int bytes_remaining = length - i;
417 const unsigned int bytes_per_this_line = min(bytes_per_line,
418 bytes_remaining);
419 char header[100];
420 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
421 TEST_AND_RETURN(r == 13);
422 string line = header;
423 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
424 char buf[20];
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800425 uint8_t c = arr[i + j];
adlr@google.com3defe6a2009-12-04 20:57:17 +0000426 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
427 TEST_AND_RETURN(r == 3);
428 line += buf;
429 }
430 LOG(INFO) << line;
431 }
432}
433
Alex Deymof329b932014-10-30 01:37:48 -0700434bool SplitPartitionName(const string& partition_name,
435 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800436 int* out_partition_num) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700437 if (!base::StartsWithASCII(partition_name, "/dev/", true)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800438 LOG(ERROR) << "Invalid partition device name: " << partition_name;
439 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700440 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800441
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700442 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
443 if (last_nondigit_pos == string::npos ||
444 (last_nondigit_pos + 1) == partition_name.size()) {
445 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800446 return false;
447 }
448
Alex Deymof329b932014-10-30 01:37:48 -0700449 size_t partition_name_len = string::npos;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700450 if (partition_name[last_nondigit_pos] == '_') {
451 // NAND block devices have weird naming which could be something
452 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
453 size_t prev_nondigit_pos =
454 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
455 if (prev_nondigit_pos == string::npos ||
456 (prev_nondigit_pos + 1) == last_nondigit_pos) {
457 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
458 return false;
459 }
460
461 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
462 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800463 }
464
465 if (out_disk_name) {
466 // Special case for MMC devices which have the following naming scheme:
467 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700468 size_t disk_name_len = last_nondigit_pos;
469 if (partition_name[last_nondigit_pos] != 'p' ||
470 last_nondigit_pos == 0 ||
471 !isdigit(partition_name[last_nondigit_pos - 1])) {
472 disk_name_len++;
473 }
474 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800475 }
476
477 if (out_partition_num) {
Alex Deymof329b932014-10-30 01:37:48 -0700478 string partition_str = partition_name.substr(last_nondigit_pos + 1,
479 partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800480 *out_partition_num = atoi(partition_str.c_str());
481 }
482 return true;
483}
484
Alex Deymof329b932014-10-30 01:37:48 -0700485string MakePartitionName(const string& disk_name, int partition_num) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800486 if (partition_num < 1) {
487 LOG(ERROR) << "Invalid partition number: " << partition_num;
488 return string();
489 }
490
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700491 if (!base::StartsWithASCII(disk_name, "/dev/", true)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800492 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700493 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800494 }
495
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800496 if (IsMtdDeviceName(disk_name)) {
497 // Special case for UBI block devices.
498 // 1. ubiblock is not writable, we need to use plain "ubi".
499 // 2. There is a "_0" suffix.
500 return MakeNandPartitionName(partition_num);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800501 }
502
Alex Deymof329b932014-10-30 01:37:48 -0700503 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700504 if (isdigit(partition_name.back())) {
505 // Special case for devices with names ending with a digit.
506 // Add "p" to separate the disk name from partition number,
507 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800508 partition_name += 'p';
509 }
510
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700511 partition_name += std::to_string(partition_num);
512
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800513 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700514}
515
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800516string MakePartitionNameForMount(const string& part_name) {
517 if (IsMtdDeviceName(part_name)) {
518 int partition_num;
519 if (!SplitPartitionName(part_name, nullptr, &partition_num)) {
520 return "";
521 }
522 return MakeNandPartitionNameForMount(partition_num);
523 }
524 return part_name;
525}
526
Alex Deymof329b932014-10-30 01:37:48 -0700527string ErrnoNumberAsString(int err) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000528 char buf[100];
529 buf[0] = '\0';
530 return strerror_r(err, buf, sizeof(buf));
531}
532
adlr@google.com3defe6a2009-12-04 20:57:17 +0000533bool FileExists(const char* path) {
534 struct stat stbuf;
535 return 0 == lstat(path, &stbuf);
536}
537
Darin Petkov30291ed2010-11-12 10:23:06 -0800538bool IsSymlink(const char* path) {
539 struct stat stbuf;
540 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
541}
542
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800543bool TryAttachingUbiVolume(int volume_num, int timeout) {
544 const string volume_path = base::StringPrintf("/dev/ubi%d_0", volume_num);
545 if (FileExists(volume_path.c_str())) {
546 return true;
547 }
548
549 int exit_code;
550 vector<string> cmd = {
551 "ubiattach",
552 "-m",
553 base::StringPrintf("%d", volume_num),
554 "-d",
555 base::StringPrintf("%d", volume_num)
556 };
557 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
558 TEST_AND_RETURN_FALSE(exit_code == 0);
559
560 cmd = {
561 "ubiblock",
562 "--create",
563 volume_path
564 };
565 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
566 TEST_AND_RETURN_FALSE(exit_code == 0);
567
568 while (timeout > 0 && !FileExists(volume_path.c_str())) {
569 sleep(1);
570 timeout--;
571 }
572
573 return FileExists(volume_path.c_str());
574}
575
Alex Deymof329b932014-10-30 01:37:48 -0700576bool MakeTempFile(const string& base_filename_template,
577 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700578 int* fd) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700579 base::FilePath filename_template;
580 TEST_AND_RETURN_FALSE(
581 GetTempName(base_filename_template, &filename_template));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700582 DCHECK(filename || fd);
Alex Deymo5aa1c542015-09-18 01:02:33 -0700583 vector<char> buf(filename_template.value().size() + 1);
584 memcpy(buf.data(), filename_template.value().data(),
585 filename_template.value().size());
586 buf[filename_template.value().size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700587
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800588 int mkstemp_fd = mkstemp(buf.data());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700589 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
590 if (filename) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800591 *filename = buf.data();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700592 }
593 if (fd) {
594 *fd = mkstemp_fd;
595 } else {
596 close(mkstemp_fd);
597 }
598 return true;
599}
600
Alex Deymof329b932014-10-30 01:37:48 -0700601bool MakeTempDirectory(const string& base_dirname_template,
602 string* dirname) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700603 base::FilePath dirname_template;
604 TEST_AND_RETURN_FALSE(GetTempName(base_dirname_template, &dirname_template));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700605 DCHECK(dirname);
Alex Deymo5aa1c542015-09-18 01:02:33 -0700606 vector<char> buf(dirname_template.value().size() + 1);
607 memcpy(buf.data(), dirname_template.value().data(),
608 dirname_template.value().size());
609 buf[dirname_template.value().size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700610
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800611 char* return_code = mkdtemp(buf.data());
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700612 TEST_AND_RETURN_FALSE_ERRNO(return_code != nullptr);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800613 *dirname = buf.data();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700614 return true;
615}
616
adlr@google.com3defe6a2009-12-04 20:57:17 +0000617bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700618 const string& mountpoint,
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700619 unsigned long mountflags) { // NOLINT(runtime/int)
Alex Deymo4c82df32014-11-10 22:25:57 -0800620 // TODO(sosa): Remove "ext3" once crbug.com/208022 is resolved.
Alex Deymo5fc5e102015-09-18 10:36:21 -0700621 const vector<const char*> fstypes{"ext2", "ext3", "ext4", "squashfs"};
Alex Deymo4c82df32014-11-10 22:25:57 -0800622 for (const char* fstype : fstypes) {
623 int rc = mount(device.c_str(), mountpoint.c_str(), fstype, mountflags,
624 nullptr);
625 if (rc == 0)
626 return true;
627
628 PLOG(WARNING) << "Unable to mount destination device " << device
629 << " on " << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000630 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800631 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
632 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000633}
634
635bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700636 for (int num_retries = 0; ; ++num_retries) {
637 if (umount(mountpoint.c_str()) == 0)
638 break;
639
640 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
641 num_retries < kUnmountMaxNumOfRetries);
Alex Deymo8d2bbe32015-06-23 16:28:59 -0700642 usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700643 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000644 return true;
645}
646
Alex Deymof329b932014-10-30 01:37:48 -0700647bool GetFilesystemSize(const string& device,
Darin Petkovd3f8c892010-10-12 21:38:45 -0700648 int* out_block_count,
649 int* out_block_size) {
650 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
Alex Deymoe7141c62014-10-17 14:03:01 -0700651 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700652 ScopedFdCloser fd_closer(&fd);
653 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
654}
655
656bool GetFilesystemSizeFromFD(int fd,
657 int* out_block_count,
658 int* out_block_size) {
659 TEST_AND_RETURN_FALSE(fd >= 0);
660
Alex Deymo192393b2014-11-10 15:58:38 -0800661 // Determine the filesystem size by directly reading the block count and
662 // block size information from the superblock. Supported FS are ext3 and
663 // squashfs.
664
665 // Read from the fd only once and detect in memory. The first 2 KiB is enough
666 // to read the ext2 superblock (located at offset 1024) and the squashfs
667 // superblock (located at offset 0).
668 const ssize_t kBufferSize = 2048;
669
670 uint8_t buffer[kBufferSize];
671 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, 0)) != kBufferSize) {
672 PLOG(ERROR) << "Unable to read the file system header:";
Darin Petkovd3f8c892010-10-12 21:38:45 -0700673 return false;
674 }
Alex Deymo192393b2014-11-10 15:58:38 -0800675
676 if (GetSquashfs4Size(buffer, kBufferSize, out_block_count, out_block_size))
677 return true;
678 if (GetExt3Size(buffer, kBufferSize, out_block_count, out_block_size))
679 return true;
680
681 LOG(ERROR) << "Unable to determine file system type.";
682 return false;
683}
684
685bool GetExt3Size(const uint8_t* buffer, size_t buffer_size,
686 int* out_block_count,
687 int* out_block_size) {
688 // See include/linux/ext2_fs.h for more details on the structure. We obtain
689 // ext2 constants from ext2fs/ext2fs.h header but we don't link with the
690 // library.
691 if (buffer_size < SUPERBLOCK_OFFSET + SUPERBLOCK_SIZE)
692 return false;
693
694 const uint8_t* superblock = buffer + SUPERBLOCK_OFFSET;
695
696 // ext3_fs.h: ext3_super_block.s_blocks_count
697 uint32_t block_count =
698 *reinterpret_cast<const uint32_t*>(superblock + 1 * sizeof(int32_t));
699
700 // ext3_fs.h: ext3_super_block.s_log_block_size
701 uint32_t log_block_size =
702 *reinterpret_cast<const uint32_t*>(superblock + 6 * sizeof(int32_t));
703
704 // ext3_fs.h: ext3_super_block.s_magic
705 uint16_t magic =
706 *reinterpret_cast<const uint16_t*>(superblock + 14 * sizeof(int32_t));
707
Darin Petkovd3f8c892010-10-12 21:38:45 -0700708 block_count = le32toh(block_count);
Alex Deymo192393b2014-11-10 15:58:38 -0800709 log_block_size = le32toh(log_block_size) + EXT2_MIN_BLOCK_LOG_SIZE;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700710 magic = le16toh(magic);
711
712 // Sanity check the parameters.
Alex Deymo192393b2014-11-10 15:58:38 -0800713 TEST_AND_RETURN_FALSE(magic == EXT2_SUPER_MAGIC);
714 TEST_AND_RETURN_FALSE(log_block_size >= EXT2_MIN_BLOCK_LOG_SIZE &&
715 log_block_size <= EXT2_MAX_BLOCK_LOG_SIZE);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700716 TEST_AND_RETURN_FALSE(block_count > 0);
717
Alex Deymo192393b2014-11-10 15:58:38 -0800718 if (out_block_count)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700719 *out_block_count = block_count;
Alex Deymo192393b2014-11-10 15:58:38 -0800720 if (out_block_size)
721 *out_block_size = 1 << log_block_size;
722 return true;
723}
724
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800725bool GetSquashfs4Size(const uint8_t* buffer, size_t buffer_size,
Alex Deymo192393b2014-11-10 15:58:38 -0800726 int* out_block_count,
727 int* out_block_size) {
728 // See fs/squashfs/squashfs_fs.h for format details. We only support
729 // Squashfs 4.x little endian.
730
731 // sizeof(struct squashfs_super_block)
732 const size_t kSquashfsSuperBlockSize = 96;
733 if (buffer_size < kSquashfsSuperBlockSize)
734 return false;
735
736 // Check magic, squashfs_fs.h: SQUASHFS_MAGIC
737 if (memcmp(buffer, "hsqs", 4) != 0)
738 return false; // Only little endian is supported.
739
740 // squashfs_fs.h: struct squashfs_super_block.s_major
741 uint16_t s_major = *reinterpret_cast<const uint16_t*>(
742 buffer + 5 * sizeof(uint32_t) + 4 * sizeof(uint16_t));
743
744 if (s_major != 4) {
745 LOG(ERROR) << "Found unsupported squashfs major version " << s_major;
746 return false;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700747 }
Alex Deymo192393b2014-11-10 15:58:38 -0800748
749 // squashfs_fs.h: struct squashfs_super_block.bytes_used
750 uint64_t bytes_used = *reinterpret_cast<const int64_t*>(
751 buffer + 5 * sizeof(uint32_t) + 6 * sizeof(uint16_t) + sizeof(uint64_t));
752
753 const int block_size = 4096;
754
755 // The squashfs' bytes_used doesn't need to be aligned with the block boundary
756 // so we round up to the nearest blocksize.
757 if (out_block_count)
758 *out_block_count = (bytes_used + block_size - 1) / block_size;
759 if (out_block_size)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700760 *out_block_size = block_size;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700761 return true;
762}
763
Alex Deymo60ca1a72015-06-18 18:19:15 -0700764bool IsExtFilesystem(const string& device) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700765 brillo::Blob header;
Alex Deymode942f32015-03-13 11:57:15 -0700766 // The first 2 KiB is enough to read the ext2 superblock (located at offset
767 // 1024).
768 if (!ReadFileChunk(device, 0, 2048, &header))
769 return false;
770 return GetExt3Size(header.data(), header.size(), nullptr, nullptr);
771}
772
Alex Deymo60ca1a72015-06-18 18:19:15 -0700773bool IsSquashfsFilesystem(const string& device) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700774 brillo::Blob header;
Alex Deymode942f32015-03-13 11:57:15 -0700775 // The first 96 is enough to read the squashfs superblock.
776 const ssize_t kSquashfsSuperBlockSize = 96;
777 if (!ReadFileChunk(device, 0, kSquashfsSuperBlockSize, &header))
778 return false;
779 return GetSquashfs4Size(header.data(), header.size(), nullptr, nullptr);
780}
781
Alex Deymo032e7722014-03-25 17:53:56 -0700782// Tries to parse the header of an ELF file to obtain a human-readable
783// description of it on the |output| string.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800784static bool GetFileFormatELF(const uint8_t* buffer, size_t size,
785 string* output) {
Alex Deymo032e7722014-03-25 17:53:56 -0700786 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700787 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700788 return false;
789 *output = "ELF";
790
791 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700792 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700793 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700794 switch (buffer[EI_CLASS]) {
795 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700796 *output += " 32-bit";
797 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700798 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700799 *output += " 64-bit";
800 break;
801 default:
802 *output += " ?-bit";
803 }
804
805 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700806 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700807 return true;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800808 uint8_t ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700809 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700810 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700811 *output += " little-endian";
812 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700813 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700814 *output += " big-endian";
815 break;
816 default:
817 *output += " ?-endian";
818 // Don't parse anything after the 0x10 offset if endianness is unknown.
819 return true;
820 }
821
Alex Deymoc1711e22014-08-08 13:16:23 -0700822 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
823 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
824 // and size is the same for both 32 and 64 bits.
825 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700826 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700827 uint16_t e_machine;
Alex Deymo032e7722014-03-25 17:53:56 -0700828 // Fix endianess regardless of the host endianess.
Alex Deymoc1711e22014-08-08 13:16:23 -0700829 if (ei_data == ELFDATA2LSB)
830 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700831 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700832 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700833
834 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700835 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700836 *output += " x86";
837 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700838 case EM_MIPS:
839 *output += " mips";
840 break;
841 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700842 *output += " arm";
843 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700844 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700845 *output += " x86-64";
846 break;
847 default:
848 *output += " unknown-arch";
849 }
850 return true;
851}
852
853string GetFileFormat(const string& path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700854 brillo::Blob buffer;
Alex Deymo032e7722014-03-25 17:53:56 -0700855 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
856 return "File not found.";
857
858 string result;
859 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
860 return result;
861
862 return "data";
863}
864
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800865namespace {
866// Do the actual trigger. We do it as a main-loop callback to (try to) get a
867// consistent stack trace.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700868void TriggerCrashReporterUpload() {
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800869 pid_t pid = fork();
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700870 CHECK_GE(pid, 0) << "fork failed"; // fork() failed. Something is very wrong.
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800871 if (pid == 0) {
872 // We are the child. Crash.
873 abort(); // never returns
874 }
875 // We are the parent. Wait for child to terminate.
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700876 pid_t result = waitpid(pid, nullptr, 0);
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800877 LOG_IF(ERROR, result < 0) << "waitpid() failed";
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800878}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700879} // namespace
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800880
881void ScheduleCrashReporterUpload() {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700882 brillo::MessageLoop::current()->PostTask(
Alex Deymo60ca1a72015-06-18 18:19:15 -0700883 FROM_HERE,
884 base::Bind(&TriggerCrashReporterUpload));
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800885}
886
Chris Sosa4f8ee272012-11-30 13:01:54 -0800887bool SetCpuShares(CpuShares shares) {
888 string string_shares = base::IntToString(static_cast<int>(shares));
889 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
890 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700891 if (utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
892 string_shares.size())) {
Chris Sosa4f8ee272012-11-30 13:01:54 -0800893 return true;
894 } else {
895 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
896 << " using " << cpu_shares_file;
897 return false;
898 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700899}
900
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700901int FuzzInt(int value, unsigned int range) {
902 int min = value - range / 2;
903 int max = value + range - range / 2;
904 return base::RandInt(min, max);
905}
906
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700907string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800908 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700909}
910
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800911string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400912 string str;
913
914 // Handle negative durations by prefixing with a minus.
915 if (delta.ToInternalValue() < 0) {
916 delta *= -1;
917 str = "-";
918 }
919
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700920 // Canonicalize into days, hours, minutes, seconds and microseconds.
921 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800922 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700923 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800924 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700925 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800926 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700927 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800928 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700929 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800930
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700931 if (days)
932 base::StringAppendF(&str, "%ud", days);
933 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800934 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700935 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800936 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700937 base::StringAppendF(&str, "%u", secs);
938 if (usecs) {
939 int width = 6;
940 while ((usecs / 10) * 10 == usecs) {
941 usecs /= 10;
942 width--;
943 }
944 base::StringAppendF(&str, ".%0*u", width, usecs);
945 }
946 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800947 return str;
948}
949
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700950string ToString(const Time utc_time) {
951 Time::Exploded exp_time;
952 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700953 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700954 exp_time.month,
955 exp_time.day_of_month,
956 exp_time.year,
957 exp_time.hour,
958 exp_time.minute,
959 exp_time.second);
960}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000961
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700962string ToString(bool b) {
963 return (b ? "true" : "false");
964}
965
Alex Deymo1c656c42013-06-28 11:02:14 -0700966string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700967 switch (source) {
968 case kDownloadSourceHttpsServer: return "HttpsServer";
969 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700970 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -0700971 case kNumDownloadSources: return "Unknown";
972 // Don't add a default case to let the compiler warn about newly added
973 // download sources which should be added here.
974 }
975
976 return "Unknown";
977}
978
Alex Deymo1c656c42013-06-28 11:02:14 -0700979string ToString(PayloadType payload_type) {
980 switch (payload_type) {
981 case kPayloadTypeDelta: return "Delta";
982 case kPayloadTypeFull: return "Full";
983 case kPayloadTypeForcedFull: return "ForcedFull";
984 case kNumPayloadTypes: return "Unknown";
985 // Don't add a default case to let the compiler warn about newly added
986 // payload types which should be added here.
987 }
988
989 return "Unknown";
990}
991
David Zeuthena99981f2013-04-29 13:42:47 -0700992ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700993 // Ignore the higher order bits in the code by applying the mask as
994 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700995 // with values less than ErrorCode::kUmaReportedMax.
996 ErrorCode base_code = static_cast<ErrorCode>(
997 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -0700998
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800999 // Make additional adjustments required for UMA and error classification.
1000 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
1001 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001002 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -07001003 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001004 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001005 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001006 << " to ErrorCode::kOmahaErrorInHTTPResponse";
1007 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -07001008 }
1009
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001010 return base_code;
1011}
1012
David Zeuthena99981f2013-04-29 13:42:47 -07001013string CodeToString(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001014 // If the given code has both parts (i.e. the error code part and the flags
1015 // part) then strip off the flags part since the switch statement below
1016 // has case statements only for the base error code or a single flag but
1017 // doesn't support any combinations of those.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001018 if ((static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags)) &&
1019 (static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags)))
1020 code = static_cast<ErrorCode>(
1021 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001022 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001023 case ErrorCode::kSuccess: return "ErrorCode::kSuccess";
1024 case ErrorCode::kError: return "ErrorCode::kError";
1025 case ErrorCode::kOmahaRequestError: return "ErrorCode::kOmahaRequestError";
1026 case ErrorCode::kOmahaResponseHandlerError:
1027 return "ErrorCode::kOmahaResponseHandlerError";
1028 case ErrorCode::kFilesystemCopierError:
1029 return "ErrorCode::kFilesystemCopierError";
1030 case ErrorCode::kPostinstallRunnerError:
1031 return "ErrorCode::kPostinstallRunnerError";
1032 case ErrorCode::kPayloadMismatchedType:
1033 return "ErrorCode::kPayloadMismatchedType";
1034 case ErrorCode::kInstallDeviceOpenError:
1035 return "ErrorCode::kInstallDeviceOpenError";
1036 case ErrorCode::kKernelDeviceOpenError:
1037 return "ErrorCode::kKernelDeviceOpenError";
1038 case ErrorCode::kDownloadTransferError:
1039 return "ErrorCode::kDownloadTransferError";
1040 case ErrorCode::kPayloadHashMismatchError:
1041 return "ErrorCode::kPayloadHashMismatchError";
1042 case ErrorCode::kPayloadSizeMismatchError:
1043 return "ErrorCode::kPayloadSizeMismatchError";
1044 case ErrorCode::kDownloadPayloadVerificationError:
1045 return "ErrorCode::kDownloadPayloadVerificationError";
1046 case ErrorCode::kDownloadNewPartitionInfoError:
1047 return "ErrorCode::kDownloadNewPartitionInfoError";
1048 case ErrorCode::kDownloadWriteError:
1049 return "ErrorCode::kDownloadWriteError";
1050 case ErrorCode::kNewRootfsVerificationError:
1051 return "ErrorCode::kNewRootfsVerificationError";
1052 case ErrorCode::kNewKernelVerificationError:
1053 return "ErrorCode::kNewKernelVerificationError";
1054 case ErrorCode::kSignedDeltaPayloadExpectedError:
1055 return "ErrorCode::kSignedDeltaPayloadExpectedError";
1056 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1057 return "ErrorCode::kDownloadPayloadPubKeyVerificationError";
1058 case ErrorCode::kPostinstallBootedFromFirmwareB:
1059 return "ErrorCode::kPostinstallBootedFromFirmwareB";
1060 case ErrorCode::kDownloadStateInitializationError:
1061 return "ErrorCode::kDownloadStateInitializationError";
1062 case ErrorCode::kDownloadInvalidMetadataMagicString:
1063 return "ErrorCode::kDownloadInvalidMetadataMagicString";
1064 case ErrorCode::kDownloadSignatureMissingInManifest:
1065 return "ErrorCode::kDownloadSignatureMissingInManifest";
1066 case ErrorCode::kDownloadManifestParseError:
1067 return "ErrorCode::kDownloadManifestParseError";
1068 case ErrorCode::kDownloadMetadataSignatureError:
1069 return "ErrorCode::kDownloadMetadataSignatureError";
1070 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1071 return "ErrorCode::kDownloadMetadataSignatureVerificationError";
1072 case ErrorCode::kDownloadMetadataSignatureMismatch:
1073 return "ErrorCode::kDownloadMetadataSignatureMismatch";
1074 case ErrorCode::kDownloadOperationHashVerificationError:
1075 return "ErrorCode::kDownloadOperationHashVerificationError";
1076 case ErrorCode::kDownloadOperationExecutionError:
1077 return "ErrorCode::kDownloadOperationExecutionError";
1078 case ErrorCode::kDownloadOperationHashMismatch:
1079 return "ErrorCode::kDownloadOperationHashMismatch";
1080 case ErrorCode::kOmahaRequestEmptyResponseError:
1081 return "ErrorCode::kOmahaRequestEmptyResponseError";
1082 case ErrorCode::kOmahaRequestXMLParseError:
1083 return "ErrorCode::kOmahaRequestXMLParseError";
1084 case ErrorCode::kDownloadInvalidMetadataSize:
1085 return "ErrorCode::kDownloadInvalidMetadataSize";
1086 case ErrorCode::kDownloadInvalidMetadataSignature:
1087 return "ErrorCode::kDownloadInvalidMetadataSignature";
1088 case ErrorCode::kOmahaResponseInvalid:
1089 return "ErrorCode::kOmahaResponseInvalid";
1090 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1091 return "ErrorCode::kOmahaUpdateIgnoredPerPolicy";
1092 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1093 return "ErrorCode::kOmahaUpdateDeferredPerPolicy";
1094 case ErrorCode::kOmahaErrorInHTTPResponse:
1095 return "ErrorCode::kOmahaErrorInHTTPResponse";
1096 case ErrorCode::kDownloadOperationHashMissingError:
1097 return "ErrorCode::kDownloadOperationHashMissingError";
1098 case ErrorCode::kDownloadMetadataSignatureMissingError:
1099 return "ErrorCode::kDownloadMetadataSignatureMissingError";
1100 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1101 return "ErrorCode::kOmahaUpdateDeferredForBackoff";
1102 case ErrorCode::kPostinstallPowerwashError:
1103 return "ErrorCode::kPostinstallPowerwashError";
1104 case ErrorCode::kUpdateCanceledByChannelChange:
1105 return "ErrorCode::kUpdateCanceledByChannelChange";
1106 case ErrorCode::kUmaReportedMax:
1107 return "ErrorCode::kUmaReportedMax";
1108 case ErrorCode::kOmahaRequestHTTPResponseBase:
1109 return "ErrorCode::kOmahaRequestHTTPResponseBase";
1110 case ErrorCode::kResumedFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001111 return "Resumed";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001112 case ErrorCode::kDevModeFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001113 return "DevMode";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001114 case ErrorCode::kTestImageFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001115 return "TestImage";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001116 case ErrorCode::kTestOmahaUrlFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001117 return "TestOmahaUrl";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001118 case ErrorCode::kSpecialFlags:
1119 return "ErrorCode::kSpecialFlags";
1120 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1121 return "ErrorCode::kPostinstallFirmwareRONotUpdatable";
1122 case ErrorCode::kUnsupportedMajorPayloadVersion:
1123 return "ErrorCode::kUnsupportedMajorPayloadVersion";
1124 case ErrorCode::kUnsupportedMinorPayloadVersion:
1125 return "ErrorCode::kUnsupportedMinorPayloadVersion";
David Zeuthenf3e28012014-08-26 18:23:52 -04001126 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
1127 return "ErrorCode::kOmahaRequestXMLHasEntityDecl";
Allie Woodeb9e6d82015-04-17 13:55:30 -07001128 case ErrorCode::kFilesystemVerifierError:
1129 return "ErrorCode::kFilesystemVerifierError";
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001130 // Don't add a default case to let the compiler warn about newly added
1131 // error codes which should be added here.
1132 }
1133
1134 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
1135}
Jay Srinivasanf0572052012-10-23 18:12:56 -07001136
Gilad Arnold30dedd82013-07-03 06:19:09 -07001137bool CreatePowerwashMarkerFile(const char* file_path) {
1138 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
1139 bool result = utils::WriteFile(marker_file,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001140 kPowerwashCommand,
1141 strlen(kPowerwashCommand));
Gilad Arnold30dedd82013-07-03 06:19:09 -07001142 if (result) {
1143 LOG(INFO) << "Created " << marker_file << " to powerwash on next reboot";
1144 } else {
1145 PLOG(ERROR) << "Error in creating powerwash marker file: " << marker_file;
1146 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001147
1148 return result;
1149}
1150
Gilad Arnold30dedd82013-07-03 06:19:09 -07001151bool DeletePowerwashMarkerFile(const char* file_path) {
1152 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
Alex Vakulenko75039d72014-03-25 12:36:28 -07001153 const base::FilePath kPowerwashMarkerPath(marker_file);
1154 bool result = base::DeleteFile(kPowerwashMarkerPath, false);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001155
1156 if (result)
1157 LOG(INFO) << "Successfully deleted the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001158 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001159 else
1160 PLOG(ERROR) << "Could not delete the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001161 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001162
1163 return result;
1164}
1165
David Zeuthen27a48bc2013-08-06 12:06:29 -07001166Time TimeFromStructTimespec(struct timespec *ts) {
Ben Chan9abb7632014-08-07 00:10:53 -07001167 int64_t us = static_cast<int64_t>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
1168 static_cast<int64_t>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
David Zeuthen27a48bc2013-08-06 12:06:29 -07001169 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
1170}
1171
Alex Deymof329b932014-10-30 01:37:48 -07001172string StringVectorToString(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -07001173 string str = "[";
Alex Deymof329b932014-10-30 01:37:48 -07001174 for (vector<string>::const_iterator i = vec_str.begin();
1175 i != vec_str.end(); ++i) {
1176 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -07001177 str += ", ";
1178 str += '"';
1179 str += *i;
1180 str += '"';
1181 }
1182 str += "]";
1183 return str;
1184}
1185
David Zeuthen8f191b22013-08-06 12:27:50 -07001186string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001187 string encoded_hash = brillo::data_encoding::Base64Encode(payload_hash);
Alex Deymoc00c98a2015-03-17 17:38:00 -07001188 return base::StringPrintf("cros_update_size_%" PRIuS "_hash_%s",
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001189 payload_size,
1190 encoded_hash.c_str());
David Zeuthen8f191b22013-08-06 12:27:50 -07001191}
1192
Alex Deymof329b932014-10-30 01:37:48 -07001193bool DecodeAndStoreBase64String(const string& base64_encoded,
David Zeuthene7f89172013-10-31 10:21:04 -07001194 base::FilePath *out_path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001195 brillo::Blob contents;
David Zeuthene7f89172013-10-31 10:21:04 -07001196
1197 out_path->clear();
1198
1199 if (base64_encoded.size() == 0) {
1200 LOG(ERROR) << "Can't decode empty string.";
1201 return false;
1202 }
1203
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001204 if (!brillo::data_encoding::Base64Decode(base64_encoded, &contents) ||
David Zeuthene7f89172013-10-31 10:21:04 -07001205 contents.size() == 0) {
1206 LOG(ERROR) << "Error decoding base64.";
1207 return false;
1208 }
1209
Alex Vakulenko75039d72014-03-25 12:36:28 -07001210 FILE *file = base::CreateAndOpenTemporaryFile(out_path);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001211 if (file == nullptr) {
David Zeuthene7f89172013-10-31 10:21:04 -07001212 LOG(ERROR) << "Error creating temporary file.";
1213 return false;
1214 }
1215
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001216 if (fwrite(contents.data(), 1, contents.size(), file) != contents.size()) {
David Zeuthene7f89172013-10-31 10:21:04 -07001217 PLOG(ERROR) << "Error writing to temporary file.";
1218 if (fclose(file) != 0)
1219 PLOG(ERROR) << "Error closing temporary file.";
1220 if (unlink(out_path->value().c_str()) != 0)
1221 PLOG(ERROR) << "Error unlinking temporary file.";
1222 out_path->clear();
1223 return false;
1224 }
1225
1226 if (fclose(file) != 0) {
1227 PLOG(ERROR) << "Error closing temporary file.";
1228 out_path->clear();
1229 return false;
1230 }
1231
1232 return true;
1233}
1234
Alex Deymof329b932014-10-30 01:37:48 -07001235bool ConvertToOmahaInstallDate(Time time, int *out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -08001236 time_t unix_time = time.ToTimeT();
1237 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
1238 const time_t kOmahaEpoch = 1167638400;
1239 const int64_t kNumSecondsPerWeek = 7*24*3600;
1240 const int64_t kNumDaysPerWeek = 7;
1241
1242 time_t omaha_time = unix_time - kOmahaEpoch;
1243
1244 if (omaha_time < 0)
1245 return false;
1246
1247 // Note, as per the comment in utils.h we are deliberately not
1248 // handling DST correctly.
1249
1250 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
1251 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
1252
1253 return true;
1254}
1255
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001256bool GetMinorVersion(const brillo::KeyValueStore& store,
Alex Deymob42b98d2015-07-06 17:42:38 -07001257 uint32_t* minor_version) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001258 string result;
Alex Deymob42b98d2015-07-06 17:42:38 -07001259 if (store.GetString("PAYLOAD_MINOR_VERSION", &result)) {
Allie Wood425aa972015-02-17 14:47:17 -08001260 if (!base::StringToUint(result, minor_version)) {
1261 LOG(ERROR) << "StringToUint failed when parsing delta minor version.";
1262 return false;
1263 }
Allie Wood78750a42015-02-11 15:42:11 -08001264 return true;
1265 }
1266 return false;
1267}
1268
Alex Deymo60ca1a72015-06-18 18:19:15 -07001269bool ReadExtents(const string& path, const vector<Extent>& extents,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001270 brillo::Blob* out_data, ssize_t out_data_size,
Allie Wood56873452015-03-27 17:48:40 -07001271 size_t block_size) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001272 brillo::Blob data(out_data_size);
Allie Wood56873452015-03-27 17:48:40 -07001273 ssize_t bytes_read = 0;
1274 int fd = open(path.c_str(), O_RDONLY);
1275 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
1276 ScopedFdCloser fd_closer(&fd);
1277
Gilad Arnold41e34742015-05-11 11:31:50 -07001278 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -07001279 ssize_t bytes_read_this_iteration = 0;
1280 ssize_t bytes = extent.num_blocks() * block_size;
1281 TEST_AND_RETURN_FALSE(bytes_read + bytes <= out_data_size);
1282 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
1283 &data[bytes_read],
1284 bytes,
1285 extent.start_block() * block_size,
1286 &bytes_read_this_iteration));
1287 TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes);
1288 bytes_read += bytes_read_this_iteration;
1289 }
1290 TEST_AND_RETURN_FALSE(out_data_size == bytes_read);
1291 *out_data = data;
1292 return true;
1293}
1294
Alex Deymodd132f32015-09-14 19:12:07 -07001295bool GetBootId(string* boot_id) {
1296 TEST_AND_RETURN_FALSE(
1297 base::ReadFileToString(base::FilePath(kBootIdPath), boot_id));
1298 base::TrimWhitespaceASCII(*boot_id, base::TRIM_TRAILING, boot_id);
1299 return true;
1300}
1301
adlr@google.com3defe6a2009-12-04 20:57:17 +00001302} // namespace utils
1303
1304} // namespace chromeos_update_engine