blob: 728d992cdd641f602d086fea53268f55f1f610b5 [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
adlr@google.com3defe6a2009-12-04 20:57:17 +0000254} // namespace utils
255
256// Class to unmount FS when object goes out of scope
257class ScopedFilesystemUnmounter {
258 public:
259 explicit ScopedFilesystemUnmounter(const std::string& mountpoint)
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800260 : mountpoint_(mountpoint),
261 should_unmount_(true) {}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000262 ~ScopedFilesystemUnmounter() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800263 if (should_unmount_) {
264 utils::UnmountFilesystem(mountpoint_);
265 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000266 }
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800267 void set_should_unmount(bool unmount) { should_unmount_ = unmount; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000268 private:
269 const std::string mountpoint_;
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800270 bool should_unmount_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700271 DISALLOW_COPY_AND_ASSIGN(ScopedFilesystemUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000272};
273
274// Utility class to close a file descriptor
275class ScopedFdCloser {
276 public:
277 explicit ScopedFdCloser(int* fd) : fd_(fd), should_close_(true) {}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000278 ~ScopedFdCloser() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800279 if (should_close_ && fd_ && (*fd_ >= 0)) {
Gilad Arnoldf9609112012-02-29 11:38:47 -0800280 if (!close(*fd_))
281 *fd_ = -1;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000282 }
283 }
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800284 void set_should_close(bool should_close) { should_close_ = should_close; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000285 private:
286 int* fd_;
287 bool should_close_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700288 DISALLOW_COPY_AND_ASSIGN(ScopedFdCloser);
289};
290
Gilad Arnoldf9609112012-02-29 11:38:47 -0800291// An EINTR-immune file descriptor closer.
292class ScopedEintrSafeFdCloser {
293 public:
294 explicit ScopedEintrSafeFdCloser(int* fd) : fd_(fd), should_close_(true) {}
295 ~ScopedEintrSafeFdCloser() {
296 if (should_close_ && fd_ && (*fd_ >= 0)) {
297 if (!HANDLE_EINTR(close(*fd_)))
298 *fd_ = -1;
299 }
300 }
301 void set_should_close(bool should_close) { should_close_ = should_close; }
302 private:
303 int* fd_;
304 bool should_close_;
305 DISALLOW_COPY_AND_ASSIGN(ScopedEintrSafeFdCloser);
306};
307
Thieu Le5c7d9752010-12-15 16:09:28 -0800308// Utility class to close a file system
309class ScopedExt2fsCloser {
310 public:
311 explicit ScopedExt2fsCloser(ext2_filsys filsys) : filsys_(filsys) {}
312 ~ScopedExt2fsCloser() { ext2fs_close(filsys_); }
313
314 private:
315 ext2_filsys filsys_;
316 DISALLOW_COPY_AND_ASSIGN(ScopedExt2fsCloser);
317};
318
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700319// Utility class to delete a file when it goes out of scope.
320class ScopedPathUnlinker {
321 public:
Darin Petkov52dcaeb2011-01-14 15:33:06 -0800322 explicit ScopedPathUnlinker(const std::string& path)
323 : path_(path),
324 should_remove_(true) {}
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700325 ~ScopedPathUnlinker() {
Darin Petkov52dcaeb2011-01-14 15:33:06 -0800326 if (should_remove_ && unlink(path_.c_str()) < 0) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700327 std::string err_message = strerror(errno);
328 LOG(ERROR) << "Unable to unlink path " << path_ << ": " << err_message;
329 }
330 }
Darin Petkov52dcaeb2011-01-14 15:33:06 -0800331 void set_should_remove(bool should_remove) { should_remove_ = should_remove; }
332
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700333 private:
334 const std::string path_;
Darin Petkov52dcaeb2011-01-14 15:33:06 -0800335 bool should_remove_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700336 DISALLOW_COPY_AND_ASSIGN(ScopedPathUnlinker);
337};
338
339// Utility class to delete an empty directory when it goes out of scope.
340class ScopedDirRemover {
341 public:
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800342 explicit ScopedDirRemover(const std::string& path)
343 : path_(path),
344 should_remove_(true) {}
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700345 ~ScopedDirRemover() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800346 if (should_remove_ && (rmdir(path_.c_str()) < 0)) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700347 PLOG(ERROR) << "Unable to remove dir " << path_;
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800348 }
349 }
350 void set_should_remove(bool should_remove) { should_remove_ = should_remove; }
351
352 protected:
353 const std::string path_;
354
355 private:
356 bool should_remove_;
357 DISALLOW_COPY_AND_ASSIGN(ScopedDirRemover);
358};
359
360// Utility class to unmount a filesystem mounted on a temporary directory and
361// delete the temporary directory when it goes out of scope.
362class ScopedTempUnmounter : public ScopedDirRemover {
363 public:
364 explicit ScopedTempUnmounter(const std::string& path) :
365 ScopedDirRemover(path) {}
366 ~ScopedTempUnmounter() {
367 utils::UnmountFilesystem(path_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700368 }
369 private:
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800370 DISALLOW_COPY_AND_ASSIGN(ScopedTempUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000371};
372
373// A little object to call ActionComplete on the ActionProcessor when
374// it's destructed.
375class ScopedActionCompleter {
376 public:
377 explicit ScopedActionCompleter(ActionProcessor* processor,
378 AbstractAction* action)
379 : processor_(processor),
380 action_(action),
Darin Petkovc1a8b422010-07-19 11:34:49 -0700381 code_(kActionCodeError),
adlr@google.com3defe6a2009-12-04 20:57:17 +0000382 should_complete_(true) {}
383 ~ScopedActionCompleter() {
384 if (should_complete_)
Darin Petkovc1a8b422010-07-19 11:34:49 -0700385 processor_->ActionComplete(action_, code_);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000386 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700387 void set_code(ActionExitCode code) { code_ = code; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000388 void set_should_complete(bool should_complete) {
389 should_complete_ = should_complete;
390 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700391
adlr@google.com3defe6a2009-12-04 20:57:17 +0000392 private:
393 ActionProcessor* processor_;
394 AbstractAction* action_;
Darin Petkovc1a8b422010-07-19 11:34:49 -0700395 ActionExitCode code_;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000396 bool should_complete_;
397 DISALLOW_COPY_AND_ASSIGN(ScopedActionCompleter);
398};
399
400} // namespace chromeos_update_engine
401
402#define TEST_AND_RETURN_FALSE_ERRNO(_x) \
403 do { \
404 bool _success = (_x); \
405 if (!_success) { \
406 std::string _msg = \
407 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
408 LOG(ERROR) << #_x " failed: " << _msg; \
409 return false; \
410 } \
411 } while (0)
412
413#define TEST_AND_RETURN_FALSE(_x) \
414 do { \
415 bool _success = (_x); \
416 if (!_success) { \
417 LOG(ERROR) << #_x " failed."; \
418 return false; \
419 } \
420 } while (0)
421
422#define TEST_AND_RETURN_ERRNO(_x) \
423 do { \
424 bool _success = (_x); \
425 if (!_success) { \
426 std::string _msg = \
427 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
428 LOG(ERROR) << #_x " failed: " << _msg; \
429 return; \
430 } \
431 } while (0)
432
433#define TEST_AND_RETURN(_x) \
434 do { \
435 bool _success = (_x); \
436 if (!_success) { \
437 LOG(ERROR) << #_x " failed."; \
438 return; \
439 } \
440 } while (0)
441
Thieu Le5c7d9752010-12-15 16:09:28 -0800442#define TEST_AND_RETURN_FALSE_ERRCODE(_x) \
443 do { \
444 errcode_t _error = (_x); \
445 if (_error) { \
446 errno = _error; \
447 LOG(ERROR) << #_x " failed: " << _error; \
448 return false; \
449 } \
450 } while (0)
451
adlr@google.com3defe6a2009-12-04 20:57:17 +0000452
453
454#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_UTILS_H__