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