blob: 1cb37e5714664534bd38e5ba9272bc5df8db8141 [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"
Sen Jiange0d04282016-03-01 14:22:52 -080060#include "update_engine/payload_consumer/payload_constants.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
Alex Deymo32951022016-08-10 17:02:49 -070086// A pointer to a null-terminated string containing the root directory where all
87// the temporary files should be created. If null, the system default is used
88// instead.
89const char* root_temp_dir = nullptr;
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 Vakulenko0103c362016-01-20 07:56:15 -080094 return base::StartsWith(disk_name, "/dev/ubi",
95 base::CompareCase::SENSITIVE) ||
96 base::StartsWith(disk_name, "/dev/mtd", base::CompareCase::SENSITIVE);
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080097}
98
99// Return the device name for the corresponding partition on a NAND device.
100// WARNING: This function returns device names that are not mountable.
101string MakeNandPartitionName(int partition_num) {
102 switch (partition_num) {
103 case 2:
104 case 4:
105 case 6: {
106 return base::StringPrintf("/dev/mtd%d", partition_num);
107 }
108 default: {
109 return base::StringPrintf("/dev/ubi%d_0", partition_num);
110 }
111 }
112}
113
114// Return the device name for the corresponding partition on a NAND device that
115// may be mountable (but may not be writable).
116string MakeNandPartitionNameForMount(int partition_num) {
117 switch (partition_num) {
118 case 2:
119 case 4:
120 case 6: {
121 return base::StringPrintf("/dev/mtd%d", partition_num);
122 }
123 case 3:
124 case 5:
125 case 7: {
126 return base::StringPrintf("/dev/ubiblock%d_0", partition_num);
127 }
128 default: {
129 return base::StringPrintf("/dev/ubi%d_0", partition_num);
130 }
131 }
132}
133
Alex Deymo5aa1c542015-09-18 01:02:33 -0700134// If |path| is absolute, or explicit relative to the current working directory,
135// leaves it as is. Otherwise, uses the system's temp directory, as defined by
136// base::GetTempDir() and prepends it to |path|. On success stores the full
137// temporary path in |template_path| and returns true.
138bool GetTempName(const string& path, base::FilePath* template_path) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800139 if (path[0] == '/' ||
140 base::StartsWith(path, "./", base::CompareCase::SENSITIVE) ||
141 base::StartsWith(path, "../", base::CompareCase::SENSITIVE)) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700142 *template_path = base::FilePath(path);
143 return true;
144 }
145
146 base::FilePath temp_dir;
Alex Deymo32951022016-08-10 17:02:49 -0700147 if (root_temp_dir) {
148 temp_dir = base::FilePath(root_temp_dir);
149 } else {
Sen Jiang9c123462015-11-19 13:16:23 -0800150#ifdef __ANDROID__
Alex Deymo32951022016-08-10 17:02:49 -0700151 temp_dir = base::FilePath(constants::kNonVolatileDirectory).Append("tmp");
152#else
153 TEST_AND_RETURN_FALSE(base::GetTempDir(&temp_dir));
154#endif // __ANDROID__
155 }
Sen Jiang9c123462015-11-19 13:16:23 -0800156 if (!base::PathExists(temp_dir))
157 TEST_AND_RETURN_FALSE(base::CreateDirectory(temp_dir));
Alex Deymo5aa1c542015-09-18 01:02:33 -0700158 *template_path = temp_dir.Append(path);
159 return true;
160}
161
Ben Chan77a1eba2012-10-07 22:54:55 -0700162} // namespace
163
adlr@google.com3defe6a2009-12-04 20:57:17 +0000164namespace utils {
165
Alex Deymo32951022016-08-10 17:02:49 -0700166void SetRootTempDir(const char* new_root_temp_dir) {
167 root_temp_dir = new_root_temp_dir;
168}
169
J. Richard Barnette63137e52013-10-28 10:57:29 -0700170string ParseECVersion(string input_line) {
Ben Chan736fcb52014-05-21 18:28:22 -0700171 base::TrimWhitespaceASCII(input_line, base::TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -0700172
Alex Vakulenko75039d72014-03-25 12:36:28 -0700173 // At this point we want to convert the format key=value pair from mosys to
Chris Sosac1972482013-04-30 22:31:10 -0700174 // a vector of key value pairs.
Ben Chanf9cb98c2014-09-21 18:31:30 -0700175 vector<pair<string, string>> kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -0700176 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Alex Deymo020600d2014-11-05 21:05:55 -0800177 for (const pair<string, string>& kv_pair : kv_pairs) {
Chris Sosac1972482013-04-30 22:31:10 -0700178 // Finally match against the fw_verion which may have quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800179 if (kv_pair.first == "fw_version") {
Chris Sosac1972482013-04-30 22:31:10 -0700180 string output;
181 // Trim any quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800182 base::TrimString(kv_pair.second, "\"", &output);
Chris Sosac1972482013-04-30 22:31:10 -0700183 return output;
184 }
185 }
186 }
187 LOG(ERROR) << "Unable to parse fwid from ec info.";
188 return "";
189}
190
Alex Deymo335516c2016-11-28 13:37:06 -0800191bool WriteFile(const char* path, const void* data, size_t data_len) {
192 int fd = HANDLE_EINTR(open(path, O_WRONLY | O_CREAT | O_TRUNC, 0600));
193 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
194 ScopedFdCloser fd_closer(&fd);
195 return WriteAll(fd, data, data_len);
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800196}
197
Alex Deymo0d298542016-03-30 18:31:49 -0700198bool ReadAll(
199 int fd, void* buf, size_t count, size_t* out_bytes_read, bool* eof) {
200 char* c_buf = static_cast<char*>(buf);
201 size_t bytes_read = 0;
202 *eof = false;
203 while (bytes_read < count) {
204 ssize_t rc = HANDLE_EINTR(read(fd, c_buf + bytes_read, count - bytes_read));
205 if (rc < 0) {
206 // EAGAIN and EWOULDBLOCK are normal return values when there's no more
207 // input and we are in non-blocking mode.
208 if (errno != EWOULDBLOCK && errno != EAGAIN) {
209 PLOG(ERROR) << "Error reading fd " << fd;
210 *out_bytes_read = bytes_read;
211 return false;
212 }
213 break;
214 } else if (rc == 0) {
215 // A value of 0 means that we reached EOF and there is nothing else to
216 // read from this fd.
217 *eof = true;
218 break;
219 } else {
220 bytes_read += rc;
221 }
222 }
223 *out_bytes_read = bytes_read;
224 return true;
225}
226
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700227bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700228 const char* c_buf = static_cast<const char*>(buf);
229 ssize_t bytes_written = 0;
230 while (bytes_written < static_cast<ssize_t>(count)) {
231 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
232 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
233 bytes_written += rc;
234 }
235 return true;
236}
237
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700238bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
239 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700240 size_t bytes_written = 0;
241 int num_attempts = 0;
242 while (bytes_written < count) {
243 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700244 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
245 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700246 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
247 if (rc < 0) {
248 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
249 << " bytes_written=" << bytes_written
250 << " count=" << count << " offset=" << offset;
251 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700252 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
253 bytes_written += rc;
254 }
255 return true;
256}
257
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700258bool WriteAll(const FileDescriptorPtr& fd, const void* buf, size_t count) {
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800259 const char* c_buf = static_cast<const char*>(buf);
260 ssize_t bytes_written = 0;
261 while (bytes_written < static_cast<ssize_t>(count)) {
262 ssize_t rc = fd->Write(c_buf + bytes_written, count - bytes_written);
263 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
264 bytes_written += rc;
265 }
266 return true;
267}
268
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700269bool PWriteAll(const FileDescriptorPtr& fd,
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800270 const void* buf,
271 size_t count,
272 off_t offset) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700273 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
274 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800275 return WriteAll(fd, buf, count);
276}
277
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700278bool PReadAll(int fd, void* buf, size_t count, off_t offset,
279 ssize_t* out_bytes_read) {
280 char* c_buf = static_cast<char*>(buf);
281 ssize_t bytes_read = 0;
282 while (bytes_read < static_cast<ssize_t>(count)) {
283 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
284 offset + bytes_read);
285 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
286 if (rc == 0) {
287 break;
288 }
289 bytes_read += rc;
290 }
291 *out_bytes_read = bytes_read;
292 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700293}
294
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700295bool PReadAll(const FileDescriptorPtr& fd, void* buf, size_t count, off_t offset,
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800296 ssize_t* out_bytes_read) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700297 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
298 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800299 char* c_buf = static_cast<char*>(buf);
300 ssize_t bytes_read = 0;
301 while (bytes_read < static_cast<ssize_t>(count)) {
302 ssize_t rc = fd->Read(c_buf + bytes_read, count - bytes_read);
303 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
304 if (rc == 0) {
305 break;
306 }
307 bytes_read += rc;
308 }
309 *out_bytes_read = bytes_read;
310 return true;
311}
312
Gilad Arnold19a45f02012-07-19 12:36:10 -0700313// Append |nbytes| of content from |buf| to the vector pointed to by either
314// |vec_p| or |str_p|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800315static void AppendBytes(const uint8_t* buf, size_t nbytes,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700316 brillo::Blob* vec_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700317 CHECK(buf);
318 CHECK(vec_p);
319 vec_p->insert(vec_p->end(), buf, buf + nbytes);
320}
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800321static void AppendBytes(const uint8_t* buf, size_t nbytes,
Alex Deymof329b932014-10-30 01:37:48 -0700322 string* str_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700323 CHECK(buf);
324 CHECK(str_p);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800325 str_p->append(buf, buf + nbytes);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700326}
327
328// Reads from an open file |fp|, appending the read content to the container
329// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200330// file's content, false otherwise. If |size| is not -1, reads up to |size|
331// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700332template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200333static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700334 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200335 CHECK(size == -1 || size >= 0);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800336 uint8_t buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200337 while (size == -1 || size > 0) {
338 off_t bytes_to_read = sizeof(buf);
339 if (size > 0 && bytes_to_read > size) {
340 bytes_to_read = size;
341 }
342 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
343 if (!nbytes) {
344 break;
345 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700346 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200347 if (size != -1) {
348 CHECK(size >= static_cast<off_t>(nbytes));
349 size -= nbytes;
350 }
351 }
352 if (ferror(fp)) {
353 return false;
354 }
355 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700356}
357
Darin Petkov8e447e02013-04-16 16:23:50 +0200358// Opens a file |path| for reading and appends its the contents to a container
359// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
360// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700361template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700362static bool ReadFileChunkAndAppend(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200363 off_t offset,
364 off_t size,
365 T* out_p) {
366 CHECK_GE(offset, 0);
367 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700368 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200369 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000370 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200371 if (offset) {
372 // Return success without appending any data if a chunk beyond the end of
373 // the file is requested.
374 if (offset >= FileSize(path)) {
375 return true;
376 }
377 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
378 }
379 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000380}
381
Alex Deymo10875d92014-11-10 21:52:57 -0800382// TODO(deymo): This is only used in unittest, but requires the private
383// Read<string>() defined here. Expose Read<string>() or move to base/ version.
384bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700385 FILE* fp = popen(cmd.c_str(), "r");
386 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000387 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200388 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700389 return (success && pclose(fp) >= 0);
390}
391
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700392bool ReadFile(const string& path, brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200393 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700394}
395
Darin Petkov8e447e02013-04-16 16:23:50 +0200396bool ReadFile(const string& path, string* out_p) {
397 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700398}
399
Darin Petkov8e447e02013-04-16 16:23:50 +0200400bool ReadFileChunk(const string& path, off_t offset, off_t size,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700401 brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200402 return ReadFileChunkAndAppend(path, offset, size, out_p);
403}
404
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700405off_t BlockDevSize(int fd) {
406 uint64_t dev_size;
407 int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
408 if (rc == -1) {
409 dev_size = -1;
410 PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
411 }
412 return dev_size;
413}
414
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700415off_t FileSize(int fd) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700416 struct stat stbuf;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700417 int rc = fstat(fd, &stbuf);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700418 CHECK_EQ(rc, 0);
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700419 if (rc < 0) {
420 PLOG(ERROR) << "Error stat-ing " << fd;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700421 return rc;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700422 }
423 if (S_ISREG(stbuf.st_mode))
424 return stbuf.st_size;
425 if (S_ISBLK(stbuf.st_mode))
426 return BlockDevSize(fd);
427 LOG(ERROR) << "Couldn't determine the type of " << fd;
428 return -1;
429}
430
431off_t FileSize(const string& path) {
432 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
433 if (fd == -1) {
434 PLOG(ERROR) << "Error opening " << path;
435 return fd;
436 }
437 off_t size = FileSize(fd);
438 if (size == -1)
439 PLOG(ERROR) << "Error getting file size of " << path;
440 close(fd);
441 return size;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700442}
443
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800444void HexDumpArray(const uint8_t* const arr, const size_t length) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000445 LOG(INFO) << "Logging array of length: " << length;
446 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700447 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000448 const unsigned int bytes_remaining = length - i;
449 const unsigned int bytes_per_this_line = min(bytes_per_line,
450 bytes_remaining);
451 char header[100];
452 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
453 TEST_AND_RETURN(r == 13);
454 string line = header;
455 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
456 char buf[20];
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800457 uint8_t c = arr[i + j];
adlr@google.com3defe6a2009-12-04 20:57:17 +0000458 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
459 TEST_AND_RETURN(r == 3);
460 line += buf;
461 }
462 LOG(INFO) << line;
463 }
464}
465
Alex Deymof329b932014-10-30 01:37:48 -0700466bool SplitPartitionName(const string& partition_name,
467 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800468 int* out_partition_num) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800469 if (!base::StartsWith(partition_name, "/dev/",
470 base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800471 LOG(ERROR) << "Invalid partition device name: " << partition_name;
472 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700473 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800474
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700475 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
476 if (last_nondigit_pos == string::npos ||
477 (last_nondigit_pos + 1) == partition_name.size()) {
478 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800479 return false;
480 }
481
Alex Deymof329b932014-10-30 01:37:48 -0700482 size_t partition_name_len = string::npos;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700483 if (partition_name[last_nondigit_pos] == '_') {
484 // NAND block devices have weird naming which could be something
485 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
486 size_t prev_nondigit_pos =
487 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
488 if (prev_nondigit_pos == string::npos ||
489 (prev_nondigit_pos + 1) == last_nondigit_pos) {
490 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
491 return false;
492 }
493
494 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
495 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800496 }
497
498 if (out_disk_name) {
499 // Special case for MMC devices which have the following naming scheme:
500 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700501 size_t disk_name_len = last_nondigit_pos;
502 if (partition_name[last_nondigit_pos] != 'p' ||
503 last_nondigit_pos == 0 ||
504 !isdigit(partition_name[last_nondigit_pos - 1])) {
505 disk_name_len++;
506 }
507 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800508 }
509
510 if (out_partition_num) {
Alex Deymof329b932014-10-30 01:37:48 -0700511 string partition_str = partition_name.substr(last_nondigit_pos + 1,
512 partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800513 *out_partition_num = atoi(partition_str.c_str());
514 }
515 return true;
516}
517
Alex Deymof329b932014-10-30 01:37:48 -0700518string MakePartitionName(const string& disk_name, int partition_num) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800519 if (partition_num < 1) {
520 LOG(ERROR) << "Invalid partition number: " << partition_num;
521 return string();
522 }
523
Alex Vakulenko0103c362016-01-20 07:56:15 -0800524 if (!base::StartsWith(disk_name, "/dev/", base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800525 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700526 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800527 }
528
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800529 if (IsMtdDeviceName(disk_name)) {
530 // Special case for UBI block devices.
531 // 1. ubiblock is not writable, we need to use plain "ubi".
532 // 2. There is a "_0" suffix.
533 return MakeNandPartitionName(partition_num);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800534 }
535
Alex Deymof329b932014-10-30 01:37:48 -0700536 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700537 if (isdigit(partition_name.back())) {
538 // Special case for devices with names ending with a digit.
539 // Add "p" to separate the disk name from partition number,
540 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800541 partition_name += 'p';
542 }
543
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700544 partition_name += std::to_string(partition_num);
545
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800546 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700547}
548
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800549string MakePartitionNameForMount(const string& part_name) {
550 if (IsMtdDeviceName(part_name)) {
551 int partition_num;
552 if (!SplitPartitionName(part_name, nullptr, &partition_num)) {
553 return "";
554 }
555 return MakeNandPartitionNameForMount(partition_num);
556 }
557 return part_name;
558}
559
Alex Deymof329b932014-10-30 01:37:48 -0700560string ErrnoNumberAsString(int err) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000561 char buf[100];
562 buf[0] = '\0';
563 return strerror_r(err, buf, sizeof(buf));
564}
565
adlr@google.com3defe6a2009-12-04 20:57:17 +0000566bool FileExists(const char* path) {
567 struct stat stbuf;
568 return 0 == lstat(path, &stbuf);
569}
570
Darin Petkov30291ed2010-11-12 10:23:06 -0800571bool IsSymlink(const char* path) {
572 struct stat stbuf;
573 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
574}
575
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800576bool TryAttachingUbiVolume(int volume_num, int timeout) {
577 const string volume_path = base::StringPrintf("/dev/ubi%d_0", volume_num);
578 if (FileExists(volume_path.c_str())) {
579 return true;
580 }
581
582 int exit_code;
583 vector<string> cmd = {
584 "ubiattach",
585 "-m",
586 base::StringPrintf("%d", volume_num),
587 "-d",
588 base::StringPrintf("%d", volume_num)
589 };
590 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
591 TEST_AND_RETURN_FALSE(exit_code == 0);
592
593 cmd = {
594 "ubiblock",
595 "--create",
596 volume_path
597 };
598 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
599 TEST_AND_RETURN_FALSE(exit_code == 0);
600
601 while (timeout > 0 && !FileExists(volume_path.c_str())) {
602 sleep(1);
603 timeout--;
604 }
605
606 return FileExists(volume_path.c_str());
607}
608
Alex Deymof329b932014-10-30 01:37:48 -0700609bool MakeTempFile(const string& base_filename_template,
610 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700611 int* fd) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700612 base::FilePath filename_template;
613 TEST_AND_RETURN_FALSE(
614 GetTempName(base_filename_template, &filename_template));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700615 DCHECK(filename || fd);
Alex Deymo5aa1c542015-09-18 01:02:33 -0700616 vector<char> buf(filename_template.value().size() + 1);
617 memcpy(buf.data(), filename_template.value().data(),
618 filename_template.value().size());
619 buf[filename_template.value().size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700620
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800621 int mkstemp_fd = mkstemp(buf.data());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700622 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
623 if (filename) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800624 *filename = buf.data();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700625 }
626 if (fd) {
627 *fd = mkstemp_fd;
628 } else {
629 close(mkstemp_fd);
630 }
631 return true;
632}
633
Alex Deymo5fb356c2016-03-25 18:48:22 -0700634bool SetBlockDeviceReadOnly(const string& device, bool read_only) {
635 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY | O_CLOEXEC));
636 if (fd < 0) {
637 PLOG(ERROR) << "Opening block device " << device;
638 return false;
639 }
640 ScopedFdCloser fd_closer(&fd);
641 // We take no action if not needed.
642 int read_only_flag;
643 int expected_flag = read_only ? 1 : 0;
644 int rc = ioctl(fd, BLKROGET, &read_only_flag);
645 // In case of failure reading the setting we will try to set it anyway.
646 if (rc == 0 && read_only_flag == expected_flag)
647 return true;
648
649 rc = ioctl(fd, BLKROSET, &expected_flag);
650 if (rc != 0) {
651 PLOG(ERROR) << "Marking block device " << device << " as read_only="
652 << expected_flag;
653 return false;
654 }
655 return true;
656}
657
adlr@google.com3defe6a2009-12-04 20:57:17 +0000658bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700659 const string& mountpoint,
Alex Deymo390efed2016-02-18 11:00:40 -0800660 unsigned long mountflags, // NOLINT(runtime/int)
Alex Deymo14dbd332016-03-01 18:55:54 -0800661 const string& type,
662 const string& fs_mount_options) {
Alex Deymo390efed2016-02-18 11:00:40 -0800663 vector<const char*> fstypes;
664 if (type.empty()) {
665 fstypes = {"ext2", "ext3", "ext4", "squashfs"};
666 } else {
667 fstypes = {type.c_str()};
668 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800669 for (const char* fstype : fstypes) {
670 int rc = mount(device.c_str(), mountpoint.c_str(), fstype, mountflags,
Alex Deymo14dbd332016-03-01 18:55:54 -0800671 fs_mount_options.c_str());
Alex Deymo4c82df32014-11-10 22:25:57 -0800672 if (rc == 0)
673 return true;
674
675 PLOG(WARNING) << "Unable to mount destination device " << device
676 << " on " << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000677 }
Alex Deymo390efed2016-02-18 11:00:40 -0800678 if (!type.empty()) {
679 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
680 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800681 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000682}
683
684bool UnmountFilesystem(const string& mountpoint) {
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700685 int num_retries = 1;
686 for (;; ++num_retries) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700687 if (umount(mountpoint.c_str()) == 0)
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700688 return true;
689 if (errno != EBUSY || num_retries >= kUnmountMaxNumOfRetries)
Ben Chan77a1eba2012-10-07 22:54:55 -0700690 break;
Alex Deymo8d2bbe32015-06-23 16:28:59 -0700691 usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700692 }
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700693 if (errno == EINVAL) {
694 LOG(INFO) << "Not a mountpoint: " << mountpoint;
695 return false;
696 }
697 PLOG(WARNING) << "Error unmounting " << mountpoint << " after " << num_retries
698 << " attempts. Lazy unmounting instead, error was";
699 if (umount2(mountpoint.c_str(), MNT_DETACH) != 0) {
700 PLOG(ERROR) << "Lazy unmount failed";
701 return false;
702 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000703 return true;
704}
705
Alex Deymo032e7722014-03-25 17:53:56 -0700706// Tries to parse the header of an ELF file to obtain a human-readable
707// description of it on the |output| string.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800708static bool GetFileFormatELF(const uint8_t* buffer, size_t size,
709 string* output) {
Alex Deymo032e7722014-03-25 17:53:56 -0700710 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700711 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700712 return false;
713 *output = "ELF";
714
715 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700716 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700717 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700718 switch (buffer[EI_CLASS]) {
719 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700720 *output += " 32-bit";
721 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700722 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700723 *output += " 64-bit";
724 break;
725 default:
726 *output += " ?-bit";
727 }
728
729 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700730 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700731 return true;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800732 uint8_t ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700733 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700734 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700735 *output += " little-endian";
736 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700737 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700738 *output += " big-endian";
739 break;
740 default:
741 *output += " ?-endian";
742 // Don't parse anything after the 0x10 offset if endianness is unknown.
743 return true;
744 }
745
Alex Deymoc1711e22014-08-08 13:16:23 -0700746 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
747 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
748 // and size is the same for both 32 and 64 bits.
749 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700750 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700751 uint16_t e_machine;
Alex Deymo032e7722014-03-25 17:53:56 -0700752 // Fix endianess regardless of the host endianess.
Alex Deymoc1711e22014-08-08 13:16:23 -0700753 if (ei_data == ELFDATA2LSB)
754 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700755 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700756 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700757
758 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700759 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700760 *output += " x86";
761 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700762 case EM_MIPS:
763 *output += " mips";
764 break;
765 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700766 *output += " arm";
767 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700768 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700769 *output += " x86-64";
770 break;
771 default:
772 *output += " unknown-arch";
773 }
774 return true;
775}
776
777string GetFileFormat(const string& path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700778 brillo::Blob buffer;
Alex Deymo032e7722014-03-25 17:53:56 -0700779 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
780 return "File not found.";
781
782 string result;
783 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
784 return result;
785
786 return "data";
787}
788
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700789int FuzzInt(int value, unsigned int range) {
790 int min = value - range / 2;
791 int max = value + range - range / 2;
792 return base::RandInt(min, max);
793}
794
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700795string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800796 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700797}
798
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800799string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400800 string str;
801
802 // Handle negative durations by prefixing with a minus.
803 if (delta.ToInternalValue() < 0) {
804 delta *= -1;
805 str = "-";
806 }
807
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700808 // Canonicalize into days, hours, minutes, seconds and microseconds.
809 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800810 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700811 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800812 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700813 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800814 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700815 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800816 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700817 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800818
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700819 if (days)
820 base::StringAppendF(&str, "%ud", days);
821 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800822 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700823 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800824 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700825 base::StringAppendF(&str, "%u", secs);
826 if (usecs) {
827 int width = 6;
828 while ((usecs / 10) * 10 == usecs) {
829 usecs /= 10;
830 width--;
831 }
832 base::StringAppendF(&str, ".%0*u", width, usecs);
833 }
834 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800835 return str;
836}
837
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700838string ToString(const Time utc_time) {
839 Time::Exploded exp_time;
840 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700841 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700842 exp_time.month,
843 exp_time.day_of_month,
844 exp_time.year,
845 exp_time.hour,
846 exp_time.minute,
847 exp_time.second);
848}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000849
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700850string ToString(bool b) {
851 return (b ? "true" : "false");
852}
853
Alex Deymo1c656c42013-06-28 11:02:14 -0700854string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700855 switch (source) {
856 case kDownloadSourceHttpsServer: return "HttpsServer";
857 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700858 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -0700859 case kNumDownloadSources: return "Unknown";
860 // Don't add a default case to let the compiler warn about newly added
861 // download sources which should be added here.
862 }
863
864 return "Unknown";
865}
866
Alex Deymo1c656c42013-06-28 11:02:14 -0700867string ToString(PayloadType payload_type) {
868 switch (payload_type) {
869 case kPayloadTypeDelta: return "Delta";
870 case kPayloadTypeFull: return "Full";
871 case kPayloadTypeForcedFull: return "ForcedFull";
872 case kNumPayloadTypes: return "Unknown";
873 // Don't add a default case to let the compiler warn about newly added
874 // payload types which should be added here.
875 }
876
877 return "Unknown";
878}
879
David Zeuthena99981f2013-04-29 13:42:47 -0700880ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700881 // Ignore the higher order bits in the code by applying the mask as
882 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700883 // with values less than ErrorCode::kUmaReportedMax.
884 ErrorCode base_code = static_cast<ErrorCode>(
885 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -0700886
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800887 // Make additional adjustments required for UMA and error classification.
888 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
889 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700890 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700891 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800892 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800893 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700894 << " to ErrorCode::kOmahaErrorInHTTPResponse";
895 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700896 }
897
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800898 return base_code;
899}
900
David Zeuthen27a48bc2013-08-06 12:06:29 -0700901Time TimeFromStructTimespec(struct timespec *ts) {
Ben Chan9abb7632014-08-07 00:10:53 -0700902 int64_t us = static_cast<int64_t>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
903 static_cast<int64_t>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700904 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
905}
906
Alex Deymof329b932014-10-30 01:37:48 -0700907string StringVectorToString(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700908 string str = "[";
Alex Deymof329b932014-10-30 01:37:48 -0700909 for (vector<string>::const_iterator i = vec_str.begin();
910 i != vec_str.end(); ++i) {
911 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -0700912 str += ", ";
913 str += '"';
914 str += *i;
915 str += '"';
916 }
917 str += "]";
918 return str;
919}
920
David Zeuthen8f191b22013-08-06 12:27:50 -0700921string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700922 string encoded_hash = brillo::data_encoding::Base64Encode(payload_hash);
Alex Deymoc00c98a2015-03-17 17:38:00 -0700923 return base::StringPrintf("cros_update_size_%" PRIuS "_hash_%s",
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800924 payload_size,
925 encoded_hash.c_str());
David Zeuthen8f191b22013-08-06 12:27:50 -0700926}
927
Alex Deymof329b932014-10-30 01:37:48 -0700928bool DecodeAndStoreBase64String(const string& base64_encoded,
David Zeuthene7f89172013-10-31 10:21:04 -0700929 base::FilePath *out_path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700930 brillo::Blob contents;
David Zeuthene7f89172013-10-31 10:21:04 -0700931
932 out_path->clear();
933
934 if (base64_encoded.size() == 0) {
935 LOG(ERROR) << "Can't decode empty string.";
936 return false;
937 }
938
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700939 if (!brillo::data_encoding::Base64Decode(base64_encoded, &contents) ||
David Zeuthene7f89172013-10-31 10:21:04 -0700940 contents.size() == 0) {
941 LOG(ERROR) << "Error decoding base64.";
942 return false;
943 }
944
Alex Vakulenko75039d72014-03-25 12:36:28 -0700945 FILE *file = base::CreateAndOpenTemporaryFile(out_path);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700946 if (file == nullptr) {
David Zeuthene7f89172013-10-31 10:21:04 -0700947 LOG(ERROR) << "Error creating temporary file.";
948 return false;
949 }
950
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800951 if (fwrite(contents.data(), 1, contents.size(), file) != contents.size()) {
David Zeuthene7f89172013-10-31 10:21:04 -0700952 PLOG(ERROR) << "Error writing to temporary file.";
953 if (fclose(file) != 0)
954 PLOG(ERROR) << "Error closing temporary file.";
955 if (unlink(out_path->value().c_str()) != 0)
956 PLOG(ERROR) << "Error unlinking temporary file.";
957 out_path->clear();
958 return false;
959 }
960
961 if (fclose(file) != 0) {
962 PLOG(ERROR) << "Error closing temporary file.";
963 out_path->clear();
964 return false;
965 }
966
967 return true;
968}
969
Alex Deymof329b932014-10-30 01:37:48 -0700970bool ConvertToOmahaInstallDate(Time time, int *out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -0800971 time_t unix_time = time.ToTimeT();
972 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
973 const time_t kOmahaEpoch = 1167638400;
974 const int64_t kNumSecondsPerWeek = 7*24*3600;
975 const int64_t kNumDaysPerWeek = 7;
976
977 time_t omaha_time = unix_time - kOmahaEpoch;
978
979 if (omaha_time < 0)
980 return false;
981
982 // Note, as per the comment in utils.h we are deliberately not
983 // handling DST correctly.
984
985 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
986 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
987
988 return true;
989}
990
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700991bool GetMinorVersion(const brillo::KeyValueStore& store,
Alex Deymob42b98d2015-07-06 17:42:38 -0700992 uint32_t* minor_version) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700993 string result;
Alex Deymob42b98d2015-07-06 17:42:38 -0700994 if (store.GetString("PAYLOAD_MINOR_VERSION", &result)) {
Allie Wood425aa972015-02-17 14:47:17 -0800995 if (!base::StringToUint(result, minor_version)) {
996 LOG(ERROR) << "StringToUint failed when parsing delta minor version.";
997 return false;
998 }
Allie Wood78750a42015-02-11 15:42:11 -0800999 return true;
1000 }
1001 return false;
1002}
1003
Sen Jiange0d04282016-03-01 14:22:52 -08001004bool IsZlibCompatible(const string& fingerprint) {
1005 if (fingerprint.size() != sizeof(kCompatibleZlibFingerprint[0]) - 1) {
1006 LOG(ERROR) << "Invalid fingerprint: " << fingerprint;
1007 return false;
1008 }
1009 for (auto& f : kCompatibleZlibFingerprint) {
1010 if (base::CompareCaseInsensitiveASCII(fingerprint, f) == 0) {
1011 return true;
1012 }
1013 }
1014 return false;
1015}
1016
Alex Deymo60ca1a72015-06-18 18:19:15 -07001017bool ReadExtents(const string& path, const vector<Extent>& extents,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001018 brillo::Blob* out_data, ssize_t out_data_size,
Allie Wood56873452015-03-27 17:48:40 -07001019 size_t block_size) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001020 brillo::Blob data(out_data_size);
Allie Wood56873452015-03-27 17:48:40 -07001021 ssize_t bytes_read = 0;
1022 int fd = open(path.c_str(), O_RDONLY);
1023 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
1024 ScopedFdCloser fd_closer(&fd);
1025
Gilad Arnold41e34742015-05-11 11:31:50 -07001026 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -07001027 ssize_t bytes_read_this_iteration = 0;
1028 ssize_t bytes = extent.num_blocks() * block_size;
1029 TEST_AND_RETURN_FALSE(bytes_read + bytes <= out_data_size);
1030 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
1031 &data[bytes_read],
1032 bytes,
1033 extent.start_block() * block_size,
1034 &bytes_read_this_iteration));
1035 TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes);
1036 bytes_read += bytes_read_this_iteration;
1037 }
1038 TEST_AND_RETURN_FALSE(out_data_size == bytes_read);
1039 *out_data = data;
1040 return true;
1041}
1042
Alex Deymodd132f32015-09-14 19:12:07 -07001043bool GetBootId(string* boot_id) {
1044 TEST_AND_RETURN_FALSE(
1045 base::ReadFileToString(base::FilePath(kBootIdPath), boot_id));
1046 base::TrimWhitespaceASCII(*boot_id, base::TRIM_TRAILING, boot_id);
1047 return true;
1048}
1049
adlr@google.com3defe6a2009-12-04 20:57:17 +00001050} // namespace utils
1051
1052} // namespace chromeos_update_engine