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