blob: dd2afead156c3a3c1a76daa5d978c93376c36514 [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>
Andrew de los Reyes970bb282009-12-09 16:34:04 -080025#include <fcntl.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000026#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
Alex Deymoc4acdf42014-05-28 21:07:10 -070029#include <sys/mount.h>
30#include <sys/resource.h>
31#include <sys/stat.h>
32#include <sys/types.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000033#include <unistd.h>
Darin Petkovf74eb652010-08-04 12:08:38 -070034
adlr@google.com3defe6a2009-12-04 20:57:17 +000035#include <algorithm>
Alex Vakulenkod2779df2014-06-16 13:19:00 -070036#include <utility>
Chris Sosac1972482013-04-30 22:31:10 -070037#include <vector>
Darin Petkovf74eb652010-08-04 12:08:38 -070038
Alex Vakulenko4906c1c2014-08-21 13:17:44 -070039#include <base/callback.h>
Ben Chan736fcb52014-05-21 18:28:22 -070040#include <base/files/file_path.h>
Alex Deymo192393b2014-11-10 15:58:38 -080041#include <base/files/file_util.h>
Ben Chan736fcb52014-05-21 18:28:22 -070042#include <base/files/scoped_file.h>
Alex Deymoc00c98a2015-03-17 17:38:00 -070043#include <base/format_macros.h>
Alex Deymo60ca1a72015-06-18 18:19:15 -070044#include <base/location.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040045#include <base/logging.h>
Chris Sosafc661a12013-02-26 14:43:21 -080046#include <base/posix/eintr_wrapper.h>
Will Drewry8f71da82010-08-30 14:07:11 -050047#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070048#include <base/strings/string_number_conversions.h>
49#include <base/strings/string_split.h>
50#include <base/strings/string_util.h>
51#include <base/strings/stringprintf.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070052#include <brillo/data_encoding.h>
Will Drewry8f71da82010-08-30 14:07:11 -050053
Alex Deymo39910dc2015-11-09 17:04:30 -080054#include "update_engine/common/clock_interface.h"
55#include "update_engine/common/constants.h"
Sen Jiang9c123462015-11-19 13:16:23 -080056#include "update_engine/common/platform_constants.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080057#include "update_engine/common/prefs_interface.h"
58#include "update_engine/common/subprocess.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080059#include "update_engine/payload_consumer/file_descriptor.h"
60#include "update_engine/payload_consumer/file_writer.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000061
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070062using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080063using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000064using std::min;
Chris Sosac1972482013-04-30 22:31:10 -070065using std::pair;
adlr@google.com3defe6a2009-12-04 20:57:17 +000066using std::string;
67using std::vector;
68
69namespace chromeos_update_engine {
70
Ben Chan77a1eba2012-10-07 22:54:55 -070071namespace {
72
73// The following constants control how UnmountFilesystem should retry if
74// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
75// one second.
76const int kUnmountMaxNumOfRetries = 5;
77const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Alex Deymo032e7722014-03-25 17:53:56 -070078
79// Number of bytes to read from a file to attempt to detect its contents. Used
80// in GetFileFormat.
81const int kGetFileFormatMaxHeaderSize = 32;
82
Alex Deymodd132f32015-09-14 19:12:07 -070083// The path to the kernel's boot_id.
84const char kBootIdPath[] = "/proc/sys/kernel/random/boot_id";
85
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080086// Return true if |disk_name| is an MTD or a UBI device. Note that this test is
87// simply based on the name of the device.
88bool IsMtdDeviceName(const string& disk_name) {
Alex Vakulenko0103c362016-01-20 07:56:15 -080089 return base::StartsWith(disk_name, "/dev/ubi",
90 base::CompareCase::SENSITIVE) ||
91 base::StartsWith(disk_name, "/dev/mtd", base::CompareCase::SENSITIVE);
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080092}
93
94// Return the device name for the corresponding partition on a NAND device.
95// WARNING: This function returns device names that are not mountable.
96string MakeNandPartitionName(int partition_num) {
97 switch (partition_num) {
98 case 2:
99 case 4:
100 case 6: {
101 return base::StringPrintf("/dev/mtd%d", partition_num);
102 }
103 default: {
104 return base::StringPrintf("/dev/ubi%d_0", partition_num);
105 }
106 }
107}
108
109// Return the device name for the corresponding partition on a NAND device that
110// may be mountable (but may not be writable).
111string MakeNandPartitionNameForMount(int partition_num) {
112 switch (partition_num) {
113 case 2:
114 case 4:
115 case 6: {
116 return base::StringPrintf("/dev/mtd%d", partition_num);
117 }
118 case 3:
119 case 5:
120 case 7: {
121 return base::StringPrintf("/dev/ubiblock%d_0", partition_num);
122 }
123 default: {
124 return base::StringPrintf("/dev/ubi%d_0", partition_num);
125 }
126 }
127}
128
Alex Deymo5aa1c542015-09-18 01:02:33 -0700129// If |path| is absolute, or explicit relative to the current working directory,
130// leaves it as is. Otherwise, uses the system's temp directory, as defined by
131// base::GetTempDir() and prepends it to |path|. On success stores the full
132// temporary path in |template_path| and returns true.
133bool GetTempName(const string& path, base::FilePath* template_path) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800134 if (path[0] == '/' ||
135 base::StartsWith(path, "./", base::CompareCase::SENSITIVE) ||
136 base::StartsWith(path, "../", base::CompareCase::SENSITIVE)) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700137 *template_path = base::FilePath(path);
138 return true;
139 }
140
141 base::FilePath temp_dir;
Sen Jiang9c123462015-11-19 13:16:23 -0800142#ifdef __ANDROID__
143 temp_dir = base::FilePath(constants::kNonVolatileDirectory).Append("tmp");
144 if (!base::PathExists(temp_dir))
145 TEST_AND_RETURN_FALSE(base::CreateDirectory(temp_dir));
146#else
Alex Deymo5aa1c542015-09-18 01:02:33 -0700147 TEST_AND_RETURN_FALSE(base::GetTempDir(&temp_dir));
Sen Jiang9c123462015-11-19 13:16:23 -0800148#endif // __ANDROID__
Alex Deymo5aa1c542015-09-18 01:02:33 -0700149 *template_path = temp_dir.Append(path);
150 return true;
151}
152
Ben Chan77a1eba2012-10-07 22:54:55 -0700153} // namespace
154
adlr@google.com3defe6a2009-12-04 20:57:17 +0000155namespace utils {
156
J. Richard Barnette63137e52013-10-28 10:57:29 -0700157string ParseECVersion(string input_line) {
Ben Chan736fcb52014-05-21 18:28:22 -0700158 base::TrimWhitespaceASCII(input_line, base::TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -0700159
Alex Vakulenko75039d72014-03-25 12:36:28 -0700160 // At this point we want to convert the format key=value pair from mosys to
Chris Sosac1972482013-04-30 22:31:10 -0700161 // a vector of key value pairs.
Ben Chanf9cb98c2014-09-21 18:31:30 -0700162 vector<pair<string, string>> kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -0700163 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Alex Deymo020600d2014-11-05 21:05:55 -0800164 for (const pair<string, string>& kv_pair : kv_pairs) {
Chris Sosac1972482013-04-30 22:31:10 -0700165 // Finally match against the fw_verion which may have quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800166 if (kv_pair.first == "fw_version") {
Chris Sosac1972482013-04-30 22:31:10 -0700167 string output;
168 // Trim any quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800169 base::TrimString(kv_pair.second, "\"", &output);
Chris Sosac1972482013-04-30 22:31:10 -0700170 return output;
171 }
172 }
173 }
174 LOG(ERROR) << "Unable to parse fwid from ec info.";
175 return "";
176}
177
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800178bool WriteFile(const char* path, const void* data, int data_len) {
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800179 DirectFileWriter writer;
180 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
181 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700182 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800183 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800184 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800185 return true;
186}
187
Alex Deymo0d298542016-03-30 18:31:49 -0700188bool ReadAll(
189 int fd, void* buf, size_t count, size_t* out_bytes_read, bool* eof) {
190 char* c_buf = static_cast<char*>(buf);
191 size_t bytes_read = 0;
192 *eof = false;
193 while (bytes_read < count) {
194 ssize_t rc = HANDLE_EINTR(read(fd, c_buf + bytes_read, count - bytes_read));
195 if (rc < 0) {
196 // EAGAIN and EWOULDBLOCK are normal return values when there's no more
197 // input and we are in non-blocking mode.
198 if (errno != EWOULDBLOCK && errno != EAGAIN) {
199 PLOG(ERROR) << "Error reading fd " << fd;
200 *out_bytes_read = bytes_read;
201 return false;
202 }
203 break;
204 } else if (rc == 0) {
205 // A value of 0 means that we reached EOF and there is nothing else to
206 // read from this fd.
207 *eof = true;
208 break;
209 } else {
210 bytes_read += rc;
211 }
212 }
213 *out_bytes_read = bytes_read;
214 return true;
215}
216
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700217bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700218 const char* c_buf = static_cast<const char*>(buf);
219 ssize_t bytes_written = 0;
220 while (bytes_written < static_cast<ssize_t>(count)) {
221 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
222 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
223 bytes_written += rc;
224 }
225 return true;
226}
227
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700228bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
229 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700230 size_t bytes_written = 0;
231 int num_attempts = 0;
232 while (bytes_written < count) {
233 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700234 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
235 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700236 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
237 if (rc < 0) {
238 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
239 << " bytes_written=" << bytes_written
240 << " count=" << count << " offset=" << offset;
241 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700242 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
243 bytes_written += rc;
244 }
245 return true;
246}
247
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800248bool WriteAll(FileDescriptorPtr fd, const void* buf, size_t count) {
249 const char* c_buf = static_cast<const char*>(buf);
250 ssize_t bytes_written = 0;
251 while (bytes_written < static_cast<ssize_t>(count)) {
252 ssize_t rc = fd->Write(c_buf + bytes_written, count - bytes_written);
253 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
254 bytes_written += rc;
255 }
256 return true;
257}
258
259bool PWriteAll(FileDescriptorPtr fd,
260 const void* buf,
261 size_t count,
262 off_t offset) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700263 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
264 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800265 return WriteAll(fd, buf, count);
266}
267
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700268bool PReadAll(int fd, void* buf, size_t count, off_t offset,
269 ssize_t* out_bytes_read) {
270 char* c_buf = static_cast<char*>(buf);
271 ssize_t bytes_read = 0;
272 while (bytes_read < static_cast<ssize_t>(count)) {
273 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
274 offset + bytes_read);
275 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
276 if (rc == 0) {
277 break;
278 }
279 bytes_read += rc;
280 }
281 *out_bytes_read = bytes_read;
282 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700283}
284
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800285bool PReadAll(FileDescriptorPtr fd, void* buf, size_t count, off_t offset,
286 ssize_t* out_bytes_read) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700287 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
288 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800289 char* c_buf = static_cast<char*>(buf);
290 ssize_t bytes_read = 0;
291 while (bytes_read < static_cast<ssize_t>(count)) {
292 ssize_t rc = fd->Read(c_buf + bytes_read, count - bytes_read);
293 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
294 if (rc == 0) {
295 break;
296 }
297 bytes_read += rc;
298 }
299 *out_bytes_read = bytes_read;
300 return true;
301}
302
Gilad Arnold19a45f02012-07-19 12:36:10 -0700303// Append |nbytes| of content from |buf| to the vector pointed to by either
304// |vec_p| or |str_p|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800305static void AppendBytes(const uint8_t* buf, size_t nbytes,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700306 brillo::Blob* vec_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700307 CHECK(buf);
308 CHECK(vec_p);
309 vec_p->insert(vec_p->end(), buf, buf + nbytes);
310}
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800311static void AppendBytes(const uint8_t* buf, size_t nbytes,
Alex Deymof329b932014-10-30 01:37:48 -0700312 string* str_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700313 CHECK(buf);
314 CHECK(str_p);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800315 str_p->append(buf, buf + nbytes);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700316}
317
318// Reads from an open file |fp|, appending the read content to the container
319// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200320// file's content, false otherwise. If |size| is not -1, reads up to |size|
321// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700322template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200323static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700324 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200325 CHECK(size == -1 || size >= 0);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800326 uint8_t buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200327 while (size == -1 || size > 0) {
328 off_t bytes_to_read = sizeof(buf);
329 if (size > 0 && bytes_to_read > size) {
330 bytes_to_read = size;
331 }
332 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
333 if (!nbytes) {
334 break;
335 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700336 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200337 if (size != -1) {
338 CHECK(size >= static_cast<off_t>(nbytes));
339 size -= nbytes;
340 }
341 }
342 if (ferror(fp)) {
343 return false;
344 }
345 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700346}
347
Darin Petkov8e447e02013-04-16 16:23:50 +0200348// Opens a file |path| for reading and appends its the contents to a container
349// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
350// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700351template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700352static bool ReadFileChunkAndAppend(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200353 off_t offset,
354 off_t size,
355 T* out_p) {
356 CHECK_GE(offset, 0);
357 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700358 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200359 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000360 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200361 if (offset) {
362 // Return success without appending any data if a chunk beyond the end of
363 // the file is requested.
364 if (offset >= FileSize(path)) {
365 return true;
366 }
367 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
368 }
369 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000370}
371
Alex Deymo10875d92014-11-10 21:52:57 -0800372// TODO(deymo): This is only used in unittest, but requires the private
373// Read<string>() defined here. Expose Read<string>() or move to base/ version.
374bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700375 FILE* fp = popen(cmd.c_str(), "r");
376 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000377 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200378 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700379 return (success && pclose(fp) >= 0);
380}
381
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700382bool ReadFile(const string& path, brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200383 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700384}
385
Darin Petkov8e447e02013-04-16 16:23:50 +0200386bool ReadFile(const string& path, string* out_p) {
387 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700388}
389
Darin Petkov8e447e02013-04-16 16:23:50 +0200390bool ReadFileChunk(const string& path, off_t offset, off_t size,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700391 brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200392 return ReadFileChunkAndAppend(path, offset, size, out_p);
393}
394
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700395off_t BlockDevSize(int fd) {
396 uint64_t dev_size;
397 int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
398 if (rc == -1) {
399 dev_size = -1;
400 PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
401 }
402 return dev_size;
403}
404
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700405off_t FileSize(int fd) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700406 struct stat stbuf;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700407 int rc = fstat(fd, &stbuf);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700408 CHECK_EQ(rc, 0);
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700409 if (rc < 0) {
410 PLOG(ERROR) << "Error stat-ing " << fd;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700411 return rc;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700412 }
413 if (S_ISREG(stbuf.st_mode))
414 return stbuf.st_size;
415 if (S_ISBLK(stbuf.st_mode))
416 return BlockDevSize(fd);
417 LOG(ERROR) << "Couldn't determine the type of " << fd;
418 return -1;
419}
420
421off_t FileSize(const string& path) {
422 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
423 if (fd == -1) {
424 PLOG(ERROR) << "Error opening " << path;
425 return fd;
426 }
427 off_t size = FileSize(fd);
428 if (size == -1)
429 PLOG(ERROR) << "Error getting file size of " << path;
430 close(fd);
431 return size;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700432}
433
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800434void HexDumpArray(const uint8_t* const arr, const size_t length) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000435 LOG(INFO) << "Logging array of length: " << length;
436 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700437 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000438 const unsigned int bytes_remaining = length - i;
439 const unsigned int bytes_per_this_line = min(bytes_per_line,
440 bytes_remaining);
441 char header[100];
442 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
443 TEST_AND_RETURN(r == 13);
444 string line = header;
445 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
446 char buf[20];
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800447 uint8_t c = arr[i + j];
adlr@google.com3defe6a2009-12-04 20:57:17 +0000448 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
449 TEST_AND_RETURN(r == 3);
450 line += buf;
451 }
452 LOG(INFO) << line;
453 }
454}
455
Alex Deymof329b932014-10-30 01:37:48 -0700456bool SplitPartitionName(const string& partition_name,
457 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800458 int* out_partition_num) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800459 if (!base::StartsWith(partition_name, "/dev/",
460 base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800461 LOG(ERROR) << "Invalid partition device name: " << partition_name;
462 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700463 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800464
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700465 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
466 if (last_nondigit_pos == string::npos ||
467 (last_nondigit_pos + 1) == partition_name.size()) {
468 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800469 return false;
470 }
471
Alex Deymof329b932014-10-30 01:37:48 -0700472 size_t partition_name_len = string::npos;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700473 if (partition_name[last_nondigit_pos] == '_') {
474 // NAND block devices have weird naming which could be something
475 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
476 size_t prev_nondigit_pos =
477 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
478 if (prev_nondigit_pos == string::npos ||
479 (prev_nondigit_pos + 1) == last_nondigit_pos) {
480 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
481 return false;
482 }
483
484 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
485 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800486 }
487
488 if (out_disk_name) {
489 // Special case for MMC devices which have the following naming scheme:
490 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700491 size_t disk_name_len = last_nondigit_pos;
492 if (partition_name[last_nondigit_pos] != 'p' ||
493 last_nondigit_pos == 0 ||
494 !isdigit(partition_name[last_nondigit_pos - 1])) {
495 disk_name_len++;
496 }
497 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800498 }
499
500 if (out_partition_num) {
Alex Deymof329b932014-10-30 01:37:48 -0700501 string partition_str = partition_name.substr(last_nondigit_pos + 1,
502 partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800503 *out_partition_num = atoi(partition_str.c_str());
504 }
505 return true;
506}
507
Alex Deymof329b932014-10-30 01:37:48 -0700508string MakePartitionName(const string& disk_name, int partition_num) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800509 if (partition_num < 1) {
510 LOG(ERROR) << "Invalid partition number: " << partition_num;
511 return string();
512 }
513
Alex Vakulenko0103c362016-01-20 07:56:15 -0800514 if (!base::StartsWith(disk_name, "/dev/", base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800515 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700516 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800517 }
518
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800519 if (IsMtdDeviceName(disk_name)) {
520 // Special case for UBI block devices.
521 // 1. ubiblock is not writable, we need to use plain "ubi".
522 // 2. There is a "_0" suffix.
523 return MakeNandPartitionName(partition_num);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800524 }
525
Alex Deymof329b932014-10-30 01:37:48 -0700526 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700527 if (isdigit(partition_name.back())) {
528 // Special case for devices with names ending with a digit.
529 // Add "p" to separate the disk name from partition number,
530 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800531 partition_name += 'p';
532 }
533
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700534 partition_name += std::to_string(partition_num);
535
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800536 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700537}
538
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800539string MakePartitionNameForMount(const string& part_name) {
540 if (IsMtdDeviceName(part_name)) {
541 int partition_num;
542 if (!SplitPartitionName(part_name, nullptr, &partition_num)) {
543 return "";
544 }
545 return MakeNandPartitionNameForMount(partition_num);
546 }
547 return part_name;
548}
549
Alex Deymof329b932014-10-30 01:37:48 -0700550string ErrnoNumberAsString(int err) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000551 char buf[100];
552 buf[0] = '\0';
553 return strerror_r(err, buf, sizeof(buf));
554}
555
adlr@google.com3defe6a2009-12-04 20:57:17 +0000556bool FileExists(const char* path) {
557 struct stat stbuf;
558 return 0 == lstat(path, &stbuf);
559}
560
Darin Petkov30291ed2010-11-12 10:23:06 -0800561bool IsSymlink(const char* path) {
562 struct stat stbuf;
563 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
564}
565
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800566bool TryAttachingUbiVolume(int volume_num, int timeout) {
567 const string volume_path = base::StringPrintf("/dev/ubi%d_0", volume_num);
568 if (FileExists(volume_path.c_str())) {
569 return true;
570 }
571
572 int exit_code;
573 vector<string> cmd = {
574 "ubiattach",
575 "-m",
576 base::StringPrintf("%d", volume_num),
577 "-d",
578 base::StringPrintf("%d", volume_num)
579 };
580 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
581 TEST_AND_RETURN_FALSE(exit_code == 0);
582
583 cmd = {
584 "ubiblock",
585 "--create",
586 volume_path
587 };
588 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
589 TEST_AND_RETURN_FALSE(exit_code == 0);
590
591 while (timeout > 0 && !FileExists(volume_path.c_str())) {
592 sleep(1);
593 timeout--;
594 }
595
596 return FileExists(volume_path.c_str());
597}
598
Alex Deymof329b932014-10-30 01:37:48 -0700599bool MakeTempFile(const string& base_filename_template,
600 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700601 int* fd) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700602 base::FilePath filename_template;
603 TEST_AND_RETURN_FALSE(
604 GetTempName(base_filename_template, &filename_template));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700605 DCHECK(filename || fd);
Alex Deymo5aa1c542015-09-18 01:02:33 -0700606 vector<char> buf(filename_template.value().size() + 1);
607 memcpy(buf.data(), filename_template.value().data(),
608 filename_template.value().size());
609 buf[filename_template.value().size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700610
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800611 int mkstemp_fd = mkstemp(buf.data());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700612 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
613 if (filename) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800614 *filename = buf.data();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700615 }
616 if (fd) {
617 *fd = mkstemp_fd;
618 } else {
619 close(mkstemp_fd);
620 }
621 return true;
622}
623
Alex Deymo5fb356c2016-03-25 18:48:22 -0700624bool SetBlockDeviceReadOnly(const string& device, bool read_only) {
625 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY | O_CLOEXEC));
626 if (fd < 0) {
627 PLOG(ERROR) << "Opening block device " << device;
628 return false;
629 }
630 ScopedFdCloser fd_closer(&fd);
631 // We take no action if not needed.
632 int read_only_flag;
633 int expected_flag = read_only ? 1 : 0;
634 int rc = ioctl(fd, BLKROGET, &read_only_flag);
635 // In case of failure reading the setting we will try to set it anyway.
636 if (rc == 0 && read_only_flag == expected_flag)
637 return true;
638
639 rc = ioctl(fd, BLKROSET, &expected_flag);
640 if (rc != 0) {
641 PLOG(ERROR) << "Marking block device " << device << " as read_only="
642 << expected_flag;
643 return false;
644 }
645 return true;
646}
647
adlr@google.com3defe6a2009-12-04 20:57:17 +0000648bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700649 const string& mountpoint,
Alex Deymo390efed2016-02-18 11:00:40 -0800650 unsigned long mountflags, // NOLINT(runtime/int)
Alex Deymo14dbd332016-03-01 18:55:54 -0800651 const string& type,
652 const string& fs_mount_options) {
Alex Deymo390efed2016-02-18 11:00:40 -0800653 vector<const char*> fstypes;
654 if (type.empty()) {
655 fstypes = {"ext2", "ext3", "ext4", "squashfs"};
656 } else {
657 fstypes = {type.c_str()};
658 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800659 for (const char* fstype : fstypes) {
660 int rc = mount(device.c_str(), mountpoint.c_str(), fstype, mountflags,
Alex Deymo14dbd332016-03-01 18:55:54 -0800661 fs_mount_options.c_str());
Alex Deymo4c82df32014-11-10 22:25:57 -0800662 if (rc == 0)
663 return true;
664
665 PLOG(WARNING) << "Unable to mount destination device " << device
666 << " on " << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000667 }
Alex Deymo390efed2016-02-18 11:00:40 -0800668 if (!type.empty()) {
669 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
670 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800671 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000672}
673
674bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700675 for (int num_retries = 0; ; ++num_retries) {
676 if (umount(mountpoint.c_str()) == 0)
677 break;
678
679 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
680 num_retries < kUnmountMaxNumOfRetries);
Alex Deymo8d2bbe32015-06-23 16:28:59 -0700681 usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700682 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000683 return true;
684}
685
Alex Deymo032e7722014-03-25 17:53:56 -0700686// Tries to parse the header of an ELF file to obtain a human-readable
687// description of it on the |output| string.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800688static bool GetFileFormatELF(const uint8_t* buffer, size_t size,
689 string* output) {
Alex Deymo032e7722014-03-25 17:53:56 -0700690 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700691 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700692 return false;
693 *output = "ELF";
694
695 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700696 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700697 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700698 switch (buffer[EI_CLASS]) {
699 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700700 *output += " 32-bit";
701 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700702 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700703 *output += " 64-bit";
704 break;
705 default:
706 *output += " ?-bit";
707 }
708
709 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700710 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700711 return true;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800712 uint8_t ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700713 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700714 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700715 *output += " little-endian";
716 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700717 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700718 *output += " big-endian";
719 break;
720 default:
721 *output += " ?-endian";
722 // Don't parse anything after the 0x10 offset if endianness is unknown.
723 return true;
724 }
725
Alex Deymoc1711e22014-08-08 13:16:23 -0700726 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
727 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
728 // and size is the same for both 32 and 64 bits.
729 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700730 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700731 uint16_t e_machine;
Alex Deymo032e7722014-03-25 17:53:56 -0700732 // Fix endianess regardless of the host endianess.
Alex Deymoc1711e22014-08-08 13:16:23 -0700733 if (ei_data == ELFDATA2LSB)
734 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700735 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700736 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700737
738 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700739 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700740 *output += " x86";
741 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700742 case EM_MIPS:
743 *output += " mips";
744 break;
745 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700746 *output += " arm";
747 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700748 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700749 *output += " x86-64";
750 break;
751 default:
752 *output += " unknown-arch";
753 }
754 return true;
755}
756
757string GetFileFormat(const string& path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700758 brillo::Blob buffer;
Alex Deymo032e7722014-03-25 17:53:56 -0700759 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
760 return "File not found.";
761
762 string result;
763 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
764 return result;
765
766 return "data";
767}
768
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700769int FuzzInt(int value, unsigned int range) {
770 int min = value - range / 2;
771 int max = value + range - range / 2;
772 return base::RandInt(min, max);
773}
774
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700775string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800776 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700777}
778
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800779string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400780 string str;
781
782 // Handle negative durations by prefixing with a minus.
783 if (delta.ToInternalValue() < 0) {
784 delta *= -1;
785 str = "-";
786 }
787
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700788 // Canonicalize into days, hours, minutes, seconds and microseconds.
789 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800790 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700791 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800792 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700793 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800794 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700795 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800796 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700797 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800798
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700799 if (days)
800 base::StringAppendF(&str, "%ud", days);
801 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800802 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700803 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800804 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700805 base::StringAppendF(&str, "%u", secs);
806 if (usecs) {
807 int width = 6;
808 while ((usecs / 10) * 10 == usecs) {
809 usecs /= 10;
810 width--;
811 }
812 base::StringAppendF(&str, ".%0*u", width, usecs);
813 }
814 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800815 return str;
816}
817
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700818string ToString(const Time utc_time) {
819 Time::Exploded exp_time;
820 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700821 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700822 exp_time.month,
823 exp_time.day_of_month,
824 exp_time.year,
825 exp_time.hour,
826 exp_time.minute,
827 exp_time.second);
828}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000829
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700830string ToString(bool b) {
831 return (b ? "true" : "false");
832}
833
Alex Deymo1c656c42013-06-28 11:02:14 -0700834string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700835 switch (source) {
836 case kDownloadSourceHttpsServer: return "HttpsServer";
837 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700838 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -0700839 case kNumDownloadSources: return "Unknown";
840 // Don't add a default case to let the compiler warn about newly added
841 // download sources which should be added here.
842 }
843
844 return "Unknown";
845}
846
Alex Deymo1c656c42013-06-28 11:02:14 -0700847string ToString(PayloadType payload_type) {
848 switch (payload_type) {
849 case kPayloadTypeDelta: return "Delta";
850 case kPayloadTypeFull: return "Full";
851 case kPayloadTypeForcedFull: return "ForcedFull";
852 case kNumPayloadTypes: return "Unknown";
853 // Don't add a default case to let the compiler warn about newly added
854 // payload types which should be added here.
855 }
856
857 return "Unknown";
858}
859
David Zeuthena99981f2013-04-29 13:42:47 -0700860ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700861 // Ignore the higher order bits in the code by applying the mask as
862 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700863 // with values less than ErrorCode::kUmaReportedMax.
864 ErrorCode base_code = static_cast<ErrorCode>(
865 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -0700866
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800867 // Make additional adjustments required for UMA and error classification.
868 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
869 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700870 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700871 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800872 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800873 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700874 << " to ErrorCode::kOmahaErrorInHTTPResponse";
875 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700876 }
877
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800878 return base_code;
879}
880
Gilad Arnold30dedd82013-07-03 06:19:09 -0700881bool CreatePowerwashMarkerFile(const char* file_path) {
882 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
883 bool result = utils::WriteFile(marker_file,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700884 kPowerwashCommand,
885 strlen(kPowerwashCommand));
Gilad Arnold30dedd82013-07-03 06:19:09 -0700886 if (result) {
887 LOG(INFO) << "Created " << marker_file << " to powerwash on next reboot";
888 } else {
889 PLOG(ERROR) << "Error in creating powerwash marker file: " << marker_file;
890 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700891
892 return result;
893}
894
Gilad Arnold30dedd82013-07-03 06:19:09 -0700895bool DeletePowerwashMarkerFile(const char* file_path) {
896 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
Alex Vakulenko75039d72014-03-25 12:36:28 -0700897 const base::FilePath kPowerwashMarkerPath(marker_file);
898 bool result = base::DeleteFile(kPowerwashMarkerPath, false);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700899
900 if (result)
901 LOG(INFO) << "Successfully deleted the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -0700902 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700903 else
904 PLOG(ERROR) << "Could not delete the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -0700905 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700906
907 return result;
908}
909
David Zeuthen27a48bc2013-08-06 12:06:29 -0700910Time TimeFromStructTimespec(struct timespec *ts) {
Ben Chan9abb7632014-08-07 00:10:53 -0700911 int64_t us = static_cast<int64_t>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
912 static_cast<int64_t>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700913 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
914}
915
Alex Deymof329b932014-10-30 01:37:48 -0700916string StringVectorToString(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700917 string str = "[";
Alex Deymof329b932014-10-30 01:37:48 -0700918 for (vector<string>::const_iterator i = vec_str.begin();
919 i != vec_str.end(); ++i) {
920 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -0700921 str += ", ";
922 str += '"';
923 str += *i;
924 str += '"';
925 }
926 str += "]";
927 return str;
928}
929
David Zeuthen8f191b22013-08-06 12:27:50 -0700930string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700931 string encoded_hash = brillo::data_encoding::Base64Encode(payload_hash);
Alex Deymoc00c98a2015-03-17 17:38:00 -0700932 return base::StringPrintf("cros_update_size_%" PRIuS "_hash_%s",
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800933 payload_size,
934 encoded_hash.c_str());
David Zeuthen8f191b22013-08-06 12:27:50 -0700935}
936
Alex Deymof329b932014-10-30 01:37:48 -0700937bool DecodeAndStoreBase64String(const string& base64_encoded,
David Zeuthene7f89172013-10-31 10:21:04 -0700938 base::FilePath *out_path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700939 brillo::Blob contents;
David Zeuthene7f89172013-10-31 10:21:04 -0700940
941 out_path->clear();
942
943 if (base64_encoded.size() == 0) {
944 LOG(ERROR) << "Can't decode empty string.";
945 return false;
946 }
947
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700948 if (!brillo::data_encoding::Base64Decode(base64_encoded, &contents) ||
David Zeuthene7f89172013-10-31 10:21:04 -0700949 contents.size() == 0) {
950 LOG(ERROR) << "Error decoding base64.";
951 return false;
952 }
953
Alex Vakulenko75039d72014-03-25 12:36:28 -0700954 FILE *file = base::CreateAndOpenTemporaryFile(out_path);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700955 if (file == nullptr) {
David Zeuthene7f89172013-10-31 10:21:04 -0700956 LOG(ERROR) << "Error creating temporary file.";
957 return false;
958 }
959
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800960 if (fwrite(contents.data(), 1, contents.size(), file) != contents.size()) {
David Zeuthene7f89172013-10-31 10:21:04 -0700961 PLOG(ERROR) << "Error writing to temporary file.";
962 if (fclose(file) != 0)
963 PLOG(ERROR) << "Error closing temporary file.";
964 if (unlink(out_path->value().c_str()) != 0)
965 PLOG(ERROR) << "Error unlinking temporary file.";
966 out_path->clear();
967 return false;
968 }
969
970 if (fclose(file) != 0) {
971 PLOG(ERROR) << "Error closing temporary file.";
972 out_path->clear();
973 return false;
974 }
975
976 return true;
977}
978
Alex Deymof329b932014-10-30 01:37:48 -0700979bool ConvertToOmahaInstallDate(Time time, int *out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -0800980 time_t unix_time = time.ToTimeT();
981 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
982 const time_t kOmahaEpoch = 1167638400;
983 const int64_t kNumSecondsPerWeek = 7*24*3600;
984 const int64_t kNumDaysPerWeek = 7;
985
986 time_t omaha_time = unix_time - kOmahaEpoch;
987
988 if (omaha_time < 0)
989 return false;
990
991 // Note, as per the comment in utils.h we are deliberately not
992 // handling DST correctly.
993
994 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
995 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
996
997 return true;
998}
999
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001000bool GetMinorVersion(const brillo::KeyValueStore& store,
Alex Deymob42b98d2015-07-06 17:42:38 -07001001 uint32_t* minor_version) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001002 string result;
Alex Deymob42b98d2015-07-06 17:42:38 -07001003 if (store.GetString("PAYLOAD_MINOR_VERSION", &result)) {
Allie Wood425aa972015-02-17 14:47:17 -08001004 if (!base::StringToUint(result, minor_version)) {
1005 LOG(ERROR) << "StringToUint failed when parsing delta minor version.";
1006 return false;
1007 }
Allie Wood78750a42015-02-11 15:42:11 -08001008 return true;
1009 }
1010 return false;
1011}
1012
Alex Deymo60ca1a72015-06-18 18:19:15 -07001013bool ReadExtents(const string& path, const vector<Extent>& extents,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001014 brillo::Blob* out_data, ssize_t out_data_size,
Allie Wood56873452015-03-27 17:48:40 -07001015 size_t block_size) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001016 brillo::Blob data(out_data_size);
Allie Wood56873452015-03-27 17:48:40 -07001017 ssize_t bytes_read = 0;
1018 int fd = open(path.c_str(), O_RDONLY);
1019 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
1020 ScopedFdCloser fd_closer(&fd);
1021
Gilad Arnold41e34742015-05-11 11:31:50 -07001022 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -07001023 ssize_t bytes_read_this_iteration = 0;
1024 ssize_t bytes = extent.num_blocks() * block_size;
1025 TEST_AND_RETURN_FALSE(bytes_read + bytes <= out_data_size);
1026 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
1027 &data[bytes_read],
1028 bytes,
1029 extent.start_block() * block_size,
1030 &bytes_read_this_iteration));
1031 TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes);
1032 bytes_read += bytes_read_this_iteration;
1033 }
1034 TEST_AND_RETURN_FALSE(out_data_size == bytes_read);
1035 *out_data = data;
1036 return true;
1037}
1038
Alex Deymodd132f32015-09-14 19:12:07 -07001039bool GetBootId(string* boot_id) {
1040 TEST_AND_RETURN_FALSE(
1041 base::ReadFileToString(base::FilePath(kBootIdPath), boot_id));
1042 base::TrimWhitespaceASCII(*boot_id, base::TRIM_TRAILING, boot_id);
1043 return true;
1044}
1045
adlr@google.com3defe6a2009-12-04 20:57:17 +00001046} // namespace utils
1047
1048} // namespace chromeos_update_engine