blob: 162fe7b8d9ea51c59c19491beee4a861707bd080 [file] [log] [blame]
Darin Petkov296889c2010-07-23 16:20:54 -07001// Copyright (c) 2009 The Chromium OS Authors. All rights reserved.
adlr@google.com3defe6a2009-12-04 20:57:17 +00002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "update_engine/utils.h"
Darin Petkovf74eb652010-08-04 12:08:38 -07006
adlr@google.com3defe6a2009-12-04 20:57:17 +00007#include <sys/mount.h>
Darin Petkovc6c135c2010-08-11 13:36:18 -07008#include <sys/resource.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +00009#include <sys/stat.h>
10#include <sys/types.h>
11#include <dirent.h>
12#include <errno.h>
Andrew de los Reyes970bb282009-12-09 16:34:04 -080013#include <fcntl.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000014#include <stdio.h>
15#include <stdlib.h>
16#include <string.h>
17#include <unistd.h>
Darin Petkovf74eb652010-08-04 12:08:38 -070018
adlr@google.com3defe6a2009-12-04 20:57:17 +000019#include <algorithm>
Darin Petkovf74eb652010-08-04 12:08:38 -070020
Darin Petkovd3f8c892010-10-12 21:38:45 -070021#include <base/eintr_wrapper.h>
Will Drewry8f71da82010-08-30 14:07:11 -050022#include <base/file_path.h>
23#include <base/file_util.h>
24#include <base/rand_util.h>
25#include <base/string_util.h>
26#include <base/logging.h>
27#include <rootdev/rootdev.h>
28
Andrew de los Reyes970bb282009-12-09 16:34:04 -080029#include "update_engine/file_writer.h"
Darin Petkov33d30642010-08-04 10:18:57 -070030#include "update_engine/omaha_request_params.h"
Darin Petkov296889c2010-07-23 16:20:54 -070031#include "update_engine/subprocess.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000032
33using std::min;
34using std::string;
35using std::vector;
36
37namespace chromeos_update_engine {
38
39namespace utils {
40
Darin Petkov2a0e6332010-09-24 14:43:41 -070041static const char kOOBECompletedMarker[] = "/home/chronos/.oobe_completed";
Darin Petkova07586b2010-10-20 13:41:15 -070042static const char kDevImageMarker[] = "/root/.dev_mode";
Darin Petkov2a0e6332010-09-24 14:43:41 -070043
Darin Petkov33d30642010-08-04 10:18:57 -070044bool IsOfficialBuild() {
Darin Petkova07586b2010-10-20 13:41:15 -070045 return !file_util::PathExists(FilePath(kDevImageMarker));
Darin Petkov33d30642010-08-04 10:18:57 -070046}
47
Darin Petkov2a0e6332010-09-24 14:43:41 -070048bool IsOOBEComplete() {
49 return file_util::PathExists(FilePath(kOOBECompletedMarker));
50}
51
Andrew de los Reyes970bb282009-12-09 16:34:04 -080052bool WriteFile(const char* path, const char* data, int data_len) {
53 DirectFileWriter writer;
54 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
55 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -070056 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -080057 ScopedFileWriterCloser closer(&writer);
58 TEST_AND_RETURN_FALSE_ERRNO(data_len == writer.Write(data, data_len));
59 return true;
60}
61
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070062bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070063 const char* c_buf = static_cast<const char*>(buf);
64 ssize_t bytes_written = 0;
65 while (bytes_written < static_cast<ssize_t>(count)) {
66 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
67 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
68 bytes_written += rc;
69 }
70 return true;
71}
72
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070073bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
74 const char* c_buf = static_cast<const char*>(buf);
75 ssize_t bytes_written = 0;
76 while (bytes_written < static_cast<ssize_t>(count)) {
77 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
78 offset + bytes_written);
79 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
80 bytes_written += rc;
81 }
82 return true;
83}
84
85bool PReadAll(int fd, void* buf, size_t count, off_t offset,
86 ssize_t* out_bytes_read) {
87 char* c_buf = static_cast<char*>(buf);
88 ssize_t bytes_read = 0;
89 while (bytes_read < static_cast<ssize_t>(count)) {
90 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
91 offset + bytes_read);
92 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
93 if (rc == 0) {
94 break;
95 }
96 bytes_read += rc;
97 }
98 *out_bytes_read = bytes_read;
99 return true;
Darin Petkov296889c2010-07-23 16:20:54 -0700100
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700101}
102
adlr@google.com3defe6a2009-12-04 20:57:17 +0000103bool ReadFile(const std::string& path, std::vector<char>* out) {
104 CHECK(out);
105 FILE* fp = fopen(path.c_str(), "r");
106 if (!fp)
107 return false;
108 const size_t kChunkSize = 1024;
109 size_t read_size;
110 do {
111 char buf[kChunkSize];
112 read_size = fread(buf, 1, kChunkSize, fp);
113 if (read_size == 0)
114 break;
115 out->insert(out->end(), buf, buf + read_size);
116 } while (read_size == kChunkSize);
117 bool success = !ferror(fp);
118 TEST_AND_RETURN_FALSE_ERRNO(fclose(fp) == 0);
119 return success;
120}
121
122bool ReadFileToString(const std::string& path, std::string* out) {
123 vector<char> data;
124 bool success = ReadFile(path, &data);
125 if (!success) {
126 return false;
127 }
128 (*out) = string(&data[0], data.size());
129 return true;
130}
131
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700132off_t FileSize(const string& path) {
133 struct stat stbuf;
134 int rc = stat(path.c_str(), &stbuf);
135 CHECK_EQ(rc, 0);
136 if (rc < 0)
137 return rc;
138 return stbuf.st_size;
139}
140
adlr@google.com3defe6a2009-12-04 20:57:17 +0000141void HexDumpArray(const unsigned char* const arr, const size_t length) {
142 const unsigned char* const char_arr =
143 reinterpret_cast<const unsigned char* const>(arr);
144 LOG(INFO) << "Logging array of length: " << length;
145 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700146 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000147 const unsigned int bytes_remaining = length - i;
148 const unsigned int bytes_per_this_line = min(bytes_per_line,
149 bytes_remaining);
150 char header[100];
151 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
152 TEST_AND_RETURN(r == 13);
153 string line = header;
154 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
155 char buf[20];
156 unsigned char c = char_arr[i + j];
157 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
158 TEST_AND_RETURN(r == 3);
159 line += buf;
160 }
161 LOG(INFO) << line;
162 }
163}
164
165namespace {
166class ScopedDirCloser {
167 public:
168 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
169 ~ScopedDirCloser() {
170 if (dir_ && *dir_) {
171 int r = closedir(*dir_);
172 TEST_AND_RETURN_ERRNO(r == 0);
173 *dir_ = NULL;
174 dir_ = NULL;
175 }
176 }
177 private:
178 DIR** dir_;
179};
180} // namespace {}
181
182bool RecursiveUnlinkDir(const std::string& path) {
183 struct stat stbuf;
184 int r = lstat(path.c_str(), &stbuf);
185 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
186 if ((r < 0) && (errno == ENOENT))
187 // path request is missing. that's fine.
188 return true;
189 if (!S_ISDIR(stbuf.st_mode)) {
190 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700191 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000192 // success or path disappeared before we could unlink.
193 return true;
194 }
195 {
196 // We have a dir, unlink all children, then delete dir
197 DIR *dir = opendir(path.c_str());
198 TEST_AND_RETURN_FALSE_ERRNO(dir);
199 ScopedDirCloser dir_closer(&dir);
200 struct dirent dir_entry;
201 struct dirent *dir_entry_p;
202 int err = 0;
203 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
204 if (dir_entry_p == NULL) {
205 // end of stream reached
206 break;
207 }
208 // Skip . and ..
209 if (!strcmp(dir_entry_p->d_name, ".") ||
210 !strcmp(dir_entry_p->d_name, ".."))
211 continue;
212 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700213 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000214 }
215 TEST_AND_RETURN_FALSE(err == 0);
216 }
217 // unlink dir
218 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
219 return true;
220}
221
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700222string RootDevice(const string& partition_device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700223 FilePath device_path(partition_device);
224 if (device_path.DirName().value() != "/dev") {
225 return "";
226 }
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700227 string::const_iterator it = --partition_device.end();
228 for (; it >= partition_device.begin(); --it) {
229 if (!isdigit(*it))
230 break;
231 }
232 // Some devices contain a p before the partitions. For example:
233 // /dev/mmc0p4 should be shortened to /dev/mmc0.
234 if (*it == 'p')
235 --it;
236 return string(partition_device.begin(), it + 1);
237}
238
239string PartitionNumber(const string& partition_device) {
240 CHECK(!partition_device.empty());
241 string::const_iterator it = --partition_device.end();
242 for (; it >= partition_device.begin(); --it) {
243 if (!isdigit(*it))
244 break;
245 }
246 return string(it + 1, partition_device.end());
247}
248
Darin Petkovf74eb652010-08-04 12:08:38 -0700249string SysfsBlockDevice(const string& device) {
250 FilePath device_path(device);
251 if (device_path.DirName().value() != "/dev") {
252 return "";
253 }
254 return FilePath("/sys/block").Append(device_path.BaseName()).value();
255}
256
257bool IsRemovableDevice(const std::string& device) {
258 string sysfs_block = SysfsBlockDevice(device);
259 string removable;
260 if (sysfs_block.empty() ||
261 !file_util::ReadFileToString(FilePath(sysfs_block).Append("removable"),
262 &removable)) {
263 return false;
264 }
265 TrimWhitespaceASCII(removable, TRIM_ALL, &removable);
266 return removable == "1";
267}
268
adlr@google.com3defe6a2009-12-04 20:57:17 +0000269std::string ErrnoNumberAsString(int err) {
270 char buf[100];
271 buf[0] = '\0';
272 return strerror_r(err, buf, sizeof(buf));
273}
274
275std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
276 string ret;
277 bool last_insert_was_slash = false;
278 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
279 if (*it == '/') {
280 if (last_insert_was_slash)
281 continue;
282 last_insert_was_slash = true;
283 } else {
284 last_insert_was_slash = false;
285 }
286 ret.push_back(*it);
287 }
288 if (strip_trailing_slash && last_insert_was_slash) {
289 string::size_type last_non_slash = ret.find_last_not_of('/');
290 if (last_non_slash != string::npos) {
291 ret.resize(last_non_slash + 1);
292 } else {
293 ret = "";
294 }
295 }
296 return ret;
297}
298
299bool FileExists(const char* path) {
300 struct stat stbuf;
301 return 0 == lstat(path, &stbuf);
302}
303
304std::string TempFilename(string path) {
305 static const string suffix("XXXXXX");
306 CHECK(StringHasSuffix(path, suffix));
307 do {
308 string new_suffix;
309 for (unsigned int i = 0; i < suffix.size(); i++) {
310 int r = rand() % (26 * 2 + 10); // [a-zA-Z0-9]
311 if (r < 26)
312 new_suffix.append(1, 'a' + r);
313 else if (r < (26 * 2))
314 new_suffix.append(1, 'A' + r - 26);
315 else
316 new_suffix.append(1, '0' + r - (26 * 2));
317 }
318 CHECK_EQ(new_suffix.size(), suffix.size());
319 path.resize(path.size() - new_suffix.size());
320 path.append(new_suffix);
321 } while (FileExists(path.c_str()));
322 return path;
323}
324
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700325bool MakeTempFile(const std::string& filename_template,
326 std::string* filename,
327 int* fd) {
328 DCHECK(filename || fd);
329 vector<char> buf(filename_template.size() + 1);
330 memcpy(&buf[0], filename_template.data(), filename_template.size());
331 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700332
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700333 int mkstemp_fd = mkstemp(&buf[0]);
334 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
335 if (filename) {
336 *filename = &buf[0];
337 }
338 if (fd) {
339 *fd = mkstemp_fd;
340 } else {
341 close(mkstemp_fd);
342 }
343 return true;
344}
345
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700346bool MakeTempDirectory(const std::string& dirname_template,
347 std::string* dirname) {
348 DCHECK(dirname);
349 vector<char> buf(dirname_template.size() + 1);
350 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
351 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700352
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700353 char* return_code = mkdtemp(&buf[0]);
354 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
355 *dirname = &buf[0];
356 return true;
357}
358
adlr@google.com3defe6a2009-12-04 20:57:17 +0000359bool StringHasSuffix(const std::string& str, const std::string& suffix) {
360 if (suffix.size() > str.size())
361 return false;
362 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
363}
364
365bool StringHasPrefix(const std::string& str, const std::string& prefix) {
366 if (prefix.size() > str.size())
367 return false;
368 return 0 == str.compare(0, prefix.size(), prefix);
369}
370
Will Drewry8f71da82010-08-30 14:07:11 -0500371const std::string BootDevice() {
372 char boot_path[PATH_MAX];
373 // Resolve the boot device path fully, including dereferencing
374 // through dm-verity.
375 int ret = rootdev(boot_path, sizeof(boot_path), true, false);
376
377 if (ret < 0) {
378 LOG(ERROR) << "rootdev failed to find the root device";
adlr@google.com3defe6a2009-12-04 20:57:17 +0000379 return "";
380 }
Will Drewry8f71da82010-08-30 14:07:11 -0500381 LOG_IF(WARNING, ret > 0) << "rootdev found a device name with no device node";
382
383 // This local variable is used to construct the return string and is not
384 // passed around after use.
385 return boot_path;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000386}
387
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700388const string BootKernelDevice(const std::string& boot_device) {
389 // Currntly this assumes the last digit of the boot device is
390 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
391 // get the kernel device.
392 string ret = boot_device;
393 if (ret.empty())
394 return ret;
395 char last_char = ret[ret.size() - 1];
396 if (last_char == '3' || last_char == '5' || last_char == '7') {
397 ret[ret.size() - 1] = last_char - 1;
398 return ret;
399 }
400 return "";
401}
402
adlr@google.com3defe6a2009-12-04 20:57:17 +0000403bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700404 const string& mountpoint,
405 unsigned long mountflags) {
406 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000407 if (rc < 0) {
408 string msg = ErrnoNumberAsString(errno);
409 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
410 << device << " on " << mountpoint;
411 return false;
412 }
413 return true;
414}
415
416bool UnmountFilesystem(const string& mountpoint) {
417 TEST_AND_RETURN_FALSE_ERRNO(umount(mountpoint.c_str()) == 0);
418 return true;
419}
420
Darin Petkovd3f8c892010-10-12 21:38:45 -0700421bool GetFilesystemSize(const std::string& device,
422 int* out_block_count,
423 int* out_block_size) {
424 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
425 TEST_AND_RETURN_FALSE(fd >= 0);
426 ScopedFdCloser fd_closer(&fd);
427 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
428}
429
430bool GetFilesystemSizeFromFD(int fd,
431 int* out_block_count,
432 int* out_block_size) {
433 TEST_AND_RETURN_FALSE(fd >= 0);
434
435 // Determine the ext3 filesystem size by directly reading the block count and
436 // block size information from the superblock. See include/linux/ext3_fs.h for
437 // more details on the structure.
438 ssize_t kBufferSize = 16 * sizeof(uint32_t);
439 char buffer[kBufferSize];
440 const int kSuperblockOffset = 1024;
441 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
442 kBufferSize) {
443 PLOG(ERROR) << "Unable to determine file system size:";
444 return false;
445 }
446 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
447 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
448 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
449 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
450 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
451 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
452 block_count = le32toh(block_count);
453 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
454 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
455 magic = le16toh(magic);
456
457 // Sanity check the parameters.
458 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
459 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
460 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
461 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
462 int block_size = 1 << log_block_size;
463 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
464 block_size <= kExt3MaxBlockSize);
465 TEST_AND_RETURN_FALSE(block_count > 0);
466
467 if (out_block_count) {
468 *out_block_count = block_count;
469 }
470 if (out_block_size) {
471 *out_block_size = block_size;
472 }
473 return true;
474}
475
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700476bool GetBootloader(BootLoader* out_bootloader) {
477 // For now, hardcode to syslinux.
478 *out_bootloader = BootLoader_SYSLINUX;
479 return true;
480}
481
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700482const char* GetGErrorMessage(const GError* error) {
483 if (!error)
484 return "Unknown error.";
485 return error->message;
486}
487
Darin Petkov296889c2010-07-23 16:20:54 -0700488bool Reboot() {
489 vector<string> command;
490 command.push_back("/sbin/shutdown");
491 command.push_back("-r");
492 command.push_back("now");
493 int rc = 0;
494 Subprocess::SynchronousExec(command, &rc);
495 TEST_AND_RETURN_FALSE(rc == 0);
496 return true;
497}
498
Darin Petkovc6c135c2010-08-11 13:36:18 -0700499bool SetProcessPriority(ProcessPriority priority) {
500 int prio = static_cast<int>(priority);
501 LOG(INFO) << "Setting process priority to " << prio;
502 TEST_AND_RETURN_FALSE(setpriority(PRIO_PROCESS, 0, prio) == 0);
503 return true;
504}
505
506int ComparePriorities(ProcessPriority priority_lhs,
507 ProcessPriority priority_rhs) {
508 return static_cast<int>(priority_rhs) - static_cast<int>(priority_lhs);
509}
510
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700511int FuzzInt(int value, unsigned int range) {
512 int min = value - range / 2;
513 int max = value + range - range / 2;
514 return base::RandInt(min, max);
515}
516
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800517const char* const kStatefulPartition = "/mnt/stateful_partition";
adlr@google.com3defe6a2009-12-04 20:57:17 +0000518
519} // namespace utils
520
521} // namespace chromeos_update_engine