• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
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 //
16 
17 #include "update_engine/common/utils.h"
18 
19 #include <stdint.h>
20 
21 #include <dirent.h>
22 #include <elf.h>
23 #include <endian.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/mount.h>
30 #include <sys/resource.h>
31 #include <sys/sendfile.h>
32 #include <sys/stat.h>
33 #include <sys/types.h>
34 #include <time.h>
35 #include <unistd.h>
36 
37 #include <algorithm>
38 #include <filesystem>
39 #include <utility>
40 #include <vector>
41 
42 #include <android-base/strings.h>
43 #include <base/callback.h>
44 #include <base/files/file_path.h>
45 #include <base/files/file_util.h>
46 #include <base/files/scoped_file.h>
47 #include <base/format_macros.h>
48 #include <base/location.h>
49 #include <base/logging.h>
50 #include <base/posix/eintr_wrapper.h>
51 #include <base/rand_util.h>
52 #include <base/strings/string_number_conversions.h>
53 #include <base/strings/string_split.h>
54 #include <base/strings/string_util.h>
55 #include <base/strings/stringprintf.h>
56 #include <brillo/data_encoding.h>
57 
58 #include "update_engine/common/constants.h"
59 #include "update_engine/common/subprocess.h"
60 #ifdef __ANDROID__
61 #include "update_engine/common/platform_constants.h"
62 #endif
63 #include "update_engine/payload_consumer/file_descriptor.h"
64 
65 using base::Time;
66 using base::TimeDelta;
67 using std::min;
68 using std::numeric_limits;
69 using std::string;
70 using std::vector;
71 
72 namespace chromeos_update_engine {
73 
74 namespace {
75 
76 // The following constants control how UnmountFilesystem should retry if
77 // umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
78 // one second.
79 const int kUnmountMaxNumOfRetries = 5;
80 const int kUnmountRetryIntervalInMicroseconds = 200 * 1000;  // 200 ms
81 
82 // Number of bytes to read from a file to attempt to detect its contents. Used
83 // in GetFileFormat.
84 const int kGetFileFormatMaxHeaderSize = 32;
85 
86 // The path to the kernel's boot_id.
87 const char kBootIdPath[] = "/proc/sys/kernel/random/boot_id";
88 
89 }  // namespace
90 // If |path| is absolute, or explicit relative to the current working directory,
91 // leaves it as is. Otherwise, uses the system's temp directory, as defined by
92 // base::GetTempDir() and prepends it to |path|. On success stores the full
93 // temporary path in |template_path| and returns true.
GetTempName(const string & path,base::FilePath * template_path)94 bool GetTempName(const string& path, base::FilePath* template_path) {
95   if (path[0] == '/' ||
96       base::StartsWith(path, "./", base::CompareCase::SENSITIVE) ||
97       base::StartsWith(path, "../", base::CompareCase::SENSITIVE)) {
98     *template_path = base::FilePath(path);
99     return true;
100   }
101 
102   base::FilePath temp_dir;
103 #ifdef __ANDROID__
104   temp_dir = base::FilePath(constants::kNonVolatileDirectory).Append("tmp");
105 #else
106   TEST_AND_RETURN_FALSE(base::GetTempDir(&temp_dir));
107 #endif  // __ANDROID__
108   if (!base::PathExists(temp_dir))
109     TEST_AND_RETURN_FALSE(base::CreateDirectory(temp_dir));
110   *template_path = temp_dir.Append(path);
111   return true;
112 }
113 
114 namespace utils {
115 
WriteFile(const char * path,const void * data,size_t data_len)116 bool WriteFile(const char* path, const void* data, size_t data_len) {
117   int fd = HANDLE_EINTR(open(path, O_WRONLY | O_CREAT | O_TRUNC, 0600));
118   TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
119   ScopedFdCloser fd_closer(&fd);
120   return WriteAll(fd, data, data_len);
121 }
122 
ReadAll(int fd,void * buf,size_t count,size_t * out_bytes_read,bool * eof)123 bool ReadAll(
124     int fd, void* buf, size_t count, size_t* out_bytes_read, bool* eof) {
125   char* c_buf = static_cast<char*>(buf);
126   size_t bytes_read = 0;
127   *eof = false;
128   while (bytes_read < count) {
129     ssize_t rc = HANDLE_EINTR(read(fd, c_buf + bytes_read, count - bytes_read));
130     if (rc < 0) {
131       // EAGAIN and EWOULDBLOCK are normal return values when there's no more
132       // input and we are in non-blocking mode.
133       if (errno != EWOULDBLOCK && errno != EAGAIN) {
134         PLOG(ERROR) << "Error reading fd " << fd;
135         *out_bytes_read = bytes_read;
136         return false;
137       }
138       break;
139     } else if (rc == 0) {
140       // A value of 0 means that we reached EOF and there is nothing else to
141       // read from this fd.
142       *eof = true;
143       break;
144     } else {
145       bytes_read += rc;
146     }
147   }
148   *out_bytes_read = bytes_read;
149   return true;
150 }
151 
WriteAll(int fd,const void * buf,size_t count)152 bool WriteAll(int fd, const void* buf, size_t count) {
153   const char* c_buf = static_cast<const char*>(buf);
154   ssize_t bytes_written = 0;
155   while (bytes_written < static_cast<ssize_t>(count)) {
156     ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
157     TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
158     bytes_written += rc;
159   }
160   return true;
161 }
162 
PWriteAll(int fd,const void * buf,size_t count,off_t offset)163 bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
164   const char* c_buf = static_cast<const char*>(buf);
165   size_t bytes_written = 0;
166   int num_attempts = 0;
167   while (bytes_written < count) {
168     num_attempts++;
169     ssize_t rc = pwrite(fd,
170                         c_buf + bytes_written,
171                         count - bytes_written,
172                         offset + bytes_written);
173     // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
174     if (rc < 0) {
175       PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
176                   << " bytes_written=" << bytes_written << " count=" << count
177                   << " offset=" << offset;
178     }
179     TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
180     bytes_written += rc;
181   }
182   return true;
183 }
184 
WriteAll(FileDescriptor * fd,const void * buf,size_t count)185 bool WriteAll(FileDescriptor* fd, const void* buf, size_t count) {
186   const char* c_buf = static_cast<const char*>(buf);
187   ssize_t bytes_written = 0;
188   while (bytes_written < static_cast<ssize_t>(count)) {
189     ssize_t rc = fd->Write(c_buf + bytes_written, count - bytes_written);
190     TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
191     bytes_written += rc;
192   }
193   return true;
194 }
195 
WriteAll(const FileDescriptorPtr & fd,const void * buf,size_t count,off_t offset)196 bool WriteAll(const FileDescriptorPtr& fd,
197               const void* buf,
198               size_t count,
199               off_t offset) {
200   TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
201                               static_cast<off_t>(-1));
202   return WriteAll(fd, buf, count);
203 }
204 
PReadAll(int fd,void * buf,size_t count,off_t offset,ssize_t * out_bytes_read)205 bool PReadAll(
206     int fd, void* buf, size_t count, off_t offset, ssize_t* out_bytes_read) {
207   char* c_buf = static_cast<char*>(buf);
208   ssize_t bytes_read = 0;
209   while (bytes_read < static_cast<ssize_t>(count)) {
210     ssize_t rc =
211         pread(fd, c_buf + bytes_read, count - bytes_read, offset + bytes_read);
212     TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
213     if (rc == 0) {
214       break;
215     }
216     bytes_read += rc;
217   }
218   *out_bytes_read = bytes_read;
219   return true;
220 }
221 
ReadAll(FileDescriptor * fd,void * buf,size_t count,off_t offset,ssize_t * out_bytes_read)222 bool ReadAll(FileDescriptor* fd,
223              void* buf,
224              size_t count,
225              off_t offset,
226              ssize_t* out_bytes_read) {
227   TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
228                               static_cast<off_t>(-1));
229   char* c_buf = static_cast<char*>(buf);
230   ssize_t bytes_read = 0;
231   while (bytes_read < static_cast<ssize_t>(count)) {
232     ssize_t rc = fd->Read(c_buf + bytes_read, count - bytes_read);
233     TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
234     if (rc == 0) {
235       break;
236     }
237     bytes_read += rc;
238   }
239   *out_bytes_read = bytes_read;
240   return true;
241 }
242 
PReadAll(FileDescriptor * fd,void * buf,size_t count,off_t offset,ssize_t * out_bytes_read)243 bool PReadAll(FileDescriptor* fd,
244               void* buf,
245               size_t count,
246               off_t offset,
247               ssize_t* out_bytes_read) {
248   auto old_off = fd->Seek(0, SEEK_CUR);
249   TEST_AND_RETURN_FALSE_ERRNO(old_off >= 0);
250 
251   auto success = ReadAll(fd, buf, count, offset, out_bytes_read);
252   TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(old_off, SEEK_SET) == old_off);
253   return success;
254 }
255 
PWriteAll(const FileDescriptorPtr & fd,const void * buf,size_t count,off_t offset)256 bool PWriteAll(const FileDescriptorPtr& fd,
257                const void* buf,
258                size_t count,
259                off_t offset) {
260   auto old_off = fd->Seek(0, SEEK_CUR);
261   TEST_AND_RETURN_FALSE_ERRNO(old_off >= 0);
262 
263   auto success = WriteAll(fd, buf, count, offset);
264   TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(old_off, SEEK_SET) == old_off);
265   return success;
266 }
267 
268 // Append |nbytes| of content from |buf| to the vector pointed to by either
269 // |vec_p| or |str_p|.
AppendBytes(const uint8_t * buf,size_t nbytes,brillo::Blob * vec_p)270 static void AppendBytes(const uint8_t* buf,
271                         size_t nbytes,
272                         brillo::Blob* vec_p) {
273   CHECK(buf);
274   CHECK(vec_p);
275   vec_p->insert(vec_p->end(), buf, buf + nbytes);
276 }
AppendBytes(const uint8_t * buf,size_t nbytes,string * str_p)277 static void AppendBytes(const uint8_t* buf, size_t nbytes, string* str_p) {
278   CHECK(buf);
279   CHECK(str_p);
280   str_p->append(buf, buf + nbytes);
281 }
282 
283 // Reads from an open file |fp|, appending the read content to the container
284 // pointer to by |out_p|.  Returns true upon successful reading all of the
285 // file's content, false otherwise. If |size| is not -1, reads up to |size|
286 // bytes.
287 template <class T>
Read(FILE * fp,off_t size,T * out_p)288 static bool Read(FILE* fp, off_t size, T* out_p) {
289   CHECK(fp);
290   CHECK(size == -1 || size >= 0);
291   uint8_t buf[1024];
292   while (size == -1 || size > 0) {
293     off_t bytes_to_read = sizeof(buf);
294     if (size > 0 && bytes_to_read > size) {
295       bytes_to_read = size;
296     }
297     size_t nbytes = fread(buf, 1, bytes_to_read, fp);
298     if (!nbytes) {
299       break;
300     }
301     AppendBytes(buf, nbytes, out_p);
302     if (size != -1) {
303       CHECK(size >= static_cast<off_t>(nbytes));
304       size -= nbytes;
305     }
306   }
307   if (ferror(fp)) {
308     return false;
309   }
310   return size == 0 || feof(fp);
311 }
312 
313 // Opens a file |path| for reading and appends its the contents to a container
314 // |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
315 // of the file, returns success. If |size| is not -1, reads up to |size| bytes.
316 template <class T>
ReadFileChunkAndAppend(const string & path,off_t offset,off_t size,T * out_p)317 static bool ReadFileChunkAndAppend(const string& path,
318                                    off_t offset,
319                                    off_t size,
320                                    T* out_p) {
321   CHECK_GE(offset, 0);
322   CHECK(size == -1 || size >= 0);
323   base::ScopedFILE fp(fopen(path.c_str(), "r"));
324   if (!fp.get())
325     return false;
326   if (offset) {
327     // Return success without appending any data if a chunk beyond the end of
328     // the file is requested.
329     if (offset >= FileSize(path)) {
330       return true;
331     }
332     TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
333   }
334   return Read(fp.get(), size, out_p);
335 }
336 
337 // TODO(deymo): This is only used in unittest, but requires the private
338 // Read<string>() defined here. Expose Read<string>() or move to base/ version.
ReadPipe(const string & cmd,string * out_p)339 bool ReadPipe(const string& cmd, string* out_p) {
340   FILE* fp = popen(cmd.c_str(), "r");
341   if (!fp)
342     return false;
343   bool success = Read(fp, -1, out_p);
344   return (success && pclose(fp) >= 0);
345 }
346 
ReadFile(const string & path,brillo::Blob * out_p)347 bool ReadFile(const string& path, brillo::Blob* out_p) {
348   return ReadFileChunkAndAppend(path, 0, -1, out_p);
349 }
350 
ReadFile(const string & path,string * out_p)351 bool ReadFile(const string& path, string* out_p) {
352   return ReadFileChunkAndAppend(path, 0, -1, out_p);
353 }
354 
ReadFileChunk(const string & path,off_t offset,off_t size,brillo::Blob * out_p)355 bool ReadFileChunk(const string& path,
356                    off_t offset,
357                    off_t size,
358                    brillo::Blob* out_p) {
359   return ReadFileChunkAndAppend(path, offset, size, out_p);
360 }
361 
BlockDevSize(int fd)362 off_t BlockDevSize(int fd) {
363   uint64_t dev_size{};
364   int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
365   if (rc == -1) {
366     dev_size = -1;
367     PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
368   }
369   return dev_size;
370 }
371 
FileSize(int fd)372 off_t FileSize(int fd) {
373   struct stat stbuf{};
374   int rc = fstat(fd, &stbuf);
375   CHECK_EQ(rc, 0);
376   if (rc < 0) {
377     PLOG(ERROR) << "Error stat-ing " << fd;
378     return rc;
379   }
380   if (S_ISREG(stbuf.st_mode))
381     return stbuf.st_size;
382   if (S_ISBLK(stbuf.st_mode))
383     return BlockDevSize(fd);
384   LOG(ERROR) << "Couldn't determine the type of " << fd;
385   return -1;
386 }
387 
FileSize(const string & path)388 off_t FileSize(const string& path) {
389   int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
390   if (fd == -1) {
391     PLOG(ERROR) << "Error opening " << path;
392     return fd;
393   }
394   off_t size = FileSize(fd);
395   if (size == -1)
396     PLOG(ERROR) << "Error getting file size of " << path;
397   close(fd);
398   return size;
399 }
400 
SendFile(int out_fd,int in_fd,size_t count)401 bool SendFile(int out_fd, int in_fd, size_t count) {
402   off64_t offset = lseek(in_fd, 0, SEEK_CUR);
403   TEST_AND_RETURN_FALSE_ERRNO(offset >= 0);
404   constexpr size_t BUFFER_SIZE = 4096;
405   while (count > 0) {
406     const auto bytes_written =
407         sendfile(out_fd, in_fd, &offset, std::min(count, BUFFER_SIZE));
408     TEST_AND_RETURN_FALSE_ERRNO(bytes_written > 0);
409     count -= bytes_written;
410   }
411   return true;
412 }
413 
DeleteDirectory(const char * dirname)414 bool DeleteDirectory(const char* dirname) {
415   if (!std::filesystem::exists(dirname)) {
416     return true;
417   }
418   const std::string tmpdir = std::string(dirname) + "_deleted";
419   std::filesystem::remove_all(tmpdir);
420   if (rename(dirname, tmpdir.c_str()) != 0) {
421     PLOG(ERROR) << "Failed to rename " << dirname << " to " << tmpdir;
422     return false;
423   }
424   std::filesystem::remove_all(tmpdir);
425   return true;
426 }
427 
FsyncDirectoryContents(const char * dirname)428 bool FsyncDirectoryContents(const char* dirname) {
429   std::filesystem::path dir_path(dirname);
430 
431   std::error_code ec;
432   if (!std::filesystem::exists(dir_path, ec) ||
433       !std::filesystem::is_directory(dir_path, ec)) {
434     LOG(ERROR) << "Error: Invalid directory path: " << dirname << std::endl;
435     return false;
436   }
437 
438   for (const auto& entry : std::filesystem::directory_iterator(dirname, ec)) {
439     if (entry.is_regular_file()) {
440       int fd = open(entry.path().c_str(), O_RDONLY | O_CLOEXEC);
441       if (fd == -1) {
442         LOG(ERROR) << "open failed: " << entry.path();
443         return false;
444       }
445 
446       if (fsync(fd) == -1) {
447         LOG(ERROR) << "fsync failed";
448         return false;
449       }
450 
451       close(fd);
452     }
453   }
454 
455   return true;
456 }
457 
FsyncDirectory(const char * dirname)458 bool FsyncDirectory(const char* dirname) {
459   if (!FsyncDirectoryContents(dirname)) {
460     LOG(ERROR) << "failed to fsync directory contents";
461     return false;
462   }
463   android::base::unique_fd fd(
464       TEMP_FAILURE_RETRY(open(dirname, O_RDONLY | O_CLOEXEC)));
465   if (fd == -1) {
466     PLOG(ERROR) << "Failed to open " << dirname;
467     return false;
468   }
469   if (fsync(fd) == -1) {
470     if (errno == EROFS || errno == EINVAL) {
471       PLOG(WARNING) << "Skip fsync " << dirname
472                     << " on a file system does not support synchronization";
473     } else {
474       PLOG(ERROR) << "Failed to fsync " << dirname;
475       return false;
476     }
477   }
478   return true;
479 }
480 
WriteStringToFileAtomic(const std::string & path,std::string_view content)481 bool WriteStringToFileAtomic(const std::string& path,
482                              std::string_view content) {
483   const std::string tmp_path = path + ".tmp";
484   {
485     const int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC;
486     android::base::unique_fd fd(
487         TEMP_FAILURE_RETRY(open(tmp_path.c_str(), flags, 0644)));
488     if (fd == -1) {
489       PLOG(ERROR) << "Failed to open " << path;
490       return false;
491     }
492     if (!WriteAll(fd.get(), content.data(), content.size())) {
493       PLOG(ERROR) << "Failed to write to fd " << fd;
494       return false;
495     }
496     // rename() without fsync() is not safe. Data could still be living on page
497     // cache. To ensure atomiticity, call fsync()
498     if (fsync(fd) != 0) {
499       PLOG(ERROR) << "Failed to fsync " << tmp_path;
500     }
501   }
502   if (rename(tmp_path.c_str(), path.c_str()) == -1) {
503     PLOG(ERROR) << "rename failed from " << tmp_path << " to " << path;
504     return false;
505   }
506   return FsyncDirectory(std::filesystem::path(path).parent_path().c_str());
507 }
508 
HexDumpArray(const uint8_t * const arr,const size_t length)509 void HexDumpArray(const uint8_t* const arr, const size_t length) {
510   LOG(INFO) << "Logging array of length: " << length;
511   const unsigned int bytes_per_line = 16;
512   for (uint32_t i = 0; i < length; i += bytes_per_line) {
513     const unsigned int bytes_remaining = length - i;
514     const unsigned int bytes_per_this_line =
515         min(bytes_per_line, bytes_remaining);
516     char header[100];
517     int r = snprintf(header, sizeof(header), "0x%08x : ", i);
518     TEST_AND_RETURN(r == 13);
519     string line = header;
520     for (unsigned int j = 0; j < bytes_per_this_line; j++) {
521       char buf[20];
522       uint8_t c = arr[i + j];
523       r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
524       TEST_AND_RETURN(r == 3);
525       line += buf;
526     }
527     LOG(INFO) << line;
528   }
529 }
530 
SplitPartitionName(const string & partition_name,string * out_disk_name,int * out_partition_num)531 bool SplitPartitionName(const string& partition_name,
532                         string* out_disk_name,
533                         int* out_partition_num) {
534   if (!base::StartsWith(
535           partition_name, "/dev/", base::CompareCase::SENSITIVE)) {
536     LOG(ERROR) << "Invalid partition device name: " << partition_name;
537     return false;
538   }
539 
540   size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
541   if (last_nondigit_pos == string::npos ||
542       (last_nondigit_pos + 1) == partition_name.size()) {
543     LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
544     return false;
545   }
546 
547   if (out_disk_name) {
548     // Special case for MMC devices which have the following naming scheme:
549     // mmcblk0p2
550     size_t disk_name_len = last_nondigit_pos;
551     if (partition_name[last_nondigit_pos] != 'p' || last_nondigit_pos == 0 ||
552         !isdigit(partition_name[last_nondigit_pos - 1])) {
553       disk_name_len++;
554     }
555     *out_disk_name = partition_name.substr(0, disk_name_len);
556   }
557 
558   if (out_partition_num) {
559     string partition_str = partition_name.substr(last_nondigit_pos + 1);
560     *out_partition_num = atoi(partition_str.c_str());
561   }
562   return true;
563 }
564 
MakePartitionName(const string & disk_name,int partition_num)565 string MakePartitionName(const string& disk_name, int partition_num) {
566   if (partition_num < 1) {
567     LOG(ERROR) << "Invalid partition number: " << partition_num;
568     return string();
569   }
570 
571   if (!base::StartsWith(disk_name, "/dev/", base::CompareCase::SENSITIVE)) {
572     LOG(ERROR) << "Invalid disk name: " << disk_name;
573     return string();
574   }
575 
576   string partition_name = disk_name;
577   if (isdigit(partition_name.back())) {
578     // Special case for devices with names ending with a digit.
579     // Add "p" to separate the disk name from partition number,
580     // e.g. "/dev/loop0p2"
581     partition_name += 'p';
582   }
583 
584   partition_name += std::to_string(partition_num);
585 
586   return partition_name;
587 }
588 
FileExists(const char * path)589 bool FileExists(const char* path) {
590   struct stat stbuf{};
591   return 0 == lstat(path, &stbuf);
592 }
593 
IsSymlink(const char * path)594 bool IsSymlink(const char* path) {
595   struct stat stbuf{};
596   return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
597 }
598 
IsRegFile(const char * path)599 bool IsRegFile(const char* path) {
600   struct stat stbuf{};
601   return lstat(path, &stbuf) == 0 && S_ISREG(stbuf.st_mode) != 0;
602 }
603 
MakeTempFile(const string & base_filename_template,string * filename,int * fd)604 bool MakeTempFile(const string& base_filename_template,
605                   string* filename,
606                   int* fd) {
607   base::FilePath filename_template;
608   TEST_AND_RETURN_FALSE(
609       GetTempName(base_filename_template, &filename_template));
610   DCHECK(filename || fd);
611   vector<char> buf(filename_template.value().size() + 1);
612   memcpy(buf.data(),
613          filename_template.value().data(),
614          filename_template.value().size());
615   buf[filename_template.value().size()] = '\0';
616 
617   int mkstemp_fd = mkstemp(buf.data());
618   TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
619   if (filename) {
620     *filename = buf.data();
621   }
622   if (fd) {
623     *fd = mkstemp_fd;
624   } else {
625     close(mkstemp_fd);
626   }
627   return true;
628 }
629 
SetBlockDeviceReadOnly(const string & device,bool read_only)630 bool SetBlockDeviceReadOnly(const string& device, bool read_only) {
631   int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY | O_CLOEXEC));
632   if (fd < 0) {
633     PLOG(ERROR) << "Opening block device " << device;
634     return false;
635   }
636   ScopedFdCloser fd_closer(&fd);
637   // We take no action if not needed.
638   int read_only_flag{};
639   int expected_flag = read_only ? 1 : 0;
640   int rc = ioctl(fd, BLKROGET, &read_only_flag);
641   // In case of failure reading the setting we will try to set it anyway.
642   if (rc == 0 && read_only_flag == expected_flag)
643     return true;
644 
645   rc = ioctl(fd, BLKROSET, &expected_flag);
646   if (rc != 0) {
647     PLOG(ERROR) << "Marking block device " << device
648                 << " as read_only=" << expected_flag;
649     return false;
650   }
651 
652   /*
653    * Read back the value to check if it is configured successfully.
654    * If fail, use the second method, set the file
655    * /sys/block/<partition_name>/force_ro
656    * to config the read only property.
657    */
658   rc = ioctl(fd, BLKROGET, &read_only_flag);
659   if (rc != 0) {
660     PLOG(ERROR) << "Failed to read back block device read-only value:"
661                 << device;
662     return false;
663   }
664   if (read_only_flag == expected_flag) {
665     return true;
666   }
667 
668   std::array<char, PATH_MAX> device_name;
669   char* pdevice = realpath(device.c_str(), device_name.data());
670   TEST_AND_RETURN_FALSE_ERRNO(pdevice);
671 
672   std::string real_path(pdevice);
673   std::size_t offset = real_path.find_last_of('/');
674   if (offset == std::string::npos) {
675     LOG(ERROR) << "Could not find partition name from " << real_path;
676     return false;
677   }
678   const std::string partition_name = real_path.substr(offset + 1);
679 
680   std::string force_ro_file = "/sys/block/" + partition_name + "/force_ro";
681   android::base::unique_fd fd_force_ro{
682       HANDLE_EINTR(open(force_ro_file.c_str(), O_WRONLY | O_CLOEXEC))};
683   TEST_AND_RETURN_FALSE_ERRNO(fd_force_ro >= 0);
684 
685   rc = write(fd_force_ro, expected_flag ? "1" : "0", 1);
686   TEST_AND_RETURN_FALSE_ERRNO(rc > 0);
687 
688   // Read back again
689   rc = ioctl(fd, BLKROGET, &read_only_flag);
690   if (rc != 0) {
691     PLOG(ERROR) << "Failed to read back block device read-only value:"
692                 << device;
693     return false;
694   }
695   if (read_only_flag != expected_flag) {
696     LOG(ERROR) << "After modifying force_ro, marking block device " << device
697                << " as read_only=" << expected_flag;
698     return false;
699   }
700   return true;
701 }
702 
MountFilesystem(const string & device,const string & mountpoint,unsigned long mountflags,const string & type,const string & fs_mount_options)703 bool MountFilesystem(const string& device,
704                      const string& mountpoint,
705                      unsigned long mountflags,  // NOLINT(runtime/int)
706                      const string& type,
707                      const string& fs_mount_options) {
708   vector<const char*> fstypes;
709   if (type.empty()) {
710     fstypes = {"ext2", "ext3", "ext4", "squashfs", "erofs"};
711   } else {
712     fstypes = {type.c_str()};
713   }
714   for (const char* fstype : fstypes) {
715     int rc = mount(device.c_str(),
716                    mountpoint.c_str(),
717                    fstype,
718                    mountflags,
719                    fs_mount_options.c_str());
720     if (rc == 0)
721       return true;
722 
723     PLOG(WARNING) << "Unable to mount destination device " << device << " on "
724                   << mountpoint << " as " << fstype;
725   }
726   if (!type.empty()) {
727     LOG(ERROR) << "Unable to mount " << device << " with any supported type";
728   }
729   return false;
730 }
731 
UnmountFilesystem(const string & mountpoint)732 bool UnmountFilesystem(const string& mountpoint) {
733   int num_retries = 1;
734   for (;; ++num_retries) {
735     if (umount(mountpoint.c_str()) == 0)
736       return true;
737     if (errno != EBUSY || num_retries >= kUnmountMaxNumOfRetries)
738       break;
739     usleep(kUnmountRetryIntervalInMicroseconds);
740   }
741   if (errno == EINVAL) {
742     LOG(INFO) << "Not a mountpoint: " << mountpoint;
743     return false;
744   }
745   PLOG(WARNING) << "Error unmounting " << mountpoint << " after " << num_retries
746                 << " attempts. Lazy unmounting instead, error was";
747   if (umount2(mountpoint.c_str(), MNT_DETACH) != 0) {
748     PLOG(ERROR) << "Lazy unmount failed";
749     return false;
750   }
751   return true;
752 }
753 
IsMountpoint(const std::string & mountpoint)754 bool IsMountpoint(const std::string& mountpoint) {
755   struct stat stdir{}, stparent{};
756 
757   // Check whether the passed mountpoint is a directory and the /.. is in the
758   // same device or not. If mountpoint/.. is in a different device it means that
759   // there is a filesystem mounted there. If it is not, but they both point to
760   // the same inode it basically is the special case of /.. pointing to /. This
761   // test doesn't play well with bind mount but that's out of the scope of what
762   // we want to detect here.
763   if (lstat(mountpoint.c_str(), &stdir) != 0) {
764     PLOG(ERROR) << "Error stat'ing " << mountpoint;
765     return false;
766   }
767   if (!S_ISDIR(stdir.st_mode))
768     return false;
769 
770   base::FilePath parent(mountpoint);
771   parent = parent.Append("..");
772   if (lstat(parent.value().c_str(), &stparent) != 0) {
773     PLOG(ERROR) << "Error stat'ing " << parent.value();
774     return false;
775   }
776   return S_ISDIR(stparent.st_mode) &&
777          (stparent.st_dev != stdir.st_dev || stparent.st_ino == stdir.st_ino);
778 }
779 
780 // Tries to parse the header of an ELF file to obtain a human-readable
781 // description of it on the |output| string.
GetFileFormatELF(const uint8_t * buffer,size_t size,string * output)782 static bool GetFileFormatELF(const uint8_t* buffer,
783                              size_t size,
784                              string* output) {
785   // 0x00: EI_MAG - ELF magic header, 4 bytes.
786   if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
787     return false;
788   *output = "ELF";
789 
790   // 0x04: EI_CLASS, 1 byte.
791   if (size < EI_CLASS + 1)
792     return true;
793   switch (buffer[EI_CLASS]) {
794     case ELFCLASS32:
795       *output += " 32-bit";
796       break;
797     case ELFCLASS64:
798       *output += " 64-bit";
799       break;
800     default:
801       *output += " ?-bit";
802   }
803 
804   // 0x05: EI_DATA, endianness, 1 byte.
805   if (size < EI_DATA + 1)
806     return true;
807   uint8_t ei_data = buffer[EI_DATA];
808   switch (ei_data) {
809     case ELFDATA2LSB:
810       *output += " little-endian";
811       break;
812     case ELFDATA2MSB:
813       *output += " big-endian";
814       break;
815     default:
816       *output += " ?-endian";
817       // Don't parse anything after the 0x10 offset if endianness is unknown.
818       return true;
819   }
820 
821   const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
822   // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
823   // and size is the same for both 32 and 64 bits.
824   if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
825     return true;
826   uint16_t e_machine{};
827   // Fix endianness regardless of the host endianness.
828   if (ei_data == ELFDATA2LSB)
829     e_machine = le16toh(hdr->e_machine);
830   else
831     e_machine = be16toh(hdr->e_machine);
832 
833   switch (e_machine) {
834     case EM_386:
835       *output += " x86";
836       break;
837     case EM_MIPS:
838       *output += " mips";
839       break;
840     case EM_ARM:
841       *output += " arm";
842       break;
843     case EM_X86_64:
844       *output += " x86-64";
845       break;
846     default:
847       *output += " unknown-arch";
848   }
849   return true;
850 }
851 
GetFileFormat(const string & path)852 string GetFileFormat(const string& path) {
853   brillo::Blob buffer;
854   if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
855     return "File not found.";
856 
857   string result;
858   if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
859     return result;
860 
861   return "data";
862 }
863 
FuzzInt(int value,unsigned int range)864 int FuzzInt(int value, unsigned int range) {
865   int min = value - range / 2;
866   int max = value + range - range / 2;
867   return base::RandInt(min, max);
868 }
869 
FormatSecs(unsigned secs)870 string FormatSecs(unsigned secs) {
871   return FormatTimeDelta(TimeDelta::FromSeconds(secs));
872 }
873 
FormatTimeDelta(TimeDelta delta)874 string FormatTimeDelta(TimeDelta delta) {
875   string str;
876 
877   // Handle negative durations by prefixing with a minus.
878   if (delta.ToInternalValue() < 0) {
879     delta *= -1;
880     str = "-";
881   }
882 
883   // Canonicalize into days, hours, minutes, seconds and microseconds.
884   unsigned days = delta.InDays();
885   delta -= TimeDelta::FromDays(days);
886   unsigned hours = delta.InHours();
887   delta -= TimeDelta::FromHours(hours);
888   unsigned mins = delta.InMinutes();
889   delta -= TimeDelta::FromMinutes(mins);
890   unsigned secs = delta.InSeconds();
891   delta -= TimeDelta::FromSeconds(secs);
892   unsigned usecs = delta.InMicroseconds();
893 
894   if (days)
895     base::StringAppendF(&str, "%ud", days);
896   if (days || hours)
897     base::StringAppendF(&str, "%uh", hours);
898   if (days || hours || mins)
899     base::StringAppendF(&str, "%um", mins);
900   base::StringAppendF(&str, "%u", secs);
901   if (usecs) {
902     int width = 6;
903     while ((usecs / 10) * 10 == usecs) {
904       usecs /= 10;
905       width--;
906     }
907     base::StringAppendF(&str, ".%0*u", width, usecs);
908   }
909   base::StringAppendF(&str, "s");
910   return str;
911 }
912 
ToString(const Time utc_time)913 string ToString(const Time utc_time) {
914   Time::Exploded exp_time{};
915   utc_time.UTCExplode(&exp_time);
916   return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
917                             exp_time.month,
918                             exp_time.day_of_month,
919                             exp_time.year,
920                             exp_time.hour,
921                             exp_time.minute,
922                             exp_time.second);
923 }
924 
ToString(bool b)925 string ToString(bool b) {
926   return (b ? "true" : "false");
927 }
928 
ToString(DownloadSource source)929 string ToString(DownloadSource source) {
930   switch (source) {
931     case kDownloadSourceHttpsServer:
932       return "HttpsServer";
933     case kDownloadSourceHttpServer:
934       return "HttpServer";
935     case kDownloadSourceHttpPeer:
936       return "HttpPeer";
937     case kNumDownloadSources:
938       return "Unknown";
939       // Don't add a default case to let the compiler warn about newly added
940       // download sources which should be added here.
941   }
942 
943   return "Unknown";
944 }
945 
ToString(PayloadType payload_type)946 string ToString(PayloadType payload_type) {
947   switch (payload_type) {
948     case kPayloadTypeDelta:
949       return "Delta";
950     case kPayloadTypeFull:
951       return "Full";
952     case kPayloadTypeForcedFull:
953       return "ForcedFull";
954     case kNumPayloadTypes:
955       return "Unknown";
956       // Don't add a default case to let the compiler warn about newly added
957       // payload types which should be added here.
958   }
959 
960   return "Unknown";
961 }
962 
GetBaseErrorCode(ErrorCode code)963 ErrorCode GetBaseErrorCode(ErrorCode code) {
964   // Ignore the higher order bits in the code by applying the mask as
965   // we want the enumerations to be in the small contiguous range
966   // with values less than ErrorCode::kUmaReportedMax.
967   ErrorCode base_code = static_cast<ErrorCode>(
968       static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
969 
970   // Make additional adjustments required for UMA and error classification.
971   // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
972   // chromium-os:34369.
973   if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
974     // Since we want to keep the enums to a small value, aggregate all HTTP
975     // errors into this one bucket for UMA and error classification purposes.
976     LOG(INFO) << "Converting error code " << base_code
977               << " to ErrorCode::kOmahaErrorInHTTPResponse";
978     base_code = ErrorCode::kOmahaErrorInHTTPResponse;
979   }
980 
981   return base_code;
982 }
983 
StringVectorToString(const vector<string> & vec_str)984 string StringVectorToString(const vector<string>& vec_str) {
985   string str = "[";
986   for (vector<string>::const_iterator i = vec_str.begin(); i != vec_str.end();
987        ++i) {
988     if (i != vec_str.begin())
989       str += ", ";
990     str += '"';
991     str += *i;
992     str += '"';
993   }
994   str += "]";
995   return str;
996 }
997 
998 // The P2P file id should be the same for devices running new version and old
999 // version so that they can share it with each other. The hash in the response
1000 // was base64 encoded, but now that we switched to use "hash_sha256" field which
1001 // is hex encoded, we have to convert them back to base64 for P2P. However, the
1002 // base64 encoded hash was base64 encoded here again historically for some
1003 // reason, so we keep the same behavior here.
CalculateP2PFileId(const brillo::Blob & payload_hash,size_t payload_size)1004 string CalculateP2PFileId(const brillo::Blob& payload_hash,
1005                           size_t payload_size) {
1006   string encoded_hash = brillo::data_encoding::Base64Encode(
1007       brillo::data_encoding::Base64Encode(payload_hash));
1008   return base::StringPrintf("cros_update_size_%" PRIuS "_hash_%s",
1009                             payload_size,
1010                             encoded_hash.c_str());
1011 }
1012 
ConvertToOmahaInstallDate(Time time,int * out_num_days)1013 bool ConvertToOmahaInstallDate(Time time, int* out_num_days) {
1014   time_t unix_time = time.ToTimeT();
1015   // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
1016   const time_t kOmahaEpoch = 1167638400;
1017   const int64_t kNumSecondsPerWeek = 7 * 24 * 3600;
1018   const int64_t kNumDaysPerWeek = 7;
1019 
1020   time_t omaha_time = unix_time - kOmahaEpoch;
1021 
1022   if (omaha_time < 0)
1023     return false;
1024 
1025   // Note, as per the comment in utils.h we are deliberately not
1026   // handling DST correctly.
1027 
1028   int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
1029   *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
1030 
1031   return true;
1032 }
1033 
GetMinorVersion(const brillo::KeyValueStore & store,uint32_t * minor_version)1034 bool GetMinorVersion(const brillo::KeyValueStore& store,
1035                      uint32_t* minor_version) {
1036   string result;
1037   if (store.GetString("PAYLOAD_MINOR_VERSION", &result)) {
1038     if (!base::StringToUint(result, minor_version)) {
1039       LOG(ERROR) << "StringToUint failed when parsing delta minor version.";
1040       return false;
1041     }
1042     return true;
1043   }
1044   return false;
1045 }
1046 
ReadExtents(const std::string & path,const google::protobuf::RepeatedPtrField<Extent> & extents,brillo::Blob * out_data,size_t block_size)1047 bool ReadExtents(const std::string& path,
1048                  const google::protobuf::RepeatedPtrField<Extent>& extents,
1049                  brillo::Blob* out_data,
1050                  size_t block_size) {
1051   return ReadExtents(path,
1052                      {extents.begin(), extents.end()},
1053                      out_data,
1054                      utils::BlocksInExtents(extents) * block_size,
1055                      block_size);
1056 }
1057 
WriteExtents(const std::string & path,const google::protobuf::RepeatedPtrField<Extent> & extents,const brillo::Blob & data,size_t block_size)1058 bool WriteExtents(const std::string& path,
1059                   const google::protobuf::RepeatedPtrField<Extent>& extents,
1060                   const brillo::Blob& data,
1061                   size_t block_size) {
1062   EintrSafeFileDescriptor fd;
1063   TEST_AND_RETURN_FALSE(fd.Open(path.c_str(), O_RDWR));
1064   size_t bytes_written = 0;
1065   for (const auto& ext : extents) {
1066     TEST_AND_RETURN_FALSE_ERRNO(
1067         fd.Seek(ext.start_block() * block_size, SEEK_SET));
1068     TEST_AND_RETURN_FALSE_ERRNO(
1069         fd.Write(data.data() + bytes_written, ext.num_blocks() * block_size));
1070     bytes_written += ext.num_blocks() * block_size;
1071   }
1072   return true;
1073 }
ReadExtents(const std::string & path,const vector<Extent> & extents,brillo::Blob * out_data,ssize_t out_data_size,size_t block_size)1074 bool ReadExtents(const std::string& path,
1075                  const vector<Extent>& extents,
1076                  brillo::Blob* out_data,
1077                  ssize_t out_data_size,
1078                  size_t block_size) {
1079   FileDescriptorPtr fd = std::make_shared<EintrSafeFileDescriptor>();
1080   fd->Open(path.c_str(), O_RDONLY);
1081   return ReadExtents(fd, extents, out_data, out_data_size, block_size);
1082 }
1083 
ReadExtents(FileDescriptorPtr fd,const google::protobuf::RepeatedPtrField<Extent> & extents,brillo::Blob * out_data,size_t block_size)1084 bool ReadExtents(FileDescriptorPtr fd,
1085                  const google::protobuf::RepeatedPtrField<Extent>& extents,
1086                  brillo::Blob* out_data,
1087                  size_t block_size) {
1088   return ReadExtents(fd,
1089                      {extents.begin(), extents.end()},
1090                      out_data,
1091                      utils::BlocksInExtents(extents) * block_size,
1092                      block_size);
1093 }
1094 
ReadExtents(FileDescriptorPtr fd,const vector<Extent> & extents,brillo::Blob * out_data,ssize_t out_data_size,size_t block_size)1095 bool ReadExtents(FileDescriptorPtr fd,
1096                  const vector<Extent>& extents,
1097                  brillo::Blob* out_data,
1098                  ssize_t out_data_size,
1099                  size_t block_size) {
1100   brillo::Blob data(out_data_size);
1101   ssize_t bytes_read = 0;
1102 
1103   for (const Extent& extent : extents) {
1104     ssize_t bytes_read_this_iteration = 0;
1105     ssize_t bytes = extent.num_blocks() * block_size;
1106     TEST_LE(bytes_read + bytes, out_data_size);
1107     TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
1108                                           &data[bytes_read],
1109                                           bytes,
1110                                           extent.start_block() * block_size,
1111                                           &bytes_read_this_iteration));
1112     TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes);
1113     bytes_read += bytes_read_this_iteration;
1114   }
1115   TEST_AND_RETURN_FALSE(out_data_size == bytes_read);
1116   *out_data = data;
1117   return true;
1118 }
1119 
GetVpdValue(string key,string * result)1120 bool GetVpdValue(string key, string* result) {
1121   int exit_code = 0;
1122   string value, error;
1123   vector<string> cmd = {"vpd_get_value", key};
1124   if (!chromeos_update_engine::Subprocess::SynchronousExec(
1125           cmd, &exit_code, &value, &error) ||
1126       exit_code) {
1127     LOG(ERROR) << "Failed to get vpd key for " << value
1128                << " with exit code: " << exit_code << " and error: " << error;
1129     return false;
1130   } else if (!error.empty()) {
1131     LOG(INFO) << "vpd_get_value succeeded but with following errors: " << error;
1132   }
1133 
1134   base::TrimWhitespaceASCII(value, base::TRIM_ALL, &value);
1135   *result = value;
1136   return true;
1137 }
1138 
GetBootId(string * boot_id)1139 bool GetBootId(string* boot_id) {
1140   TEST_AND_RETURN_FALSE(
1141       base::ReadFileToString(base::FilePath(kBootIdPath), boot_id));
1142   base::TrimWhitespaceASCII(*boot_id, base::TRIM_TRAILING, boot_id);
1143   return true;
1144 }
1145 
VersionPrefix(const std::string & version)1146 int VersionPrefix(const std::string& version) {
1147   if (version.empty()) {
1148     return 0;
1149   }
1150   vector<string> tokens = base::SplitString(
1151       version, ".", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
1152   int value{};
1153   if (tokens.empty() || !base::StringToInt(tokens[0], &value))
1154     return -1;  // Target version is invalid.
1155   return value;
1156 }
1157 
ParseRollbackKeyVersion(const string & raw_version,uint16_t * high_version,uint16_t * low_version)1158 void ParseRollbackKeyVersion(const string& raw_version,
1159                              uint16_t* high_version,
1160                              uint16_t* low_version) {
1161   DCHECK(high_version);
1162   DCHECK(low_version);
1163   *high_version = numeric_limits<uint16_t>::max();
1164   *low_version = numeric_limits<uint16_t>::max();
1165 
1166   vector<string> parts = base::SplitString(
1167       raw_version, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
1168   if (parts.size() != 2) {
1169     // The version string must have exactly one period.
1170     return;
1171   }
1172 
1173   int high{};
1174   int low{};
1175   if (!(base::StringToInt(parts[0], &high) &&
1176         base::StringToInt(parts[1], &low))) {
1177     // Both parts of the version could not be parsed correctly.
1178     return;
1179   }
1180 
1181   if (high >= 0 && high < numeric_limits<uint16_t>::max() && low >= 0 &&
1182       low < numeric_limits<uint16_t>::max()) {
1183     *high_version = static_cast<uint16_t>(high);
1184     *low_version = static_cast<uint16_t>(low);
1185   }
1186 }
1187 
GetFilePath(int fd)1188 string GetFilePath(int fd) {
1189   base::FilePath proc("/proc/self/fd/" + std::to_string(fd));
1190   base::FilePath file_name;
1191 
1192   if (!base::ReadSymbolicLink(proc, &file_name)) {
1193     return "not found";
1194   }
1195   return file_name.value();
1196 }
1197 
GetTimeAsString(time_t utime)1198 string GetTimeAsString(time_t utime) {
1199   struct tm tm{};
1200   CHECK_EQ(localtime_r(&utime, &tm), &tm);
1201   char str[16];
1202   CHECK_EQ(strftime(str, sizeof(str), "%Y%m%d-%H%M%S", &tm), 15u);
1203   return str;
1204 }
1205 
GetExclusionName(const string & str_to_convert)1206 string GetExclusionName(const string& str_to_convert) {
1207   return base::NumberToString(base::StringPieceHash()(str_to_convert));
1208 }
1209 
ParseTimestamp(std::string_view str,int64_t * out)1210 static bool ParseTimestamp(std::string_view str, int64_t* out) {
1211   if (!base::StringToInt64(base::StringPiece(str.data(), str.size()), out)) {
1212     LOG(WARNING) << "Invalid timestamp: " << str;
1213     return false;
1214   }
1215   return true;
1216 }
1217 
IsTimestampNewer(const std::string_view old_version,const std::string_view new_version)1218 ErrorCode IsTimestampNewer(const std::string_view old_version,
1219                            const std::string_view new_version) {
1220   if (old_version.empty() || new_version.empty()) {
1221     LOG(WARNING)
1222         << "One of old/new timestamp is empty, permit update anyway. Old: "
1223         << old_version << " New: " << new_version;
1224     return ErrorCode::kSuccess;
1225   }
1226   int64_t old_ver = 0;
1227   if (!ParseTimestamp(old_version, &old_ver)) {
1228     return ErrorCode::kError;
1229   }
1230   int64_t new_ver = 0;
1231   if (!ParseTimestamp(new_version, &new_ver)) {
1232     return ErrorCode::kDownloadManifestParseError;
1233   }
1234   if (old_ver > new_ver) {
1235     return ErrorCode::kPayloadTimestampError;
1236   }
1237   return ErrorCode::kSuccess;
1238 }
1239 
GetReadonlyZeroBlock(size_t size)1240 std::unique_ptr<android::base::MappedFile> GetReadonlyZeroBlock(size_t size) {
1241   android::base::unique_fd fd{HANDLE_EINTR(open("/dev/zero", O_RDONLY))};
1242   return android::base::MappedFile::FromFd(fd, 0, size, PROT_READ);
1243 }
1244 
GetReadonlyZeroString(size_t size)1245 std::string_view GetReadonlyZeroString(size_t size) {
1246   // Reserve 512MB of Virtual Address Space. No actual memory will be used.
1247   static auto zero_block = GetReadonlyZeroBlock(1024 * 1024 * 512);
1248   if (size > zero_block->size()) {
1249     auto larger_block = GetReadonlyZeroBlock(size);
1250     zero_block = std::move(larger_block);
1251   }
1252   return {zero_block->data(), size};
1253 }
1254 
1255 }  // namespace utils
1256 
HexEncode(const brillo::Blob & blob)1257 std::string HexEncode(const brillo::Blob& blob) noexcept {
1258   return base::HexEncode(blob.data(), blob.size());
1259 }
1260 
HexEncode(const std::string_view blob)1261 std::string HexEncode(const std::string_view blob) noexcept {
1262   return base::HexEncode(blob.data(), blob.size());
1263 }
1264 
ToStringView(const std::vector<unsigned char> & blob)1265 [[nodiscard]] std::string_view ToStringView(
1266     const std::vector<unsigned char>& blob) noexcept {
1267   return std::string_view{reinterpret_cast<const char*>(blob.data()),
1268                           blob.size()};
1269 }
1270 
ToStringView(const void * data,size_t size)1271 [[nodiscard]] std::string_view ToStringView(const void* data,
1272                                             size_t size) noexcept {
1273   return std::string_view(reinterpret_cast<const char*>(data), size);
1274 }
1275 
1276 }  // namespace chromeos_update_engine
1277