blob: 1e04b61736d38f58f06bb7e4aa7f4d0f290b70d4 [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"
Sen Jiange0d04282016-03-01 14:22:52 -080061#include "update_engine/payload_consumer/payload_constants.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000062
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070063using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080064using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000065using std::min;
Chris Sosac1972482013-04-30 22:31:10 -070066using std::pair;
adlr@google.com3defe6a2009-12-04 20:57:17 +000067using std::string;
68using std::vector;
69
70namespace chromeos_update_engine {
71
Ben Chan77a1eba2012-10-07 22:54:55 -070072namespace {
73
74// The following constants control how UnmountFilesystem should retry if
75// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
76// one second.
77const int kUnmountMaxNumOfRetries = 5;
78const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Alex Deymo032e7722014-03-25 17:53:56 -070079
80// Number of bytes to read from a file to attempt to detect its contents. Used
81// in GetFileFormat.
82const int kGetFileFormatMaxHeaderSize = 32;
83
Alex Deymodd132f32015-09-14 19:12:07 -070084// The path to the kernel's boot_id.
85const char kBootIdPath[] = "/proc/sys/kernel/random/boot_id";
86
Alex Deymo32951022016-08-10 17:02:49 -070087// A pointer to a null-terminated string containing the root directory where all
88// the temporary files should be created. If null, the system default is used
89// instead.
90const char* root_temp_dir = nullptr;
91
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080092// Return true if |disk_name| is an MTD or a UBI device. Note that this test is
93// simply based on the name of the device.
94bool IsMtdDeviceName(const string& disk_name) {
Alex Vakulenko0103c362016-01-20 07:56:15 -080095 return base::StartsWith(disk_name, "/dev/ubi",
96 base::CompareCase::SENSITIVE) ||
97 base::StartsWith(disk_name, "/dev/mtd", base::CompareCase::SENSITIVE);
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080098}
99
100// Return the device name for the corresponding partition on a NAND device.
101// WARNING: This function returns device names that are not mountable.
102string MakeNandPartitionName(int partition_num) {
103 switch (partition_num) {
104 case 2:
105 case 4:
106 case 6: {
107 return base::StringPrintf("/dev/mtd%d", partition_num);
108 }
109 default: {
110 return base::StringPrintf("/dev/ubi%d_0", partition_num);
111 }
112 }
113}
114
115// Return the device name for the corresponding partition on a NAND device that
116// may be mountable (but may not be writable).
117string MakeNandPartitionNameForMount(int partition_num) {
118 switch (partition_num) {
119 case 2:
120 case 4:
121 case 6: {
122 return base::StringPrintf("/dev/mtd%d", partition_num);
123 }
124 case 3:
125 case 5:
126 case 7: {
127 return base::StringPrintf("/dev/ubiblock%d_0", partition_num);
128 }
129 default: {
130 return base::StringPrintf("/dev/ubi%d_0", partition_num);
131 }
132 }
133}
134
Alex Deymo5aa1c542015-09-18 01:02:33 -0700135// If |path| is absolute, or explicit relative to the current working directory,
136// leaves it as is. Otherwise, uses the system's temp directory, as defined by
137// base::GetTempDir() and prepends it to |path|. On success stores the full
138// temporary path in |template_path| and returns true.
139bool GetTempName(const string& path, base::FilePath* template_path) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800140 if (path[0] == '/' ||
141 base::StartsWith(path, "./", base::CompareCase::SENSITIVE) ||
142 base::StartsWith(path, "../", base::CompareCase::SENSITIVE)) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700143 *template_path = base::FilePath(path);
144 return true;
145 }
146
147 base::FilePath temp_dir;
Alex Deymo32951022016-08-10 17:02:49 -0700148 if (root_temp_dir) {
149 temp_dir = base::FilePath(root_temp_dir);
150 } else {
Sen Jiang9c123462015-11-19 13:16:23 -0800151#ifdef __ANDROID__
Alex Deymo32951022016-08-10 17:02:49 -0700152 temp_dir = base::FilePath(constants::kNonVolatileDirectory).Append("tmp");
153#else
154 TEST_AND_RETURN_FALSE(base::GetTempDir(&temp_dir));
155#endif // __ANDROID__
156 }
Sen Jiang9c123462015-11-19 13:16:23 -0800157 if (!base::PathExists(temp_dir))
158 TEST_AND_RETURN_FALSE(base::CreateDirectory(temp_dir));
Alex Deymo5aa1c542015-09-18 01:02:33 -0700159 *template_path = temp_dir.Append(path);
160 return true;
161}
162
Ben Chan77a1eba2012-10-07 22:54:55 -0700163} // namespace
164
adlr@google.com3defe6a2009-12-04 20:57:17 +0000165namespace utils {
166
Alex Deymo32951022016-08-10 17:02:49 -0700167void SetRootTempDir(const char* new_root_temp_dir) {
168 root_temp_dir = new_root_temp_dir;
169}
170
J. Richard Barnette63137e52013-10-28 10:57:29 -0700171string ParseECVersion(string input_line) {
Ben Chan736fcb52014-05-21 18:28:22 -0700172 base::TrimWhitespaceASCII(input_line, base::TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -0700173
Alex Vakulenko75039d72014-03-25 12:36:28 -0700174 // At this point we want to convert the format key=value pair from mosys to
Chris Sosac1972482013-04-30 22:31:10 -0700175 // a vector of key value pairs.
Ben Chanf9cb98c2014-09-21 18:31:30 -0700176 vector<pair<string, string>> kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -0700177 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Alex Deymo020600d2014-11-05 21:05:55 -0800178 for (const pair<string, string>& kv_pair : kv_pairs) {
Chris Sosac1972482013-04-30 22:31:10 -0700179 // Finally match against the fw_verion which may have quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800180 if (kv_pair.first == "fw_version") {
Chris Sosac1972482013-04-30 22:31:10 -0700181 string output;
182 // Trim any quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800183 base::TrimString(kv_pair.second, "\"", &output);
Chris Sosac1972482013-04-30 22:31:10 -0700184 return output;
185 }
186 }
187 }
188 LOG(ERROR) << "Unable to parse fwid from ec info.";
189 return "";
190}
191
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800192bool WriteFile(const char* path, const void* data, int data_len) {
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800193 DirectFileWriter writer;
194 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
195 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700196 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800197 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800198 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800199 return true;
200}
201
Alex Deymo0d298542016-03-30 18:31:49 -0700202bool ReadAll(
203 int fd, void* buf, size_t count, size_t* out_bytes_read, bool* eof) {
204 char* c_buf = static_cast<char*>(buf);
205 size_t bytes_read = 0;
206 *eof = false;
207 while (bytes_read < count) {
208 ssize_t rc = HANDLE_EINTR(read(fd, c_buf + bytes_read, count - bytes_read));
209 if (rc < 0) {
210 // EAGAIN and EWOULDBLOCK are normal return values when there's no more
211 // input and we are in non-blocking mode.
212 if (errno != EWOULDBLOCK && errno != EAGAIN) {
213 PLOG(ERROR) << "Error reading fd " << fd;
214 *out_bytes_read = bytes_read;
215 return false;
216 }
217 break;
218 } else if (rc == 0) {
219 // A value of 0 means that we reached EOF and there is nothing else to
220 // read from this fd.
221 *eof = true;
222 break;
223 } else {
224 bytes_read += rc;
225 }
226 }
227 *out_bytes_read = bytes_read;
228 return true;
229}
230
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700231bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700232 const char* c_buf = static_cast<const char*>(buf);
233 ssize_t bytes_written = 0;
234 while (bytes_written < static_cast<ssize_t>(count)) {
235 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
236 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
237 bytes_written += rc;
238 }
239 return true;
240}
241
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700242bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
243 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700244 size_t bytes_written = 0;
245 int num_attempts = 0;
246 while (bytes_written < count) {
247 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700248 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
249 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700250 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
251 if (rc < 0) {
252 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
253 << " bytes_written=" << bytes_written
254 << " count=" << count << " offset=" << offset;
255 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700256 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
257 bytes_written += rc;
258 }
259 return true;
260}
261
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700262bool WriteAll(const FileDescriptorPtr& fd, const void* buf, size_t count) {
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800263 const char* c_buf = static_cast<const char*>(buf);
264 ssize_t bytes_written = 0;
265 while (bytes_written < static_cast<ssize_t>(count)) {
266 ssize_t rc = fd->Write(c_buf + bytes_written, count - bytes_written);
267 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
268 bytes_written += rc;
269 }
270 return true;
271}
272
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700273bool PWriteAll(const FileDescriptorPtr& fd,
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800274 const void* buf,
275 size_t count,
276 off_t offset) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700277 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
278 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800279 return WriteAll(fd, buf, count);
280}
281
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700282bool PReadAll(int fd, void* buf, size_t count, off_t offset,
283 ssize_t* out_bytes_read) {
284 char* c_buf = static_cast<char*>(buf);
285 ssize_t bytes_read = 0;
286 while (bytes_read < static_cast<ssize_t>(count)) {
287 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
288 offset + bytes_read);
289 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
290 if (rc == 0) {
291 break;
292 }
293 bytes_read += rc;
294 }
295 *out_bytes_read = bytes_read;
296 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700297}
298
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700299bool PReadAll(const FileDescriptorPtr& fd, void* buf, size_t count, off_t offset,
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800300 ssize_t* out_bytes_read) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700301 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
302 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800303 char* c_buf = static_cast<char*>(buf);
304 ssize_t bytes_read = 0;
305 while (bytes_read < static_cast<ssize_t>(count)) {
306 ssize_t rc = fd->Read(c_buf + bytes_read, count - bytes_read);
307 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
308 if (rc == 0) {
309 break;
310 }
311 bytes_read += rc;
312 }
313 *out_bytes_read = bytes_read;
314 return true;
315}
316
Gilad Arnold19a45f02012-07-19 12:36:10 -0700317// Append |nbytes| of content from |buf| to the vector pointed to by either
318// |vec_p| or |str_p|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800319static void AppendBytes(const uint8_t* buf, size_t nbytes,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700320 brillo::Blob* vec_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700321 CHECK(buf);
322 CHECK(vec_p);
323 vec_p->insert(vec_p->end(), buf, buf + nbytes);
324}
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800325static void AppendBytes(const uint8_t* buf, size_t nbytes,
Alex Deymof329b932014-10-30 01:37:48 -0700326 string* str_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700327 CHECK(buf);
328 CHECK(str_p);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800329 str_p->append(buf, buf + nbytes);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700330}
331
332// Reads from an open file |fp|, appending the read content to the container
333// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200334// file's content, false otherwise. If |size| is not -1, reads up to |size|
335// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700336template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200337static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700338 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200339 CHECK(size == -1 || size >= 0);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800340 uint8_t buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200341 while (size == -1 || size > 0) {
342 off_t bytes_to_read = sizeof(buf);
343 if (size > 0 && bytes_to_read > size) {
344 bytes_to_read = size;
345 }
346 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
347 if (!nbytes) {
348 break;
349 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700350 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200351 if (size != -1) {
352 CHECK(size >= static_cast<off_t>(nbytes));
353 size -= nbytes;
354 }
355 }
356 if (ferror(fp)) {
357 return false;
358 }
359 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700360}
361
Darin Petkov8e447e02013-04-16 16:23:50 +0200362// Opens a file |path| for reading and appends its the contents to a container
363// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
364// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700365template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700366static bool ReadFileChunkAndAppend(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200367 off_t offset,
368 off_t size,
369 T* out_p) {
370 CHECK_GE(offset, 0);
371 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700372 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200373 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000374 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200375 if (offset) {
376 // Return success without appending any data if a chunk beyond the end of
377 // the file is requested.
378 if (offset >= FileSize(path)) {
379 return true;
380 }
381 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
382 }
383 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000384}
385
Alex Deymo10875d92014-11-10 21:52:57 -0800386// TODO(deymo): This is only used in unittest, but requires the private
387// Read<string>() defined here. Expose Read<string>() or move to base/ version.
388bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700389 FILE* fp = popen(cmd.c_str(), "r");
390 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000391 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200392 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700393 return (success && pclose(fp) >= 0);
394}
395
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700396bool ReadFile(const string& path, brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200397 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700398}
399
Darin Petkov8e447e02013-04-16 16:23:50 +0200400bool ReadFile(const string& path, string* out_p) {
401 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700402}
403
Darin Petkov8e447e02013-04-16 16:23:50 +0200404bool ReadFileChunk(const string& path, off_t offset, off_t size,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700405 brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200406 return ReadFileChunkAndAppend(path, offset, size, out_p);
407}
408
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700409off_t BlockDevSize(int fd) {
410 uint64_t dev_size;
411 int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
412 if (rc == -1) {
413 dev_size = -1;
414 PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
415 }
416 return dev_size;
417}
418
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700419off_t FileSize(int fd) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700420 struct stat stbuf;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700421 int rc = fstat(fd, &stbuf);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700422 CHECK_EQ(rc, 0);
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700423 if (rc < 0) {
424 PLOG(ERROR) << "Error stat-ing " << fd;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700425 return rc;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700426 }
427 if (S_ISREG(stbuf.st_mode))
428 return stbuf.st_size;
429 if (S_ISBLK(stbuf.st_mode))
430 return BlockDevSize(fd);
431 LOG(ERROR) << "Couldn't determine the type of " << fd;
432 return -1;
433}
434
435off_t FileSize(const string& path) {
436 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
437 if (fd == -1) {
438 PLOG(ERROR) << "Error opening " << path;
439 return fd;
440 }
441 off_t size = FileSize(fd);
442 if (size == -1)
443 PLOG(ERROR) << "Error getting file size of " << path;
444 close(fd);
445 return size;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700446}
447
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800448void HexDumpArray(const uint8_t* const arr, const size_t length) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000449 LOG(INFO) << "Logging array of length: " << length;
450 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700451 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000452 const unsigned int bytes_remaining = length - i;
453 const unsigned int bytes_per_this_line = min(bytes_per_line,
454 bytes_remaining);
455 char header[100];
456 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
457 TEST_AND_RETURN(r == 13);
458 string line = header;
459 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
460 char buf[20];
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800461 uint8_t c = arr[i + j];
adlr@google.com3defe6a2009-12-04 20:57:17 +0000462 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
463 TEST_AND_RETURN(r == 3);
464 line += buf;
465 }
466 LOG(INFO) << line;
467 }
468}
469
Alex Deymof329b932014-10-30 01:37:48 -0700470bool SplitPartitionName(const string& partition_name,
471 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800472 int* out_partition_num) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800473 if (!base::StartsWith(partition_name, "/dev/",
474 base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800475 LOG(ERROR) << "Invalid partition device name: " << partition_name;
476 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700477 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800478
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700479 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
480 if (last_nondigit_pos == string::npos ||
481 (last_nondigit_pos + 1) == partition_name.size()) {
482 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800483 return false;
484 }
485
Alex Deymof329b932014-10-30 01:37:48 -0700486 size_t partition_name_len = string::npos;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700487 if (partition_name[last_nondigit_pos] == '_') {
488 // NAND block devices have weird naming which could be something
489 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
490 size_t prev_nondigit_pos =
491 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
492 if (prev_nondigit_pos == string::npos ||
493 (prev_nondigit_pos + 1) == last_nondigit_pos) {
494 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
495 return false;
496 }
497
498 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
499 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800500 }
501
502 if (out_disk_name) {
503 // Special case for MMC devices which have the following naming scheme:
504 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700505 size_t disk_name_len = last_nondigit_pos;
506 if (partition_name[last_nondigit_pos] != 'p' ||
507 last_nondigit_pos == 0 ||
508 !isdigit(partition_name[last_nondigit_pos - 1])) {
509 disk_name_len++;
510 }
511 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800512 }
513
514 if (out_partition_num) {
Alex Deymof329b932014-10-30 01:37:48 -0700515 string partition_str = partition_name.substr(last_nondigit_pos + 1,
516 partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800517 *out_partition_num = atoi(partition_str.c_str());
518 }
519 return true;
520}
521
Alex Deymof329b932014-10-30 01:37:48 -0700522string MakePartitionName(const string& disk_name, int partition_num) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800523 if (partition_num < 1) {
524 LOG(ERROR) << "Invalid partition number: " << partition_num;
525 return string();
526 }
527
Alex Vakulenko0103c362016-01-20 07:56:15 -0800528 if (!base::StartsWith(disk_name, "/dev/", base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800529 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700530 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800531 }
532
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800533 if (IsMtdDeviceName(disk_name)) {
534 // Special case for UBI block devices.
535 // 1. ubiblock is not writable, we need to use plain "ubi".
536 // 2. There is a "_0" suffix.
537 return MakeNandPartitionName(partition_num);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800538 }
539
Alex Deymof329b932014-10-30 01:37:48 -0700540 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700541 if (isdigit(partition_name.back())) {
542 // Special case for devices with names ending with a digit.
543 // Add "p" to separate the disk name from partition number,
544 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800545 partition_name += 'p';
546 }
547
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700548 partition_name += std::to_string(partition_num);
549
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800550 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700551}
552
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800553string MakePartitionNameForMount(const string& part_name) {
554 if (IsMtdDeviceName(part_name)) {
555 int partition_num;
556 if (!SplitPartitionName(part_name, nullptr, &partition_num)) {
557 return "";
558 }
559 return MakeNandPartitionNameForMount(partition_num);
560 }
561 return part_name;
562}
563
Alex Deymof329b932014-10-30 01:37:48 -0700564string ErrnoNumberAsString(int err) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000565 char buf[100];
566 buf[0] = '\0';
567 return strerror_r(err, buf, sizeof(buf));
568}
569
adlr@google.com3defe6a2009-12-04 20:57:17 +0000570bool FileExists(const char* path) {
571 struct stat stbuf;
572 return 0 == lstat(path, &stbuf);
573}
574
Darin Petkov30291ed2010-11-12 10:23:06 -0800575bool IsSymlink(const char* path) {
576 struct stat stbuf;
577 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
578}
579
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800580bool TryAttachingUbiVolume(int volume_num, int timeout) {
581 const string volume_path = base::StringPrintf("/dev/ubi%d_0", volume_num);
582 if (FileExists(volume_path.c_str())) {
583 return true;
584 }
585
586 int exit_code;
587 vector<string> cmd = {
588 "ubiattach",
589 "-m",
590 base::StringPrintf("%d", volume_num),
591 "-d",
592 base::StringPrintf("%d", volume_num)
593 };
594 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
595 TEST_AND_RETURN_FALSE(exit_code == 0);
596
597 cmd = {
598 "ubiblock",
599 "--create",
600 volume_path
601 };
602 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
603 TEST_AND_RETURN_FALSE(exit_code == 0);
604
605 while (timeout > 0 && !FileExists(volume_path.c_str())) {
606 sleep(1);
607 timeout--;
608 }
609
610 return FileExists(volume_path.c_str());
611}
612
Alex Deymof329b932014-10-30 01:37:48 -0700613bool MakeTempFile(const string& base_filename_template,
614 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700615 int* fd) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700616 base::FilePath filename_template;
617 TEST_AND_RETURN_FALSE(
618 GetTempName(base_filename_template, &filename_template));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700619 DCHECK(filename || fd);
Alex Deymo5aa1c542015-09-18 01:02:33 -0700620 vector<char> buf(filename_template.value().size() + 1);
621 memcpy(buf.data(), filename_template.value().data(),
622 filename_template.value().size());
623 buf[filename_template.value().size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700624
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800625 int mkstemp_fd = mkstemp(buf.data());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700626 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
627 if (filename) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800628 *filename = buf.data();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700629 }
630 if (fd) {
631 *fd = mkstemp_fd;
632 } else {
633 close(mkstemp_fd);
634 }
635 return true;
636}
637
Alex Deymo5fb356c2016-03-25 18:48:22 -0700638bool SetBlockDeviceReadOnly(const string& device, bool read_only) {
639 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY | O_CLOEXEC));
640 if (fd < 0) {
641 PLOG(ERROR) << "Opening block device " << device;
642 return false;
643 }
644 ScopedFdCloser fd_closer(&fd);
645 // We take no action if not needed.
646 int read_only_flag;
647 int expected_flag = read_only ? 1 : 0;
648 int rc = ioctl(fd, BLKROGET, &read_only_flag);
649 // In case of failure reading the setting we will try to set it anyway.
650 if (rc == 0 && read_only_flag == expected_flag)
651 return true;
652
653 rc = ioctl(fd, BLKROSET, &expected_flag);
654 if (rc != 0) {
655 PLOG(ERROR) << "Marking block device " << device << " as read_only="
656 << expected_flag;
657 return false;
658 }
659 return true;
660}
661
adlr@google.com3defe6a2009-12-04 20:57:17 +0000662bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700663 const string& mountpoint,
Alex Deymo390efed2016-02-18 11:00:40 -0800664 unsigned long mountflags, // NOLINT(runtime/int)
Alex Deymo14dbd332016-03-01 18:55:54 -0800665 const string& type,
666 const string& fs_mount_options) {
Alex Deymo390efed2016-02-18 11:00:40 -0800667 vector<const char*> fstypes;
668 if (type.empty()) {
669 fstypes = {"ext2", "ext3", "ext4", "squashfs"};
670 } else {
671 fstypes = {type.c_str()};
672 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800673 for (const char* fstype : fstypes) {
674 int rc = mount(device.c_str(), mountpoint.c_str(), fstype, mountflags,
Alex Deymo14dbd332016-03-01 18:55:54 -0800675 fs_mount_options.c_str());
Alex Deymo4c82df32014-11-10 22:25:57 -0800676 if (rc == 0)
677 return true;
678
679 PLOG(WARNING) << "Unable to mount destination device " << device
680 << " on " << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000681 }
Alex Deymo390efed2016-02-18 11:00:40 -0800682 if (!type.empty()) {
683 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
684 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800685 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000686}
687
688bool UnmountFilesystem(const string& mountpoint) {
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700689 int num_retries = 1;
690 for (;; ++num_retries) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700691 if (umount(mountpoint.c_str()) == 0)
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700692 return true;
693 if (errno != EBUSY || num_retries >= kUnmountMaxNumOfRetries)
Ben Chan77a1eba2012-10-07 22:54:55 -0700694 break;
Alex Deymo8d2bbe32015-06-23 16:28:59 -0700695 usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700696 }
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700697 if (errno == EINVAL) {
698 LOG(INFO) << "Not a mountpoint: " << mountpoint;
699 return false;
700 }
701 PLOG(WARNING) << "Error unmounting " << mountpoint << " after " << num_retries
702 << " attempts. Lazy unmounting instead, error was";
703 if (umount2(mountpoint.c_str(), MNT_DETACH) != 0) {
704 PLOG(ERROR) << "Lazy unmount failed";
705 return false;
706 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000707 return true;
708}
709
Alex Deymo032e7722014-03-25 17:53:56 -0700710// Tries to parse the header of an ELF file to obtain a human-readable
711// description of it on the |output| string.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800712static bool GetFileFormatELF(const uint8_t* buffer, size_t size,
713 string* output) {
Alex Deymo032e7722014-03-25 17:53:56 -0700714 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700715 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700716 return false;
717 *output = "ELF";
718
719 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700720 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700721 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700722 switch (buffer[EI_CLASS]) {
723 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700724 *output += " 32-bit";
725 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700726 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700727 *output += " 64-bit";
728 break;
729 default:
730 *output += " ?-bit";
731 }
732
733 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700734 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700735 return true;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800736 uint8_t ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700737 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700738 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700739 *output += " little-endian";
740 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700741 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700742 *output += " big-endian";
743 break;
744 default:
745 *output += " ?-endian";
746 // Don't parse anything after the 0x10 offset if endianness is unknown.
747 return true;
748 }
749
Alex Deymoc1711e22014-08-08 13:16:23 -0700750 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
751 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
752 // and size is the same for both 32 and 64 bits.
753 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700754 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700755 uint16_t e_machine;
Alex Deymo032e7722014-03-25 17:53:56 -0700756 // Fix endianess regardless of the host endianess.
Alex Deymoc1711e22014-08-08 13:16:23 -0700757 if (ei_data == ELFDATA2LSB)
758 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700759 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700760 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700761
762 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700763 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700764 *output += " x86";
765 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700766 case EM_MIPS:
767 *output += " mips";
768 break;
769 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700770 *output += " arm";
771 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700772 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700773 *output += " x86-64";
774 break;
775 default:
776 *output += " unknown-arch";
777 }
778 return true;
779}
780
781string GetFileFormat(const string& path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700782 brillo::Blob buffer;
Alex Deymo032e7722014-03-25 17:53:56 -0700783 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
784 return "File not found.";
785
786 string result;
787 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
788 return result;
789
790 return "data";
791}
792
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700793int FuzzInt(int value, unsigned int range) {
794 int min = value - range / 2;
795 int max = value + range - range / 2;
796 return base::RandInt(min, max);
797}
798
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700799string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800800 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700801}
802
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800803string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400804 string str;
805
806 // Handle negative durations by prefixing with a minus.
807 if (delta.ToInternalValue() < 0) {
808 delta *= -1;
809 str = "-";
810 }
811
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700812 // Canonicalize into days, hours, minutes, seconds and microseconds.
813 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800814 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700815 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800816 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700817 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800818 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700819 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800820 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700821 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800822
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700823 if (days)
824 base::StringAppendF(&str, "%ud", days);
825 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800826 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700827 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800828 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700829 base::StringAppendF(&str, "%u", secs);
830 if (usecs) {
831 int width = 6;
832 while ((usecs / 10) * 10 == usecs) {
833 usecs /= 10;
834 width--;
835 }
836 base::StringAppendF(&str, ".%0*u", width, usecs);
837 }
838 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800839 return str;
840}
841
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700842string ToString(const Time utc_time) {
843 Time::Exploded exp_time;
844 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700845 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700846 exp_time.month,
847 exp_time.day_of_month,
848 exp_time.year,
849 exp_time.hour,
850 exp_time.minute,
851 exp_time.second);
852}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000853
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700854string ToString(bool b) {
855 return (b ? "true" : "false");
856}
857
Alex Deymo1c656c42013-06-28 11:02:14 -0700858string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700859 switch (source) {
860 case kDownloadSourceHttpsServer: return "HttpsServer";
861 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700862 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -0700863 case kNumDownloadSources: return "Unknown";
864 // Don't add a default case to let the compiler warn about newly added
865 // download sources which should be added here.
866 }
867
868 return "Unknown";
869}
870
Alex Deymo1c656c42013-06-28 11:02:14 -0700871string ToString(PayloadType payload_type) {
872 switch (payload_type) {
873 case kPayloadTypeDelta: return "Delta";
874 case kPayloadTypeFull: return "Full";
875 case kPayloadTypeForcedFull: return "ForcedFull";
876 case kNumPayloadTypes: return "Unknown";
877 // Don't add a default case to let the compiler warn about newly added
878 // payload types which should be added here.
879 }
880
881 return "Unknown";
882}
883
David Zeuthena99981f2013-04-29 13:42:47 -0700884ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700885 // Ignore the higher order bits in the code by applying the mask as
886 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700887 // with values less than ErrorCode::kUmaReportedMax.
888 ErrorCode base_code = static_cast<ErrorCode>(
889 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -0700890
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800891 // Make additional adjustments required for UMA and error classification.
892 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
893 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700894 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700895 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800896 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800897 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700898 << " to ErrorCode::kOmahaErrorInHTTPResponse";
899 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700900 }
901
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800902 return base_code;
903}
904
David Zeuthen27a48bc2013-08-06 12:06:29 -0700905Time TimeFromStructTimespec(struct timespec *ts) {
Ben Chan9abb7632014-08-07 00:10:53 -0700906 int64_t us = static_cast<int64_t>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
907 static_cast<int64_t>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700908 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
909}
910
Alex Deymof329b932014-10-30 01:37:48 -0700911string StringVectorToString(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700912 string str = "[";
Alex Deymof329b932014-10-30 01:37:48 -0700913 for (vector<string>::const_iterator i = vec_str.begin();
914 i != vec_str.end(); ++i) {
915 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -0700916 str += ", ";
917 str += '"';
918 str += *i;
919 str += '"';
920 }
921 str += "]";
922 return str;
923}
924
David Zeuthen8f191b22013-08-06 12:27:50 -0700925string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700926 string encoded_hash = brillo::data_encoding::Base64Encode(payload_hash);
Alex Deymoc00c98a2015-03-17 17:38:00 -0700927 return base::StringPrintf("cros_update_size_%" PRIuS "_hash_%s",
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800928 payload_size,
929 encoded_hash.c_str());
David Zeuthen8f191b22013-08-06 12:27:50 -0700930}
931
Alex Deymof329b932014-10-30 01:37:48 -0700932bool DecodeAndStoreBase64String(const string& base64_encoded,
David Zeuthene7f89172013-10-31 10:21:04 -0700933 base::FilePath *out_path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700934 brillo::Blob contents;
David Zeuthene7f89172013-10-31 10:21:04 -0700935
936 out_path->clear();
937
938 if (base64_encoded.size() == 0) {
939 LOG(ERROR) << "Can't decode empty string.";
940 return false;
941 }
942
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700943 if (!brillo::data_encoding::Base64Decode(base64_encoded, &contents) ||
David Zeuthene7f89172013-10-31 10:21:04 -0700944 contents.size() == 0) {
945 LOG(ERROR) << "Error decoding base64.";
946 return false;
947 }
948
Alex Vakulenko75039d72014-03-25 12:36:28 -0700949 FILE *file = base::CreateAndOpenTemporaryFile(out_path);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700950 if (file == nullptr) {
David Zeuthene7f89172013-10-31 10:21:04 -0700951 LOG(ERROR) << "Error creating temporary file.";
952 return false;
953 }
954
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800955 if (fwrite(contents.data(), 1, contents.size(), file) != contents.size()) {
David Zeuthene7f89172013-10-31 10:21:04 -0700956 PLOG(ERROR) << "Error writing to temporary file.";
957 if (fclose(file) != 0)
958 PLOG(ERROR) << "Error closing temporary file.";
959 if (unlink(out_path->value().c_str()) != 0)
960 PLOG(ERROR) << "Error unlinking temporary file.";
961 out_path->clear();
962 return false;
963 }
964
965 if (fclose(file) != 0) {
966 PLOG(ERROR) << "Error closing temporary file.";
967 out_path->clear();
968 return false;
969 }
970
971 return true;
972}
973
Alex Deymof329b932014-10-30 01:37:48 -0700974bool ConvertToOmahaInstallDate(Time time, int *out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -0800975 time_t unix_time = time.ToTimeT();
976 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
977 const time_t kOmahaEpoch = 1167638400;
978 const int64_t kNumSecondsPerWeek = 7*24*3600;
979 const int64_t kNumDaysPerWeek = 7;
980
981 time_t omaha_time = unix_time - kOmahaEpoch;
982
983 if (omaha_time < 0)
984 return false;
985
986 // Note, as per the comment in utils.h we are deliberately not
987 // handling DST correctly.
988
989 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
990 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
991
992 return true;
993}
994
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700995bool GetMinorVersion(const brillo::KeyValueStore& store,
Alex Deymob42b98d2015-07-06 17:42:38 -0700996 uint32_t* minor_version) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700997 string result;
Alex Deymob42b98d2015-07-06 17:42:38 -0700998 if (store.GetString("PAYLOAD_MINOR_VERSION", &result)) {
Allie Wood425aa972015-02-17 14:47:17 -0800999 if (!base::StringToUint(result, minor_version)) {
1000 LOG(ERROR) << "StringToUint failed when parsing delta minor version.";
1001 return false;
1002 }
Allie Wood78750a42015-02-11 15:42:11 -08001003 return true;
1004 }
1005 return false;
1006}
1007
Sen Jiange0d04282016-03-01 14:22:52 -08001008bool IsZlibCompatible(const string& fingerprint) {
1009 if (fingerprint.size() != sizeof(kCompatibleZlibFingerprint[0]) - 1) {
1010 LOG(ERROR) << "Invalid fingerprint: " << fingerprint;
1011 return false;
1012 }
1013 for (auto& f : kCompatibleZlibFingerprint) {
1014 if (base::CompareCaseInsensitiveASCII(fingerprint, f) == 0) {
1015 return true;
1016 }
1017 }
1018 return false;
1019}
1020
Alex Deymo60ca1a72015-06-18 18:19:15 -07001021bool ReadExtents(const string& path, const vector<Extent>& extents,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001022 brillo::Blob* out_data, ssize_t out_data_size,
Allie Wood56873452015-03-27 17:48:40 -07001023 size_t block_size) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001024 brillo::Blob data(out_data_size);
Allie Wood56873452015-03-27 17:48:40 -07001025 ssize_t bytes_read = 0;
1026 int fd = open(path.c_str(), O_RDONLY);
1027 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
1028 ScopedFdCloser fd_closer(&fd);
1029
Gilad Arnold41e34742015-05-11 11:31:50 -07001030 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -07001031 ssize_t bytes_read_this_iteration = 0;
1032 ssize_t bytes = extent.num_blocks() * block_size;
1033 TEST_AND_RETURN_FALSE(bytes_read + bytes <= out_data_size);
1034 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
1035 &data[bytes_read],
1036 bytes,
1037 extent.start_block() * block_size,
1038 &bytes_read_this_iteration));
1039 TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes);
1040 bytes_read += bytes_read_this_iteration;
1041 }
1042 TEST_AND_RETURN_FALSE(out_data_size == bytes_read);
1043 *out_data = data;
1044 return true;
1045}
1046
Alex Deymodd132f32015-09-14 19:12:07 -07001047bool GetBootId(string* boot_id) {
1048 TEST_AND_RETURN_FALSE(
1049 base::ReadFileToString(base::FilePath(kBootIdPath), boot_id));
1050 base::TrimWhitespaceASCII(*boot_id, base::TRIM_TRAILING, boot_id);
1051 return true;
1052}
1053
adlr@google.com3defe6a2009-12-04 20:57:17 +00001054} // namespace utils
1055
1056} // namespace chromeos_update_engine