blob: 3e3d8302611bd6cbf4574bf6d97a60b107a65924 [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>
Yifan Hongc80de2d2020-02-25 17:13:53 -080033#include <time.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000034#include <unistd.h>
Darin Petkovf74eb652010-08-04 12:08:38 -070035
adlr@google.com3defe6a2009-12-04 20:57:17 +000036#include <algorithm>
Alex Vakulenkod2779df2014-06-16 13:19:00 -070037#include <utility>
Chris Sosac1972482013-04-30 22:31:10 -070038#include <vector>
Darin Petkovf74eb652010-08-04 12:08:38 -070039
Alex Vakulenko4906c1c2014-08-21 13:17:44 -070040#include <base/callback.h>
Ben Chan736fcb52014-05-21 18:28:22 -070041#include <base/files/file_path.h>
Alex Deymo192393b2014-11-10 15:58:38 -080042#include <base/files/file_util.h>
Ben Chan736fcb52014-05-21 18:28:22 -070043#include <base/files/scoped_file.h>
Alex Deymoc00c98a2015-03-17 17:38:00 -070044#include <base/format_macros.h>
Alex Deymo60ca1a72015-06-18 18:19:15 -070045#include <base/location.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040046#include <base/logging.h>
Chris Sosafc661a12013-02-26 14:43:21 -080047#include <base/posix/eintr_wrapper.h>
Will Drewry8f71da82010-08-30 14:07:11 -050048#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070049#include <base/strings/string_number_conversions.h>
50#include <base/strings/string_split.h>
51#include <base/strings/string_util.h>
52#include <base/strings/stringprintf.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070053#include <brillo/data_encoding.h>
Will Drewry8f71da82010-08-30 14:07:11 -050054
Alex Deymo39910dc2015-11-09 17:04:30 -080055#include "update_engine/common/clock_interface.h"
56#include "update_engine/common/constants.h"
Sen Jiang9c123462015-11-19 13:16:23 -080057#include "update_engine/common/platform_constants.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080058#include "update_engine/common/prefs_interface.h"
59#include "update_engine/common/subprocess.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080060#include "update_engine/payload_consumer/file_descriptor.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;
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -070065using std::numeric_limits;
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 Deymo5aa1c542015-09-18 01:02:33 -070087// If |path| is absolute, or explicit relative to the current working directory,
88// leaves it as is. Otherwise, uses the system's temp directory, as defined by
89// base::GetTempDir() and prepends it to |path|. On success stores the full
90// temporary path in |template_path| and returns true.
91bool GetTempName(const string& path, base::FilePath* template_path) {
Alex Vakulenko0103c362016-01-20 07:56:15 -080092 if (path[0] == '/' ||
93 base::StartsWith(path, "./", base::CompareCase::SENSITIVE) ||
94 base::StartsWith(path, "../", base::CompareCase::SENSITIVE)) {
Alex Deymo5aa1c542015-09-18 01:02:33 -070095 *template_path = base::FilePath(path);
96 return true;
97 }
98
99 base::FilePath temp_dir;
Sen Jiang9c123462015-11-19 13:16:23 -0800100#ifdef __ANDROID__
Sen Jiangc2b37662019-01-09 16:51:18 -0800101 temp_dir = base::FilePath(constants::kNonVolatileDirectory).Append("tmp");
Alex Deymo32951022016-08-10 17:02:49 -0700102#else
Sen Jiangc2b37662019-01-09 16:51:18 -0800103 TEST_AND_RETURN_FALSE(base::GetTempDir(&temp_dir));
Alex Deymo32951022016-08-10 17:02:49 -0700104#endif // __ANDROID__
Sen Jiang9c123462015-11-19 13:16:23 -0800105 if (!base::PathExists(temp_dir))
106 TEST_AND_RETURN_FALSE(base::CreateDirectory(temp_dir));
Alex Deymo5aa1c542015-09-18 01:02:33 -0700107 *template_path = temp_dir.Append(path);
108 return true;
109}
110
Ben Chan77a1eba2012-10-07 22:54:55 -0700111} // namespace
112
adlr@google.com3defe6a2009-12-04 20:57:17 +0000113namespace utils {
114
J. Richard Barnette63137e52013-10-28 10:57:29 -0700115string ParseECVersion(string input_line) {
Ben Chan736fcb52014-05-21 18:28:22 -0700116 base::TrimWhitespaceASCII(input_line, base::TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -0700117
Alex Vakulenko75039d72014-03-25 12:36:28 -0700118 // At this point we want to convert the format key=value pair from mosys to
Chris Sosac1972482013-04-30 22:31:10 -0700119 // a vector of key value pairs.
Ben Chanf9cb98c2014-09-21 18:31:30 -0700120 vector<pair<string, string>> kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -0700121 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Alex Deymo020600d2014-11-05 21:05:55 -0800122 for (const pair<string, string>& kv_pair : kv_pairs) {
Chris Sosac1972482013-04-30 22:31:10 -0700123 // Finally match against the fw_verion which may have quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800124 if (kv_pair.first == "fw_version") {
Chris Sosac1972482013-04-30 22:31:10 -0700125 string output;
126 // Trim any quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800127 base::TrimString(kv_pair.second, "\"", &output);
Chris Sosac1972482013-04-30 22:31:10 -0700128 return output;
129 }
130 }
131 }
132 LOG(ERROR) << "Unable to parse fwid from ec info.";
133 return "";
134}
135
Alex Deymo335516c2016-11-28 13:37:06 -0800136bool WriteFile(const char* path, const void* data, size_t data_len) {
137 int fd = HANDLE_EINTR(open(path, O_WRONLY | O_CREAT | O_TRUNC, 0600));
138 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
139 ScopedFdCloser fd_closer(&fd);
140 return WriteAll(fd, data, data_len);
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800141}
142
Alex Deymo0d298542016-03-30 18:31:49 -0700143bool ReadAll(
144 int fd, void* buf, size_t count, size_t* out_bytes_read, bool* eof) {
145 char* c_buf = static_cast<char*>(buf);
146 size_t bytes_read = 0;
147 *eof = false;
148 while (bytes_read < count) {
149 ssize_t rc = HANDLE_EINTR(read(fd, c_buf + bytes_read, count - bytes_read));
150 if (rc < 0) {
151 // EAGAIN and EWOULDBLOCK are normal return values when there's no more
152 // input and we are in non-blocking mode.
153 if (errno != EWOULDBLOCK && errno != EAGAIN) {
154 PLOG(ERROR) << "Error reading fd " << fd;
155 *out_bytes_read = bytes_read;
156 return false;
157 }
158 break;
159 } else if (rc == 0) {
160 // A value of 0 means that we reached EOF and there is nothing else to
161 // read from this fd.
162 *eof = true;
163 break;
164 } else {
165 bytes_read += rc;
166 }
167 }
168 *out_bytes_read = bytes_read;
169 return true;
170}
171
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700172bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700173 const char* c_buf = static_cast<const char*>(buf);
174 ssize_t bytes_written = 0;
175 while (bytes_written < static_cast<ssize_t>(count)) {
176 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
177 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
178 bytes_written += rc;
179 }
180 return true;
181}
182
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700183bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
184 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700185 size_t bytes_written = 0;
186 int num_attempts = 0;
187 while (bytes_written < count) {
188 num_attempts++;
Amin Hassanib2689592019-01-13 17:04:28 -0800189 ssize_t rc = pwrite(fd,
190 c_buf + bytes_written,
191 count - bytes_written,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700192 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700193 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
194 if (rc < 0) {
195 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
Amin Hassanib2689592019-01-13 17:04:28 -0800196 << " bytes_written=" << bytes_written << " count=" << count
197 << " offset=" << offset;
Gilad Arnold780db212012-07-11 13:12:49 -0700198 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700199 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
200 bytes_written += rc;
201 }
202 return true;
203}
204
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700205bool WriteAll(const FileDescriptorPtr& fd, const void* buf, size_t count) {
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800206 const char* c_buf = static_cast<const char*>(buf);
207 ssize_t bytes_written = 0;
208 while (bytes_written < static_cast<ssize_t>(count)) {
209 ssize_t rc = fd->Write(c_buf + bytes_written, count - bytes_written);
210 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
211 bytes_written += rc;
212 }
213 return true;
214}
215
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700216bool PWriteAll(const FileDescriptorPtr& fd,
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800217 const void* buf,
218 size_t count,
219 off_t offset) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700220 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
221 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800222 return WriteAll(fd, buf, count);
223}
224
Amin Hassanib2689592019-01-13 17:04:28 -0800225bool PReadAll(
226 int fd, void* buf, size_t count, off_t offset, ssize_t* out_bytes_read) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700227 char* c_buf = static_cast<char*>(buf);
228 ssize_t bytes_read = 0;
229 while (bytes_read < static_cast<ssize_t>(count)) {
Amin Hassanib2689592019-01-13 17:04:28 -0800230 ssize_t rc =
231 pread(fd, c_buf + bytes_read, count - bytes_read, offset + bytes_read);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700232 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
233 if (rc == 0) {
234 break;
235 }
236 bytes_read += rc;
237 }
238 *out_bytes_read = bytes_read;
239 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700240}
241
Marton Hunyadya0302682018-05-16 18:52:13 +0200242bool PReadAll(const FileDescriptorPtr& fd,
243 void* buf,
244 size_t count,
245 off_t offset,
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800246 ssize_t* out_bytes_read) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700247 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
248 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800249 char* c_buf = static_cast<char*>(buf);
250 ssize_t bytes_read = 0;
251 while (bytes_read < static_cast<ssize_t>(count)) {
252 ssize_t rc = fd->Read(c_buf + bytes_read, count - bytes_read);
253 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
254 if (rc == 0) {
255 break;
256 }
257 bytes_read += rc;
258 }
259 *out_bytes_read = bytes_read;
260 return true;
261}
262
Gilad Arnold19a45f02012-07-19 12:36:10 -0700263// Append |nbytes| of content from |buf| to the vector pointed to by either
264// |vec_p| or |str_p|.
Amin Hassanib2689592019-01-13 17:04:28 -0800265static void AppendBytes(const uint8_t* buf,
266 size_t nbytes,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700267 brillo::Blob* vec_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700268 CHECK(buf);
269 CHECK(vec_p);
270 vec_p->insert(vec_p->end(), buf, buf + nbytes);
271}
Amin Hassanib2689592019-01-13 17:04:28 -0800272static void AppendBytes(const uint8_t* buf, size_t nbytes, string* str_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700273 CHECK(buf);
274 CHECK(str_p);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800275 str_p->append(buf, buf + nbytes);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700276}
277
278// Reads from an open file |fp|, appending the read content to the container
279// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200280// file's content, false otherwise. If |size| is not -1, reads up to |size|
281// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700282template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200283static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700284 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200285 CHECK(size == -1 || size >= 0);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800286 uint8_t buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200287 while (size == -1 || size > 0) {
288 off_t bytes_to_read = sizeof(buf);
289 if (size > 0 && bytes_to_read > size) {
290 bytes_to_read = size;
291 }
292 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
293 if (!nbytes) {
294 break;
295 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700296 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200297 if (size != -1) {
298 CHECK(size >= static_cast<off_t>(nbytes));
299 size -= nbytes;
300 }
301 }
302 if (ferror(fp)) {
303 return false;
304 }
305 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700306}
307
Darin Petkov8e447e02013-04-16 16:23:50 +0200308// Opens a file |path| for reading and appends its the contents to a container
309// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
310// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700311template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700312static bool ReadFileChunkAndAppend(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200313 off_t offset,
314 off_t size,
315 T* out_p) {
316 CHECK_GE(offset, 0);
317 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700318 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200319 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000320 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200321 if (offset) {
322 // Return success without appending any data if a chunk beyond the end of
323 // the file is requested.
324 if (offset >= FileSize(path)) {
325 return true;
326 }
327 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
328 }
329 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000330}
331
Alex Deymo10875d92014-11-10 21:52:57 -0800332// TODO(deymo): This is only used in unittest, but requires the private
333// Read<string>() defined here. Expose Read<string>() or move to base/ version.
334bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700335 FILE* fp = popen(cmd.c_str(), "r");
336 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000337 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200338 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700339 return (success && pclose(fp) >= 0);
340}
341
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700342bool ReadFile(const string& path, brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200343 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700344}
345
Darin Petkov8e447e02013-04-16 16:23:50 +0200346bool ReadFile(const string& path, string* out_p) {
347 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700348}
349
Amin Hassanib2689592019-01-13 17:04:28 -0800350bool ReadFileChunk(const string& path,
351 off_t offset,
352 off_t size,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700353 brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200354 return ReadFileChunkAndAppend(path, offset, size, out_p);
355}
356
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700357off_t BlockDevSize(int fd) {
358 uint64_t dev_size;
359 int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
360 if (rc == -1) {
361 dev_size = -1;
362 PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
363 }
364 return dev_size;
365}
366
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700367off_t FileSize(int fd) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700368 struct stat stbuf;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700369 int rc = fstat(fd, &stbuf);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700370 CHECK_EQ(rc, 0);
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700371 if (rc < 0) {
372 PLOG(ERROR) << "Error stat-ing " << fd;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700373 return rc;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700374 }
375 if (S_ISREG(stbuf.st_mode))
376 return stbuf.st_size;
377 if (S_ISBLK(stbuf.st_mode))
378 return BlockDevSize(fd);
379 LOG(ERROR) << "Couldn't determine the type of " << fd;
380 return -1;
381}
382
383off_t FileSize(const string& path) {
384 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
385 if (fd == -1) {
386 PLOG(ERROR) << "Error opening " << path;
387 return fd;
388 }
389 off_t size = FileSize(fd);
390 if (size == -1)
391 PLOG(ERROR) << "Error getting file size of " << path;
392 close(fd);
393 return size;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700394}
395
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800396void HexDumpArray(const uint8_t* const arr, const size_t length) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000397 LOG(INFO) << "Logging array of length: " << length;
398 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700399 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000400 const unsigned int bytes_remaining = length - i;
Amin Hassanib2689592019-01-13 17:04:28 -0800401 const unsigned int bytes_per_this_line =
402 min(bytes_per_line, bytes_remaining);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000403 char header[100];
404 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
405 TEST_AND_RETURN(r == 13);
406 string line = header;
407 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
408 char buf[20];
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800409 uint8_t c = arr[i + j];
adlr@google.com3defe6a2009-12-04 20:57:17 +0000410 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
411 TEST_AND_RETURN(r == 3);
412 line += buf;
413 }
414 LOG(INFO) << line;
415 }
416}
417
Alex Deymof329b932014-10-30 01:37:48 -0700418bool SplitPartitionName(const string& partition_name,
419 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800420 int* out_partition_num) {
Amin Hassanib2689592019-01-13 17:04:28 -0800421 if (!base::StartsWith(
422 partition_name, "/dev/", base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800423 LOG(ERROR) << "Invalid partition device name: " << partition_name;
424 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700425 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800426
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700427 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
428 if (last_nondigit_pos == string::npos ||
429 (last_nondigit_pos + 1) == partition_name.size()) {
430 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800431 return false;
432 }
433
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800434 if (out_disk_name) {
435 // Special case for MMC devices which have the following naming scheme:
436 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700437 size_t disk_name_len = last_nondigit_pos;
Amin Hassanib2689592019-01-13 17:04:28 -0800438 if (partition_name[last_nondigit_pos] != 'p' || last_nondigit_pos == 0 ||
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700439 !isdigit(partition_name[last_nondigit_pos - 1])) {
440 disk_name_len++;
441 }
442 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800443 }
444
445 if (out_partition_num) {
Brian Norris7b428f52019-06-26 10:03:35 -0700446 string partition_str = partition_name.substr(last_nondigit_pos + 1);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800447 *out_partition_num = atoi(partition_str.c_str());
448 }
449 return true;
450}
451
Alex Deymof329b932014-10-30 01:37:48 -0700452string MakePartitionName(const string& disk_name, int partition_num) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800453 if (partition_num < 1) {
454 LOG(ERROR) << "Invalid partition number: " << partition_num;
455 return string();
456 }
457
Alex Vakulenko0103c362016-01-20 07:56:15 -0800458 if (!base::StartsWith(disk_name, "/dev/", base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800459 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700460 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800461 }
462
Alex Deymof329b932014-10-30 01:37:48 -0700463 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700464 if (isdigit(partition_name.back())) {
465 // Special case for devices with names ending with a digit.
466 // Add "p" to separate the disk name from partition number,
467 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800468 partition_name += 'p';
469 }
470
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700471 partition_name += std::to_string(partition_num);
472
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800473 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700474}
475
Alex Deymof329b932014-10-30 01:37:48 -0700476string ErrnoNumberAsString(int err) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000477 char buf[100];
478 buf[0] = '\0';
479 return strerror_r(err, buf, sizeof(buf));
480}
481
adlr@google.com3defe6a2009-12-04 20:57:17 +0000482bool FileExists(const char* path) {
483 struct stat stbuf;
484 return 0 == lstat(path, &stbuf);
485}
486
Darin Petkov30291ed2010-11-12 10:23:06 -0800487bool IsSymlink(const char* path) {
488 struct stat stbuf;
489 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
490}
491
Alex Deymof329b932014-10-30 01:37:48 -0700492bool MakeTempFile(const string& base_filename_template,
493 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700494 int* fd) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700495 base::FilePath filename_template;
496 TEST_AND_RETURN_FALSE(
497 GetTempName(base_filename_template, &filename_template));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700498 DCHECK(filename || fd);
Alex Deymo5aa1c542015-09-18 01:02:33 -0700499 vector<char> buf(filename_template.value().size() + 1);
Amin Hassanib2689592019-01-13 17:04:28 -0800500 memcpy(buf.data(),
501 filename_template.value().data(),
Alex Deymo5aa1c542015-09-18 01:02:33 -0700502 filename_template.value().size());
503 buf[filename_template.value().size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700504
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800505 int mkstemp_fd = mkstemp(buf.data());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700506 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
507 if (filename) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800508 *filename = buf.data();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700509 }
510 if (fd) {
511 *fd = mkstemp_fd;
512 } else {
513 close(mkstemp_fd);
514 }
515 return true;
516}
517
Alex Deymo5fb356c2016-03-25 18:48:22 -0700518bool SetBlockDeviceReadOnly(const string& device, bool read_only) {
519 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY | O_CLOEXEC));
520 if (fd < 0) {
521 PLOG(ERROR) << "Opening block device " << device;
522 return false;
523 }
524 ScopedFdCloser fd_closer(&fd);
525 // We take no action if not needed.
526 int read_only_flag;
527 int expected_flag = read_only ? 1 : 0;
528 int rc = ioctl(fd, BLKROGET, &read_only_flag);
529 // In case of failure reading the setting we will try to set it anyway.
530 if (rc == 0 && read_only_flag == expected_flag)
531 return true;
532
533 rc = ioctl(fd, BLKROSET, &expected_flag);
534 if (rc != 0) {
Amin Hassanib2689592019-01-13 17:04:28 -0800535 PLOG(ERROR) << "Marking block device " << device
536 << " as read_only=" << expected_flag;
Alex Deymo5fb356c2016-03-25 18:48:22 -0700537 return false;
538 }
539 return true;
540}
541
adlr@google.com3defe6a2009-12-04 20:57:17 +0000542bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700543 const string& mountpoint,
Alex Deymo390efed2016-02-18 11:00:40 -0800544 unsigned long mountflags, // NOLINT(runtime/int)
Alex Deymo14dbd332016-03-01 18:55:54 -0800545 const string& type,
546 const string& fs_mount_options) {
Alex Deymo390efed2016-02-18 11:00:40 -0800547 vector<const char*> fstypes;
548 if (type.empty()) {
549 fstypes = {"ext2", "ext3", "ext4", "squashfs"};
550 } else {
551 fstypes = {type.c_str()};
552 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800553 for (const char* fstype : fstypes) {
Amin Hassanib2689592019-01-13 17:04:28 -0800554 int rc = mount(device.c_str(),
555 mountpoint.c_str(),
556 fstype,
557 mountflags,
Alex Deymo14dbd332016-03-01 18:55:54 -0800558 fs_mount_options.c_str());
Alex Deymo4c82df32014-11-10 22:25:57 -0800559 if (rc == 0)
560 return true;
561
Amin Hassanib2689592019-01-13 17:04:28 -0800562 PLOG(WARNING) << "Unable to mount destination device " << device << " on "
563 << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000564 }
Alex Deymo390efed2016-02-18 11:00:40 -0800565 if (!type.empty()) {
566 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
567 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800568 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000569}
570
571bool UnmountFilesystem(const string& mountpoint) {
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700572 int num_retries = 1;
573 for (;; ++num_retries) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700574 if (umount(mountpoint.c_str()) == 0)
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700575 return true;
576 if (errno != EBUSY || num_retries >= kUnmountMaxNumOfRetries)
Ben Chan77a1eba2012-10-07 22:54:55 -0700577 break;
Alex Deymo8d2bbe32015-06-23 16:28:59 -0700578 usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700579 }
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700580 if (errno == EINVAL) {
581 LOG(INFO) << "Not a mountpoint: " << mountpoint;
582 return false;
583 }
584 PLOG(WARNING) << "Error unmounting " << mountpoint << " after " << num_retries
585 << " attempts. Lazy unmounting instead, error was";
586 if (umount2(mountpoint.c_str(), MNT_DETACH) != 0) {
587 PLOG(ERROR) << "Lazy unmount failed";
588 return false;
589 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000590 return true;
591}
592
Alex Deymof4116502017-03-22 17:00:31 -0700593bool IsMountpoint(const std::string& mountpoint) {
594 struct stat stdir, stparent;
595
596 // Check whether the passed mountpoint is a directory and the /.. is in the
597 // same device or not. If mountpoint/.. is in a different device it means that
598 // there is a filesystem mounted there. If it is not, but they both point to
599 // the same inode it basically is the special case of /.. pointing to /. This
600 // test doesn't play well with bind mount but that's out of the scope of what
601 // we want to detect here.
602 if (lstat(mountpoint.c_str(), &stdir) != 0) {
603 PLOG(ERROR) << "Error stat'ing " << mountpoint;
604 return false;
605 }
606 if (!S_ISDIR(stdir.st_mode))
607 return false;
608
609 base::FilePath parent(mountpoint);
610 parent = parent.Append("..");
611 if (lstat(parent.value().c_str(), &stparent) != 0) {
612 PLOG(ERROR) << "Error stat'ing " << parent.value();
613 return false;
614 }
615 return S_ISDIR(stparent.st_mode) &&
616 (stparent.st_dev != stdir.st_dev || stparent.st_ino == stdir.st_ino);
617}
618
Alex Deymo032e7722014-03-25 17:53:56 -0700619// Tries to parse the header of an ELF file to obtain a human-readable
620// description of it on the |output| string.
Amin Hassanib2689592019-01-13 17:04:28 -0800621static bool GetFileFormatELF(const uint8_t* buffer,
622 size_t size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800623 string* output) {
Alex Deymo032e7722014-03-25 17:53:56 -0700624 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700625 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700626 return false;
627 *output = "ELF";
628
629 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700630 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700631 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700632 switch (buffer[EI_CLASS]) {
633 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700634 *output += " 32-bit";
635 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700636 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700637 *output += " 64-bit";
638 break;
639 default:
640 *output += " ?-bit";
641 }
642
643 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700644 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700645 return true;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800646 uint8_t ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700647 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700648 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700649 *output += " little-endian";
650 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700651 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700652 *output += " big-endian";
653 break;
654 default:
655 *output += " ?-endian";
656 // Don't parse anything after the 0x10 offset if endianness is unknown.
657 return true;
658 }
659
Alex Deymoc1711e22014-08-08 13:16:23 -0700660 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
661 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
662 // and size is the same for both 32 and 64 bits.
663 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700664 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700665 uint16_t e_machine;
Sen Jiang771f6482018-04-04 17:59:10 -0700666 // Fix endianness regardless of the host endianness.
Alex Deymoc1711e22014-08-08 13:16:23 -0700667 if (ei_data == ELFDATA2LSB)
668 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700669 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700670 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700671
672 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700673 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700674 *output += " x86";
675 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700676 case EM_MIPS:
677 *output += " mips";
678 break;
679 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700680 *output += " arm";
681 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700682 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700683 *output += " x86-64";
684 break;
685 default:
686 *output += " unknown-arch";
687 }
688 return true;
689}
690
691string GetFileFormat(const string& path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700692 brillo::Blob buffer;
Alex Deymo032e7722014-03-25 17:53:56 -0700693 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
694 return "File not found.";
695
696 string result;
697 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
698 return result;
699
700 return "data";
701}
702
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700703int FuzzInt(int value, unsigned int range) {
704 int min = value - range / 2;
705 int max = value + range - range / 2;
706 return base::RandInt(min, max);
707}
708
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700709string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800710 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700711}
712
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800713string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400714 string str;
715
716 // Handle negative durations by prefixing with a minus.
717 if (delta.ToInternalValue() < 0) {
718 delta *= -1;
719 str = "-";
720 }
721
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700722 // Canonicalize into days, hours, minutes, seconds and microseconds.
723 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800724 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700725 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800726 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700727 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800728 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700729 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800730 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700731 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800732
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700733 if (days)
734 base::StringAppendF(&str, "%ud", days);
735 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800736 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700737 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800738 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700739 base::StringAppendF(&str, "%u", secs);
740 if (usecs) {
741 int width = 6;
742 while ((usecs / 10) * 10 == usecs) {
743 usecs /= 10;
744 width--;
745 }
746 base::StringAppendF(&str, ".%0*u", width, usecs);
747 }
748 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800749 return str;
750}
751
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700752string ToString(const Time utc_time) {
753 Time::Exploded exp_time;
754 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700755 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Amin Hassanib2689592019-01-13 17:04:28 -0800756 exp_time.month,
757 exp_time.day_of_month,
758 exp_time.year,
759 exp_time.hour,
760 exp_time.minute,
761 exp_time.second);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700762}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000763
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700764string ToString(bool b) {
765 return (b ? "true" : "false");
766}
767
Alex Deymo1c656c42013-06-28 11:02:14 -0700768string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700769 switch (source) {
Amin Hassanib2689592019-01-13 17:04:28 -0800770 case kDownloadSourceHttpsServer:
771 return "HttpsServer";
772 case kDownloadSourceHttpServer:
773 return "HttpServer";
774 case kDownloadSourceHttpPeer:
775 return "HttpPeer";
776 case kNumDownloadSources:
777 return "Unknown";
778 // Don't add a default case to let the compiler warn about newly added
779 // download sources which should be added here.
Jay Srinivasan19409b72013-04-12 19:23:36 -0700780 }
781
782 return "Unknown";
783}
784
Alex Deymo1c656c42013-06-28 11:02:14 -0700785string ToString(PayloadType payload_type) {
786 switch (payload_type) {
Amin Hassanib2689592019-01-13 17:04:28 -0800787 case kPayloadTypeDelta:
788 return "Delta";
789 case kPayloadTypeFull:
790 return "Full";
791 case kPayloadTypeForcedFull:
792 return "ForcedFull";
793 case kNumPayloadTypes:
794 return "Unknown";
795 // Don't add a default case to let the compiler warn about newly added
796 // payload types which should be added here.
Alex Deymo1c656c42013-06-28 11:02:14 -0700797 }
798
799 return "Unknown";
800}
801
David Zeuthena99981f2013-04-29 13:42:47 -0700802ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700803 // Ignore the higher order bits in the code by applying the mask as
804 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700805 // with values less than ErrorCode::kUmaReportedMax.
806 ErrorCode base_code = static_cast<ErrorCode>(
807 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -0700808
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800809 // Make additional adjustments required for UMA and error classification.
810 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
811 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700812 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700813 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800814 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800815 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700816 << " to ErrorCode::kOmahaErrorInHTTPResponse";
817 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700818 }
819
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800820 return base_code;
821}
822
Alex Deymof329b932014-10-30 01:37:48 -0700823string StringVectorToString(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700824 string str = "[";
Amin Hassanib2689592019-01-13 17:04:28 -0800825 for (vector<string>::const_iterator i = vec_str.begin(); i != vec_str.end();
826 ++i) {
Alex Deymof329b932014-10-30 01:37:48 -0700827 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -0700828 str += ", ";
829 str += '"';
830 str += *i;
831 str += '"';
832 }
833 str += "]";
834 return str;
835}
836
Sen Jiang2703ef42017-03-16 13:36:21 -0700837// The P2P file id should be the same for devices running new version and old
838// version so that they can share it with each other. The hash in the response
839// was base64 encoded, but now that we switched to use "hash_sha256" field which
840// is hex encoded, we have to convert them back to base64 for P2P. However, the
841// base64 encoded hash was base64 encoded here again historically for some
842// reason, so we keep the same behavior here.
843string CalculateP2PFileId(const brillo::Blob& payload_hash,
844 size_t payload_size) {
845 string encoded_hash = brillo::data_encoding::Base64Encode(
846 brillo::data_encoding::Base64Encode(payload_hash));
Alex Deymoc00c98a2015-03-17 17:38:00 -0700847 return base::StringPrintf("cros_update_size_%" PRIuS "_hash_%s",
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800848 payload_size,
849 encoded_hash.c_str());
David Zeuthen8f191b22013-08-06 12:27:50 -0700850}
851
Alex Deymof329b932014-10-30 01:37:48 -0700852bool ConvertToOmahaInstallDate(Time time, int *out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -0800853 time_t unix_time = time.ToTimeT();
854 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
855 const time_t kOmahaEpoch = 1167638400;
Amin Hassanib2689592019-01-13 17:04:28 -0800856 const int64_t kNumSecondsPerWeek = 7 * 24 * 3600;
David Zeuthen639aa362014-02-03 16:23:44 -0800857 const int64_t kNumDaysPerWeek = 7;
858
859 time_t omaha_time = unix_time - kOmahaEpoch;
860
861 if (omaha_time < 0)
862 return false;
863
864 // Note, as per the comment in utils.h we are deliberately not
865 // handling DST correctly.
866
867 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
868 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
869
870 return true;
871}
872
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700873bool GetMinorVersion(const brillo::KeyValueStore& store,
Alex Deymob42b98d2015-07-06 17:42:38 -0700874 uint32_t* minor_version) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700875 string result;
Alex Deymob42b98d2015-07-06 17:42:38 -0700876 if (store.GetString("PAYLOAD_MINOR_VERSION", &result)) {
Allie Wood425aa972015-02-17 14:47:17 -0800877 if (!base::StringToUint(result, minor_version)) {
878 LOG(ERROR) << "StringToUint failed when parsing delta minor version.";
879 return false;
880 }
Allie Wood78750a42015-02-11 15:42:11 -0800881 return true;
882 }
883 return false;
884}
885
Amin Hassanib2689592019-01-13 17:04:28 -0800886bool ReadExtents(const string& path,
887 const vector<Extent>& extents,
888 brillo::Blob* out_data,
889 ssize_t out_data_size,
Allie Wood56873452015-03-27 17:48:40 -0700890 size_t block_size) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700891 brillo::Blob data(out_data_size);
Allie Wood56873452015-03-27 17:48:40 -0700892 ssize_t bytes_read = 0;
893 int fd = open(path.c_str(), O_RDONLY);
894 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
895 ScopedFdCloser fd_closer(&fd);
896
Gilad Arnold41e34742015-05-11 11:31:50 -0700897 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -0700898 ssize_t bytes_read_this_iteration = 0;
899 ssize_t bytes = extent.num_blocks() * block_size;
900 TEST_AND_RETURN_FALSE(bytes_read + bytes <= out_data_size);
901 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
902 &data[bytes_read],
903 bytes,
904 extent.start_block() * block_size,
905 &bytes_read_this_iteration));
906 TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes);
907 bytes_read += bytes_read_this_iteration;
908 }
909 TEST_AND_RETURN_FALSE(out_data_size == bytes_read);
910 *out_data = data;
911 return true;
912}
913
Alex Deymodd132f32015-09-14 19:12:07 -0700914bool GetBootId(string* boot_id) {
915 TEST_AND_RETURN_FALSE(
916 base::ReadFileToString(base::FilePath(kBootIdPath), boot_id));
917 base::TrimWhitespaceASCII(*boot_id, base::TRIM_TRAILING, boot_id);
918 return true;
919}
920
Marton Hunyadya0302682018-05-16 18:52:13 +0200921int VersionPrefix(const std::string& version) {
922 if (version.empty()) {
923 return 0;
924 }
925 vector<string> tokens = base::SplitString(
926 version, ".", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
927 int value;
928 if (tokens.empty() || !base::StringToInt(tokens[0], &value))
929 return -1; // Target version is invalid.
930 return value;
931}
932
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700933void ParseRollbackKeyVersion(const string& raw_version,
934 uint16_t* high_version,
935 uint16_t* low_version) {
936 DCHECK(high_version);
937 DCHECK(low_version);
938 *high_version = numeric_limits<uint16_t>::max();
939 *low_version = numeric_limits<uint16_t>::max();
940
941 vector<string> parts = base::SplitString(
942 raw_version, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
943 if (parts.size() != 2) {
944 // The version string must have exactly one period.
945 return;
946 }
947
948 int high;
949 int low;
950 if (!(base::StringToInt(parts[0], &high) &&
951 base::StringToInt(parts[1], &low))) {
952 // Both parts of the version could not be parsed correctly.
953 return;
954 }
955
956 if (high >= 0 && high < numeric_limits<uint16_t>::max() && low >= 0 &&
957 low < numeric_limits<uint16_t>::max()) {
958 *high_version = static_cast<uint16_t>(high);
959 *low_version = static_cast<uint16_t>(low);
960 }
961}
962
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900963string GetFilePath(int fd) {
964 base::FilePath proc("/proc/self/fd/" + std::to_string(fd));
965 base::FilePath file_name;
966
967 if (!base::ReadSymbolicLink(proc, &file_name)) {
968 return "not found";
969 }
970 return file_name.value();
971}
972
Yifan Hongc80de2d2020-02-25 17:13:53 -0800973string GetTimeAsString(time_t utime) {
974 struct tm tm;
975 CHECK_EQ(localtime_r(&utime, &tm), &tm);
976 char str[16];
977 CHECK_EQ(strftime(str, sizeof(str), "%Y%m%d-%H%M%S", &tm), 15u);
978 return str;
979}
980
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700981string GetExclusionName(const string& str_to_convert) {
982 return base::NumberToString(base::StringPieceHash()(str_to_convert));
983}
984
adlr@google.com3defe6a2009-12-04 20:57:17 +0000985} // namespace utils
986
987} // namespace chromeos_update_engine