blob: 3c83674a001393ba69b8f76a9ee3efae5f6e6e16 [file] [log] [blame]
Darin Petkovf2065b42011-05-17 16:36:27 -07001// Copyright (c) 2011 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#ifndef CHROMEOS_PLATFORM_UPDATE_ENGINE_UTILS_H__
6#define CHROMEOS_PLATFORM_UPDATE_ENGINE_UTILS_H__
7
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07008#include <errno.h>
Darin Petkovc6c135c2010-08-11 13:36:18 -07009
Andrew de los Reyes81ebcd82010-03-09 15:56:18 -080010#include <algorithm>
adlr@google.com3defe6a2009-12-04 20:57:17 +000011#include <set>
12#include <string>
13#include <vector>
Darin Petkovc6c135c2010-08-11 13:36:18 -070014
Gilad Arnoldf9609112012-02-29 11:38:47 -080015#include <base/eintr_wrapper.h>
Thieu Le5c7d9752010-12-15 16:09:28 -080016#include <ext2fs/ext2fs.h>
Andrew de los Reyesc7020782010-04-28 10:46:04 -070017#include <glib.h>
Darin Petkovc6c135c2010-08-11 13:36:18 -070018
adlr@google.com3defe6a2009-12-04 20:57:17 +000019#include "update_engine/action.h"
20#include "update_engine/action_processor.h"
21
22namespace chromeos_update_engine {
23
24namespace utils {
25
Darin Petkova07586b2010-10-20 13:41:15 -070026// Returns true if this is an official Chrome OS build, false otherwise.
Darin Petkov33d30642010-08-04 10:18:57 -070027bool IsOfficialBuild();
28
Darin Petkov2a0e6332010-09-24 14:43:41 -070029// Returns true if the OOBE process has been completed and EULA accepted, false
30// otherwise.
31bool IsOOBEComplete();
32
Darin Petkov44d98d92011-03-21 16:08:11 -070033// Returns true if the boot mode is normal or if it's unable to determine the
34// boot mode. Returns false if the boot mode is developer.
Darin Petkovc91dd6b2011-01-10 12:31:34 -080035bool IsNormalBootMode();
36
Darin Petkovf2065b42011-05-17 16:36:27 -070037// Returns the HWID or an empty string on error.
38std::string GetHardwareClass();
39
Andrew de los Reyes970bb282009-12-09 16:34:04 -080040// Writes the data passed to path. The file at path will be overwritten if it
41// exists. Returns true on success, false otherwise.
42bool WriteFile(const char* path, const char* data, int data_len);
43
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070044// Calls write() or pwrite() repeatedly until all count bytes at buf are
45// written to fd or an error occurs. Returns true on success.
46bool WriteAll(int fd, const void* buf, size_t count);
47bool PWriteAll(int fd, const void* buf, size_t count, off_t offset);
48
49// Calls pread() repeatedly until count bytes are read, or EOF is reached.
50// Returns number of bytes read in *bytes_read. Returns true on success.
51bool PReadAll(int fd, void* buf, size_t count, off_t offset,
52 ssize_t* out_bytes_read);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070053
adlr@google.com3defe6a2009-12-04 20:57:17 +000054// Returns the entire contents of the file at path. Returns true on success.
55bool ReadFile(const std::string& path, std::vector<char>* out);
56bool ReadFileToString(const std::string& path, std::string* out);
57
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070058// Returns the size of the file at path. If the file doesn't exist or some
59// error occurrs, -1 is returned.
60off_t FileSize(const std::string& path);
61
adlr@google.com3defe6a2009-12-04 20:57:17 +000062std::string ErrnoNumberAsString(int err);
63
64// Strips duplicate slashes, and optionally removes all trailing slashes.
65// Does not compact /./ or /../.
66std::string NormalizePath(const std::string& path, bool strip_trailing_slash);
67
68// Returns true if the file exists for sure. Returns false if it doesn't exist,
69// or an error occurs.
70bool FileExists(const char* path);
71
Darin Petkov30291ed2010-11-12 10:23:06 -080072// Returns true if |path| exists and is a symbolic link.
73bool IsSymlink(const char* path);
74
adlr@google.com3defe6a2009-12-04 20:57:17 +000075// The last 6 chars of path must be XXXXXX. They will be randomly changed
76// and a non-existent path will be returned. Intentionally makes a copy
77// of the string passed in.
78// NEVER CALL THIS FUNCTION UNLESS YOU ARE SURE
79// THAT YOUR PROCESS WILL BE THE ONLY THING WRITING FILES IN THIS DIRECTORY.
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -080080std::string TempFilename(std::string path);
adlr@google.com3defe6a2009-12-04 20:57:17 +000081
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070082// Calls mkstemp() with the template passed. Returns the filename in the
83// out param filename. If fd is non-NULL, the file fd returned by mkstemp
84// is not close()d and is returned in the out param 'fd'. However, if
85// fd is NULL, the fd from mkstemp() will be closed.
86// The last six chars of the template must be XXXXXX.
87// Returns true on success.
88bool MakeTempFile(const std::string& filename_template,
89 std::string* filename,
90 int* fd);
91
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070092// Calls mkdtemp() with the tempate passed. Returns the generated dirname
93// in the dirname param. Returns TRUE on success. dirname must not be NULL.
94bool MakeTempDirectory(const std::string& dirname_template,
95 std::string* dirname);
96
adlr@google.com3defe6a2009-12-04 20:57:17 +000097// Deletes a directory and all its contents synchronously. Returns true
98// on success. This may be called with a regular file--it will just unlink it.
99// This WILL cross filesystem boundaries.
100bool RecursiveUnlinkDir(const std::string& path);
101
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700102// Returns the root device for a partition. For example,
Darin Petkovf74eb652010-08-04 12:08:38 -0700103// RootDevice("/dev/sda3") returns "/dev/sda". Returns an empty string
104// if the input device is not of the "/dev/xyz" form.
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700105std::string RootDevice(const std::string& partition_device);
106
107// Returns the partition number, as a string, of partition_device. For example,
Darin Petkovf74eb652010-08-04 12:08:38 -0700108// PartitionNumber("/dev/sda3") returns "3".
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700109std::string PartitionNumber(const std::string& partition_device);
110
Darin Petkovf74eb652010-08-04 12:08:38 -0700111// Returns the sysfs block device for a root block device. For
112// example, SysfsBlockDevice("/dev/sda") returns
113// "/sys/block/sda". Returns an empty string if the input device is
114// not of the "/dev/xyz" form.
115std::string SysfsBlockDevice(const std::string& device);
116
117// Returns true if the root |device| (e.g., "/dev/sdb") is known to be
118// removable, false otherwise.
119bool IsRemovableDevice(const std::string& device);
120
adlr@google.com3defe6a2009-12-04 20:57:17 +0000121// Synchronously mount or unmount a filesystem. Return true on success.
122// Mounts as ext3 with default options.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700123bool MountFilesystem(const std::string& device, const std::string& mountpoint,
124 unsigned long flags);
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800125bool UnmountFilesystem(const std::string& mountpoint);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000126
Darin Petkovd3f8c892010-10-12 21:38:45 -0700127// Returns the block count and the block byte size of the ext3 file system on
128// |device| (which may be a real device or a path to a filesystem image) or on
129// an opened file descriptor |fd|. The actual file-system size is |block_count|
130// * |block_size| bytes. Returns true on success, false otherwise.
131bool GetFilesystemSize(const std::string& device,
132 int* out_block_count,
133 int* out_block_size);
134bool GetFilesystemSizeFromFD(int fd,
135 int* out_block_count,
136 int* out_block_size);
137
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700138enum BootLoader {
139 BootLoader_SYSLINUX = 0,
140 BootLoader_CHROME_FIRMWARE = 1
141};
142// Detects which bootloader this system uses and returns it via the out
143// param. Returns true on success.
144bool GetBootloader(BootLoader* out_bootloader);
145
Darin Petkova0b9e772011-10-06 05:05:56 -0700146// Returns the error message, if any, from a GError pointer. Frees the GError
147// object and resets error to NULL.
148std::string GetAndFreeGError(GError** error);
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700149
Darin Petkov296889c2010-07-23 16:20:54 -0700150// Initiates a system reboot. Returns true on success, false otherwise.
151bool Reboot();
152
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800153// Schedules a Main Loop callback to trigger the crash reporter to perform an
154// upload as if this process had crashed.
155void ScheduleCrashReporterUpload();
156
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700157// Fuzzes an integer |value| randomly in the range:
158// [value - range / 2, value + range - range / 2]
159int FuzzInt(int value, unsigned int range);
160
adlr@google.com3defe6a2009-12-04 20:57:17 +0000161// Log a string in hex to LOG(INFO). Useful for debugging.
162void HexDumpArray(const unsigned char* const arr, const size_t length);
163inline void HexDumpString(const std::string& str) {
164 HexDumpArray(reinterpret_cast<const unsigned char*>(str.data()), str.size());
165}
166inline void HexDumpVector(const std::vector<char>& vect) {
167 HexDumpArray(reinterpret_cast<const unsigned char*>(&vect[0]), vect.size());
168}
169
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800170extern const char* const kStatefulPartition;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000171
172bool StringHasSuffix(const std::string& str, const std::string& suffix);
173bool StringHasPrefix(const std::string& str, const std::string& prefix);
174
175template<typename KeyType, typename ValueType>
176bool MapContainsKey(const std::map<KeyType, ValueType>& m, const KeyType& k) {
177 return m.find(k) != m.end();
178}
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800179template<typename KeyType>
180bool SetContainsKey(const std::set<KeyType>& s, const KeyType& k) {
181 return s.find(k) != s.end();
182}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000183
184template<typename ValueType>
185std::set<ValueType> SetWithValue(const ValueType& value) {
186 std::set<ValueType> ret;
187 ret.insert(value);
188 return ret;
189}
190
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800191template<typename T>
192bool VectorContainsValue(const std::vector<T>& vect, const T& value) {
Darin Petkovc1a8b422010-07-19 11:34:49 -0700193 return std::find(vect.begin(), vect.end(), value) != vect.end();
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800194}
195
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700196template<typename T>
197bool VectorIndexOf(const std::vector<T>& vect, const T& value,
198 typename std::vector<T>::size_type* out_index) {
199 typename std::vector<T>::const_iterator it = std::find(vect.begin(),
200 vect.end(),
201 value);
202 if (it == vect.end()) {
203 return false;
204 } else {
205 *out_index = it - vect.begin();
206 return true;
207 }
208}
209
Andrew de los Reyescc92cd32010-10-05 16:56:14 -0700210template<typename ValueType>
211void ApplyMap(std::vector<ValueType>* collection,
212 const std::map<ValueType, ValueType>& the_map) {
213 for (typename std::vector<ValueType>::iterator it = collection->begin();
214 it != collection->end(); ++it) {
215 typename std::map<ValueType, ValueType>::const_iterator map_it =
216 the_map.find(*it);
217 if (map_it != the_map.end()) {
218 *it = map_it->second;
219 }
220 }
221}
222
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700223// Returns the currently booted device. "/dev/sda3", for example.
adlr@google.com3defe6a2009-12-04 20:57:17 +0000224// This will not interpret LABEL= or UUID=. You'll need to use findfs
225// or something with equivalent funcionality to interpret those.
226const std::string BootDevice();
227
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700228// Returns the currently booted kernel device, "dev/sda2", for example.
229// Client must pass in the boot device. The suggested calling convention
230// is: BootKernelDevice(BootDevice()).
231// This function works by doing string modification on boot_device.
232// Returns empty string on failure.
233const std::string BootKernelDevice(const std::string& boot_device);
234
Darin Petkovc6c135c2010-08-11 13:36:18 -0700235enum ProcessPriority {
236 kProcessPriorityHigh = -10,
237 kProcessPriorityNormal = 0,
238 kProcessPriorityLow = 10,
239};
240
241// Compares process priorities and returns an integer that is less
242// than, equal to or greater than 0 if |priority_lhs| is,
243// respectively, lower than, same as or higher than |priority_rhs|.
244int ComparePriorities(ProcessPriority priority_lhs,
245 ProcessPriority priority_rhs);
246
247// Sets the current process priority to |priority|. Returns true on
248// success, false otherwise.
249bool SetProcessPriority(ProcessPriority priority);
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700250
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800251// Assumes data points to a Closure. Runs it and returns FALSE;
252gboolean GlibRunClosure(gpointer data);
253
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800254// Converts seconds into hour-minute-second notation. For example, 185 will
255// yield 3m5s and 4300 will yield 1h11m40s. Zero padding not applied. Seconds
256// are always shown in the result.
257std::string SecsToHourMinSecStr(unsigned secs);
258
adlr@google.com3defe6a2009-12-04 20:57:17 +0000259} // namespace utils
260
261// Class to unmount FS when object goes out of scope
262class ScopedFilesystemUnmounter {
263 public:
264 explicit ScopedFilesystemUnmounter(const std::string& mountpoint)
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800265 : mountpoint_(mountpoint),
266 should_unmount_(true) {}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000267 ~ScopedFilesystemUnmounter() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800268 if (should_unmount_) {
269 utils::UnmountFilesystem(mountpoint_);
270 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000271 }
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800272 void set_should_unmount(bool unmount) { should_unmount_ = unmount; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000273 private:
274 const std::string mountpoint_;
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800275 bool should_unmount_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700276 DISALLOW_COPY_AND_ASSIGN(ScopedFilesystemUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000277};
278
279// Utility class to close a file descriptor
280class ScopedFdCloser {
281 public:
282 explicit ScopedFdCloser(int* fd) : fd_(fd), should_close_(true) {}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000283 ~ScopedFdCloser() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800284 if (should_close_ && fd_ && (*fd_ >= 0)) {
Gilad Arnoldf9609112012-02-29 11:38:47 -0800285 if (!close(*fd_))
286 *fd_ = -1;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000287 }
288 }
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800289 void set_should_close(bool should_close) { should_close_ = should_close; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000290 private:
291 int* fd_;
292 bool should_close_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700293 DISALLOW_COPY_AND_ASSIGN(ScopedFdCloser);
294};
295
Gilad Arnoldf9609112012-02-29 11:38:47 -0800296// An EINTR-immune file descriptor closer.
297class ScopedEintrSafeFdCloser {
298 public:
299 explicit ScopedEintrSafeFdCloser(int* fd) : fd_(fd), should_close_(true) {}
300 ~ScopedEintrSafeFdCloser() {
301 if (should_close_ && fd_ && (*fd_ >= 0)) {
302 if (!HANDLE_EINTR(close(*fd_)))
303 *fd_ = -1;
304 }
305 }
306 void set_should_close(bool should_close) { should_close_ = should_close; }
307 private:
308 int* fd_;
309 bool should_close_;
310 DISALLOW_COPY_AND_ASSIGN(ScopedEintrSafeFdCloser);
311};
312
Thieu Le5c7d9752010-12-15 16:09:28 -0800313// Utility class to close a file system
314class ScopedExt2fsCloser {
315 public:
316 explicit ScopedExt2fsCloser(ext2_filsys filsys) : filsys_(filsys) {}
317 ~ScopedExt2fsCloser() { ext2fs_close(filsys_); }
318
319 private:
320 ext2_filsys filsys_;
321 DISALLOW_COPY_AND_ASSIGN(ScopedExt2fsCloser);
322};
323
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700324// Utility class to delete a file when it goes out of scope.
325class ScopedPathUnlinker {
326 public:
Darin Petkov52dcaeb2011-01-14 15:33:06 -0800327 explicit ScopedPathUnlinker(const std::string& path)
328 : path_(path),
329 should_remove_(true) {}
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700330 ~ScopedPathUnlinker() {
Darin Petkov52dcaeb2011-01-14 15:33:06 -0800331 if (should_remove_ && unlink(path_.c_str()) < 0) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700332 std::string err_message = strerror(errno);
333 LOG(ERROR) << "Unable to unlink path " << path_ << ": " << err_message;
334 }
335 }
Darin Petkov52dcaeb2011-01-14 15:33:06 -0800336 void set_should_remove(bool should_remove) { should_remove_ = should_remove; }
337
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700338 private:
339 const std::string path_;
Darin Petkov52dcaeb2011-01-14 15:33:06 -0800340 bool should_remove_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700341 DISALLOW_COPY_AND_ASSIGN(ScopedPathUnlinker);
342};
343
344// Utility class to delete an empty directory when it goes out of scope.
345class ScopedDirRemover {
346 public:
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800347 explicit ScopedDirRemover(const std::string& path)
348 : path_(path),
349 should_remove_(true) {}
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700350 ~ScopedDirRemover() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800351 if (should_remove_ && (rmdir(path_.c_str()) < 0)) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700352 PLOG(ERROR) << "Unable to remove dir " << path_;
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800353 }
354 }
355 void set_should_remove(bool should_remove) { should_remove_ = should_remove; }
356
357 protected:
358 const std::string path_;
359
360 private:
361 bool should_remove_;
362 DISALLOW_COPY_AND_ASSIGN(ScopedDirRemover);
363};
364
365// Utility class to unmount a filesystem mounted on a temporary directory and
366// delete the temporary directory when it goes out of scope.
367class ScopedTempUnmounter : public ScopedDirRemover {
368 public:
369 explicit ScopedTempUnmounter(const std::string& path) :
370 ScopedDirRemover(path) {}
371 ~ScopedTempUnmounter() {
372 utils::UnmountFilesystem(path_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700373 }
374 private:
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800375 DISALLOW_COPY_AND_ASSIGN(ScopedTempUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000376};
377
378// A little object to call ActionComplete on the ActionProcessor when
379// it's destructed.
380class ScopedActionCompleter {
381 public:
382 explicit ScopedActionCompleter(ActionProcessor* processor,
383 AbstractAction* action)
384 : processor_(processor),
385 action_(action),
Darin Petkovc1a8b422010-07-19 11:34:49 -0700386 code_(kActionCodeError),
adlr@google.com3defe6a2009-12-04 20:57:17 +0000387 should_complete_(true) {}
388 ~ScopedActionCompleter() {
389 if (should_complete_)
Darin Petkovc1a8b422010-07-19 11:34:49 -0700390 processor_->ActionComplete(action_, code_);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000391 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700392 void set_code(ActionExitCode code) { code_ = code; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000393 void set_should_complete(bool should_complete) {
394 should_complete_ = should_complete;
395 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700396
adlr@google.com3defe6a2009-12-04 20:57:17 +0000397 private:
398 ActionProcessor* processor_;
399 AbstractAction* action_;
Darin Petkovc1a8b422010-07-19 11:34:49 -0700400 ActionExitCode code_;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000401 bool should_complete_;
402 DISALLOW_COPY_AND_ASSIGN(ScopedActionCompleter);
403};
404
405} // namespace chromeos_update_engine
406
407#define TEST_AND_RETURN_FALSE_ERRNO(_x) \
408 do { \
409 bool _success = (_x); \
410 if (!_success) { \
411 std::string _msg = \
412 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
413 LOG(ERROR) << #_x " failed: " << _msg; \
414 return false; \
415 } \
416 } while (0)
417
418#define TEST_AND_RETURN_FALSE(_x) \
419 do { \
420 bool _success = (_x); \
421 if (!_success) { \
422 LOG(ERROR) << #_x " failed."; \
423 return false; \
424 } \
425 } while (0)
426
427#define TEST_AND_RETURN_ERRNO(_x) \
428 do { \
429 bool _success = (_x); \
430 if (!_success) { \
431 std::string _msg = \
432 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
433 LOG(ERROR) << #_x " failed: " << _msg; \
434 return; \
435 } \
436 } while (0)
437
438#define TEST_AND_RETURN(_x) \
439 do { \
440 bool _success = (_x); \
441 if (!_success) { \
442 LOG(ERROR) << #_x " failed."; \
443 return; \
444 } \
445 } while (0)
446
Thieu Le5c7d9752010-12-15 16:09:28 -0800447#define TEST_AND_RETURN_FALSE_ERRCODE(_x) \
448 do { \
449 errcode_t _error = (_x); \
450 if (_error) { \
451 errno = _error; \
452 LOG(ERROR) << #_x " failed: " << _error; \
453 return false; \
454 } \
455 } while (0)
456
adlr@google.com3defe6a2009-12-04 20:57:17 +0000457
458
459#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_UTILS_H__