blob: 359b6b8866a6fee79b5f242f91d4ea4720ce2d17 [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
Darin Petkov30291ed2010-11-12 10:23:06 -0800304bool IsSymlink(const char* path) {
305 struct stat stbuf;
306 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
307}
308
adlr@google.com3defe6a2009-12-04 20:57:17 +0000309std::string TempFilename(string path) {
310 static const string suffix("XXXXXX");
311 CHECK(StringHasSuffix(path, suffix));
312 do {
313 string new_suffix;
314 for (unsigned int i = 0; i < suffix.size(); i++) {
315 int r = rand() % (26 * 2 + 10); // [a-zA-Z0-9]
316 if (r < 26)
317 new_suffix.append(1, 'a' + r);
318 else if (r < (26 * 2))
319 new_suffix.append(1, 'A' + r - 26);
320 else
321 new_suffix.append(1, '0' + r - (26 * 2));
322 }
323 CHECK_EQ(new_suffix.size(), suffix.size());
324 path.resize(path.size() - new_suffix.size());
325 path.append(new_suffix);
326 } while (FileExists(path.c_str()));
327 return path;
328}
329
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700330bool MakeTempFile(const std::string& filename_template,
331 std::string* filename,
332 int* fd) {
333 DCHECK(filename || fd);
334 vector<char> buf(filename_template.size() + 1);
335 memcpy(&buf[0], filename_template.data(), filename_template.size());
336 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700337
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700338 int mkstemp_fd = mkstemp(&buf[0]);
339 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
340 if (filename) {
341 *filename = &buf[0];
342 }
343 if (fd) {
344 *fd = mkstemp_fd;
345 } else {
346 close(mkstemp_fd);
347 }
348 return true;
349}
350
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700351bool MakeTempDirectory(const std::string& dirname_template,
352 std::string* dirname) {
353 DCHECK(dirname);
354 vector<char> buf(dirname_template.size() + 1);
355 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
356 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700357
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700358 char* return_code = mkdtemp(&buf[0]);
359 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
360 *dirname = &buf[0];
361 return true;
362}
363
adlr@google.com3defe6a2009-12-04 20:57:17 +0000364bool StringHasSuffix(const std::string& str, const std::string& suffix) {
365 if (suffix.size() > str.size())
366 return false;
367 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
368}
369
370bool StringHasPrefix(const std::string& str, const std::string& prefix) {
371 if (prefix.size() > str.size())
372 return false;
373 return 0 == str.compare(0, prefix.size(), prefix);
374}
375
Will Drewry8f71da82010-08-30 14:07:11 -0500376const std::string BootDevice() {
377 char boot_path[PATH_MAX];
378 // Resolve the boot device path fully, including dereferencing
379 // through dm-verity.
380 int ret = rootdev(boot_path, sizeof(boot_path), true, false);
381
382 if (ret < 0) {
383 LOG(ERROR) << "rootdev failed to find the root device";
adlr@google.com3defe6a2009-12-04 20:57:17 +0000384 return "";
385 }
Will Drewry8f71da82010-08-30 14:07:11 -0500386 LOG_IF(WARNING, ret > 0) << "rootdev found a device name with no device node";
387
388 // This local variable is used to construct the return string and is not
389 // passed around after use.
390 return boot_path;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000391}
392
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700393const string BootKernelDevice(const std::string& boot_device) {
394 // Currntly this assumes the last digit of the boot device is
395 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
396 // get the kernel device.
397 string ret = boot_device;
398 if (ret.empty())
399 return ret;
400 char last_char = ret[ret.size() - 1];
401 if (last_char == '3' || last_char == '5' || last_char == '7') {
402 ret[ret.size() - 1] = last_char - 1;
403 return ret;
404 }
405 return "";
406}
407
adlr@google.com3defe6a2009-12-04 20:57:17 +0000408bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700409 const string& mountpoint,
410 unsigned long mountflags) {
411 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000412 if (rc < 0) {
413 string msg = ErrnoNumberAsString(errno);
414 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
415 << device << " on " << mountpoint;
416 return false;
417 }
418 return true;
419}
420
421bool UnmountFilesystem(const string& mountpoint) {
422 TEST_AND_RETURN_FALSE_ERRNO(umount(mountpoint.c_str()) == 0);
423 return true;
424}
425
Darin Petkovd3f8c892010-10-12 21:38:45 -0700426bool GetFilesystemSize(const std::string& device,
427 int* out_block_count,
428 int* out_block_size) {
429 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
430 TEST_AND_RETURN_FALSE(fd >= 0);
431 ScopedFdCloser fd_closer(&fd);
432 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
433}
434
435bool GetFilesystemSizeFromFD(int fd,
436 int* out_block_count,
437 int* out_block_size) {
438 TEST_AND_RETURN_FALSE(fd >= 0);
439
440 // Determine the ext3 filesystem size by directly reading the block count and
441 // block size information from the superblock. See include/linux/ext3_fs.h for
442 // more details on the structure.
443 ssize_t kBufferSize = 16 * sizeof(uint32_t);
444 char buffer[kBufferSize];
445 const int kSuperblockOffset = 1024;
446 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
447 kBufferSize) {
448 PLOG(ERROR) << "Unable to determine file system size:";
449 return false;
450 }
451 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
452 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
453 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
454 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
455 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
456 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
457 block_count = le32toh(block_count);
458 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
459 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
460 magic = le16toh(magic);
461
462 // Sanity check the parameters.
463 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
464 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
465 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
466 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
467 int block_size = 1 << log_block_size;
468 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
469 block_size <= kExt3MaxBlockSize);
470 TEST_AND_RETURN_FALSE(block_count > 0);
471
472 if (out_block_count) {
473 *out_block_count = block_count;
474 }
475 if (out_block_size) {
476 *out_block_size = block_size;
477 }
478 return true;
479}
480
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700481bool GetBootloader(BootLoader* out_bootloader) {
482 // For now, hardcode to syslinux.
483 *out_bootloader = BootLoader_SYSLINUX;
484 return true;
485}
486
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700487const char* GetGErrorMessage(const GError* error) {
488 if (!error)
489 return "Unknown error.";
490 return error->message;
491}
492
Darin Petkov296889c2010-07-23 16:20:54 -0700493bool Reboot() {
494 vector<string> command;
495 command.push_back("/sbin/shutdown");
496 command.push_back("-r");
497 command.push_back("now");
498 int rc = 0;
499 Subprocess::SynchronousExec(command, &rc);
500 TEST_AND_RETURN_FALSE(rc == 0);
501 return true;
502}
503
Darin Petkovc6c135c2010-08-11 13:36:18 -0700504bool SetProcessPriority(ProcessPriority priority) {
505 int prio = static_cast<int>(priority);
506 LOG(INFO) << "Setting process priority to " << prio;
507 TEST_AND_RETURN_FALSE(setpriority(PRIO_PROCESS, 0, prio) == 0);
508 return true;
509}
510
511int ComparePriorities(ProcessPriority priority_lhs,
512 ProcessPriority priority_rhs) {
513 return static_cast<int>(priority_rhs) - static_cast<int>(priority_lhs);
514}
515
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700516int FuzzInt(int value, unsigned int range) {
517 int min = value - range / 2;
518 int max = value + range - range / 2;
519 return base::RandInt(min, max);
520}
521
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800522const char* const kStatefulPartition = "/mnt/stateful_partition";
adlr@google.com3defe6a2009-12-04 20:57:17 +0000523
524} // namespace utils
525
526} // namespace chromeos_update_engine