blob: 74711a84e8bb0723b8b7a4c092acf948e6337626 [file] [log] [blame]
Darin Petkov296889c2010-07-23 16:20:54 -07001// Copyright (c) 2010 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
Thieu Le5c7d9752010-12-15 16:09:28 -080015#include <ext2fs/ext2fs.h>
Andrew de los Reyesc7020782010-04-28 10:46:04 -070016#include <glib.h>
Darin Petkovc6c135c2010-08-11 13:36:18 -070017
adlr@google.com3defe6a2009-12-04 20:57:17 +000018#include "update_engine/action.h"
19#include "update_engine/action_processor.h"
20
21namespace chromeos_update_engine {
22
23namespace utils {
24
Darin Petkova07586b2010-10-20 13:41:15 -070025// Returns true if this is an official Chrome OS build, false otherwise.
Darin Petkov33d30642010-08-04 10:18:57 -070026bool IsOfficialBuild();
27
Darin Petkov2a0e6332010-09-24 14:43:41 -070028// Returns true if the OOBE process has been completed and EULA accepted, false
29// otherwise.
30bool IsOOBEComplete();
31
Darin Petkovc91dd6b2011-01-10 12:31:34 -080032// Returns true if the boot mode is normal, false otherwise (e.g., developer or
33// recovery).
34bool IsNormalBootMode();
35
Andrew de los Reyes970bb282009-12-09 16:34:04 -080036// Writes the data passed to path. The file at path will be overwritten if it
37// exists. Returns true on success, false otherwise.
38bool WriteFile(const char* path, const char* data, int data_len);
39
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070040// Calls write() or pwrite() repeatedly until all count bytes at buf are
41// written to fd or an error occurs. Returns true on success.
42bool WriteAll(int fd, const void* buf, size_t count);
43bool PWriteAll(int fd, const void* buf, size_t count, off_t offset);
44
45// Calls pread() repeatedly until count bytes are read, or EOF is reached.
46// Returns number of bytes read in *bytes_read. Returns true on success.
47bool PReadAll(int fd, void* buf, size_t count, off_t offset,
48 ssize_t* out_bytes_read);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070049
adlr@google.com3defe6a2009-12-04 20:57:17 +000050// Returns the entire contents of the file at path. Returns true on success.
51bool ReadFile(const std::string& path, std::vector<char>* out);
52bool ReadFileToString(const std::string& path, std::string* out);
53
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070054// Returns the size of the file at path. If the file doesn't exist or some
55// error occurrs, -1 is returned.
56off_t FileSize(const std::string& path);
57
adlr@google.com3defe6a2009-12-04 20:57:17 +000058std::string ErrnoNumberAsString(int err);
59
60// Strips duplicate slashes, and optionally removes all trailing slashes.
61// Does not compact /./ or /../.
62std::string NormalizePath(const std::string& path, bool strip_trailing_slash);
63
64// Returns true if the file exists for sure. Returns false if it doesn't exist,
65// or an error occurs.
66bool FileExists(const char* path);
67
Darin Petkov30291ed2010-11-12 10:23:06 -080068// Returns true if |path| exists and is a symbolic link.
69bool IsSymlink(const char* path);
70
adlr@google.com3defe6a2009-12-04 20:57:17 +000071// The last 6 chars of path must be XXXXXX. They will be randomly changed
72// and a non-existent path will be returned. Intentionally makes a copy
73// of the string passed in.
74// NEVER CALL THIS FUNCTION UNLESS YOU ARE SURE
75// THAT YOUR PROCESS WILL BE THE ONLY THING WRITING FILES IN THIS DIRECTORY.
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -080076std::string TempFilename(std::string path);
adlr@google.com3defe6a2009-12-04 20:57:17 +000077
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070078// Calls mkstemp() with the template passed. Returns the filename in the
79// out param filename. If fd is non-NULL, the file fd returned by mkstemp
80// is not close()d and is returned in the out param 'fd'. However, if
81// fd is NULL, the fd from mkstemp() will be closed.
82// The last six chars of the template must be XXXXXX.
83// Returns true on success.
84bool MakeTempFile(const std::string& filename_template,
85 std::string* filename,
86 int* fd);
87
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070088// Calls mkdtemp() with the tempate passed. Returns the generated dirname
89// in the dirname param. Returns TRUE on success. dirname must not be NULL.
90bool MakeTempDirectory(const std::string& dirname_template,
91 std::string* dirname);
92
adlr@google.com3defe6a2009-12-04 20:57:17 +000093// Deletes a directory and all its contents synchronously. Returns true
94// on success. This may be called with a regular file--it will just unlink it.
95// This WILL cross filesystem boundaries.
96bool RecursiveUnlinkDir(const std::string& path);
97
Andrew de los Reyesf9714432010-05-04 10:21:23 -070098// Returns the root device for a partition. For example,
Darin Petkovf74eb652010-08-04 12:08:38 -070099// RootDevice("/dev/sda3") returns "/dev/sda". Returns an empty string
100// if the input device is not of the "/dev/xyz" form.
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700101std::string RootDevice(const std::string& partition_device);
102
103// Returns the partition number, as a string, of partition_device. For example,
Darin Petkovf74eb652010-08-04 12:08:38 -0700104// PartitionNumber("/dev/sda3") returns "3".
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700105std::string PartitionNumber(const std::string& partition_device);
106
Darin Petkovf74eb652010-08-04 12:08:38 -0700107// Returns the sysfs block device for a root block device. For
108// example, SysfsBlockDevice("/dev/sda") returns
109// "/sys/block/sda". Returns an empty string if the input device is
110// not of the "/dev/xyz" form.
111std::string SysfsBlockDevice(const std::string& device);
112
113// Returns true if the root |device| (e.g., "/dev/sdb") is known to be
114// removable, false otherwise.
115bool IsRemovableDevice(const std::string& device);
116
adlr@google.com3defe6a2009-12-04 20:57:17 +0000117// Synchronously mount or unmount a filesystem. Return true on success.
118// Mounts as ext3 with default options.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700119bool MountFilesystem(const std::string& device, const std::string& mountpoint,
120 unsigned long flags);
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800121bool UnmountFilesystem(const std::string& mountpoint);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000122
Darin Petkovd3f8c892010-10-12 21:38:45 -0700123// Returns the block count and the block byte size of the ext3 file system on
124// |device| (which may be a real device or a path to a filesystem image) or on
125// an opened file descriptor |fd|. The actual file-system size is |block_count|
126// * |block_size| bytes. Returns true on success, false otherwise.
127bool GetFilesystemSize(const std::string& device,
128 int* out_block_count,
129 int* out_block_size);
130bool GetFilesystemSizeFromFD(int fd,
131 int* out_block_count,
132 int* out_block_size);
133
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700134enum BootLoader {
135 BootLoader_SYSLINUX = 0,
136 BootLoader_CHROME_FIRMWARE = 1
137};
138// Detects which bootloader this system uses and returns it via the out
139// param. Returns true on success.
140bool GetBootloader(BootLoader* out_bootloader);
141
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700142// Returns the error message, if any, from a GError pointer.
143const char* GetGErrorMessage(const GError* error);
144
Darin Petkov296889c2010-07-23 16:20:54 -0700145// Initiates a system reboot. Returns true on success, false otherwise.
146bool Reboot();
147
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800148// Schedules a Main Loop callback to trigger the crash reporter to perform an
149// upload as if this process had crashed.
150void ScheduleCrashReporterUpload();
151
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700152// Fuzzes an integer |value| randomly in the range:
153// [value - range / 2, value + range - range / 2]
154int FuzzInt(int value, unsigned int range);
155
adlr@google.com3defe6a2009-12-04 20:57:17 +0000156// Log a string in hex to LOG(INFO). Useful for debugging.
157void HexDumpArray(const unsigned char* const arr, const size_t length);
158inline void HexDumpString(const std::string& str) {
159 HexDumpArray(reinterpret_cast<const unsigned char*>(str.data()), str.size());
160}
161inline void HexDumpVector(const std::vector<char>& vect) {
162 HexDumpArray(reinterpret_cast<const unsigned char*>(&vect[0]), vect.size());
163}
164
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800165extern const char* const kStatefulPartition;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000166
167bool StringHasSuffix(const std::string& str, const std::string& suffix);
168bool StringHasPrefix(const std::string& str, const std::string& prefix);
169
170template<typename KeyType, typename ValueType>
171bool MapContainsKey(const std::map<KeyType, ValueType>& m, const KeyType& k) {
172 return m.find(k) != m.end();
173}
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800174template<typename KeyType>
175bool SetContainsKey(const std::set<KeyType>& s, const KeyType& k) {
176 return s.find(k) != s.end();
177}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000178
179template<typename ValueType>
180std::set<ValueType> SetWithValue(const ValueType& value) {
181 std::set<ValueType> ret;
182 ret.insert(value);
183 return ret;
184}
185
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800186template<typename T>
187bool VectorContainsValue(const std::vector<T>& vect, const T& value) {
Darin Petkovc1a8b422010-07-19 11:34:49 -0700188 return std::find(vect.begin(), vect.end(), value) != vect.end();
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800189}
190
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700191template<typename T>
192bool VectorIndexOf(const std::vector<T>& vect, const T& value,
193 typename std::vector<T>::size_type* out_index) {
194 typename std::vector<T>::const_iterator it = std::find(vect.begin(),
195 vect.end(),
196 value);
197 if (it == vect.end()) {
198 return false;
199 } else {
200 *out_index = it - vect.begin();
201 return true;
202 }
203}
204
Andrew de los Reyescc92cd32010-10-05 16:56:14 -0700205template<typename ValueType>
206void ApplyMap(std::vector<ValueType>* collection,
207 const std::map<ValueType, ValueType>& the_map) {
208 for (typename std::vector<ValueType>::iterator it = collection->begin();
209 it != collection->end(); ++it) {
210 typename std::map<ValueType, ValueType>::const_iterator map_it =
211 the_map.find(*it);
212 if (map_it != the_map.end()) {
213 *it = map_it->second;
214 }
215 }
216}
217
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700218// Returns the currently booted device. "/dev/sda3", for example.
adlr@google.com3defe6a2009-12-04 20:57:17 +0000219// This will not interpret LABEL= or UUID=. You'll need to use findfs
220// or something with equivalent funcionality to interpret those.
221const std::string BootDevice();
222
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700223// Returns the currently booted kernel device, "dev/sda2", for example.
224// Client must pass in the boot device. The suggested calling convention
225// is: BootKernelDevice(BootDevice()).
226// This function works by doing string modification on boot_device.
227// Returns empty string on failure.
228const std::string BootKernelDevice(const std::string& boot_device);
229
Darin Petkovc6c135c2010-08-11 13:36:18 -0700230enum ProcessPriority {
231 kProcessPriorityHigh = -10,
232 kProcessPriorityNormal = 0,
233 kProcessPriorityLow = 10,
234};
235
236// Compares process priorities and returns an integer that is less
237// than, equal to or greater than 0 if |priority_lhs| is,
238// respectively, lower than, same as or higher than |priority_rhs|.
239int ComparePriorities(ProcessPriority priority_lhs,
240 ProcessPriority priority_rhs);
241
242// Sets the current process priority to |priority|. Returns true on
243// success, false otherwise.
244bool SetProcessPriority(ProcessPriority priority);
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700245
adlr@google.com3defe6a2009-12-04 20:57:17 +0000246} // namespace utils
247
248// Class to unmount FS when object goes out of scope
249class ScopedFilesystemUnmounter {
250 public:
251 explicit ScopedFilesystemUnmounter(const std::string& mountpoint)
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800252 : mountpoint_(mountpoint),
253 should_unmount_(true) {}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000254 ~ScopedFilesystemUnmounter() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800255 if (should_unmount_) {
256 utils::UnmountFilesystem(mountpoint_);
257 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000258 }
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800259 void set_should_unmount(bool unmount) { should_unmount_ = unmount; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000260 private:
261 const std::string mountpoint_;
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800262 bool should_unmount_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700263 DISALLOW_COPY_AND_ASSIGN(ScopedFilesystemUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000264};
265
266// Utility class to close a file descriptor
267class ScopedFdCloser {
268 public:
269 explicit ScopedFdCloser(int* fd) : fd_(fd), should_close_(true) {}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000270 ~ScopedFdCloser() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800271 if (should_close_ && fd_ && (*fd_ >= 0)) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000272 close(*fd_);
273 *fd_ = -1;
274 }
275 }
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800276 void set_should_close(bool should_close) { should_close_ = should_close; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000277 private:
278 int* fd_;
279 bool should_close_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700280 DISALLOW_COPY_AND_ASSIGN(ScopedFdCloser);
281};
282
Thieu Le5c7d9752010-12-15 16:09:28 -0800283// Utility class to close a file system
284class ScopedExt2fsCloser {
285 public:
286 explicit ScopedExt2fsCloser(ext2_filsys filsys) : filsys_(filsys) {}
287 ~ScopedExt2fsCloser() { ext2fs_close(filsys_); }
288
289 private:
290 ext2_filsys filsys_;
291 DISALLOW_COPY_AND_ASSIGN(ScopedExt2fsCloser);
292};
293
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700294// Utility class to delete a file when it goes out of scope.
295class ScopedPathUnlinker {
296 public:
Darin Petkov52dcaeb2011-01-14 15:33:06 -0800297 explicit ScopedPathUnlinker(const std::string& path)
298 : path_(path),
299 should_remove_(true) {}
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700300 ~ScopedPathUnlinker() {
Darin Petkov52dcaeb2011-01-14 15:33:06 -0800301 if (should_remove_ && unlink(path_.c_str()) < 0) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700302 std::string err_message = strerror(errno);
303 LOG(ERROR) << "Unable to unlink path " << path_ << ": " << err_message;
304 }
305 }
Darin Petkov52dcaeb2011-01-14 15:33:06 -0800306 void set_should_remove(bool should_remove) { should_remove_ = should_remove; }
307
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700308 private:
309 const std::string path_;
Darin Petkov52dcaeb2011-01-14 15:33:06 -0800310 bool should_remove_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700311 DISALLOW_COPY_AND_ASSIGN(ScopedPathUnlinker);
312};
313
314// Utility class to delete an empty directory when it goes out of scope.
315class ScopedDirRemover {
316 public:
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800317 explicit ScopedDirRemover(const std::string& path)
318 : path_(path),
319 should_remove_(true) {}
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700320 ~ScopedDirRemover() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800321 if (should_remove_ && (rmdir(path_.c_str()) < 0)) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700322 PLOG(ERROR) << "Unable to remove dir " << path_;
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800323 }
324 }
325 void set_should_remove(bool should_remove) { should_remove_ = should_remove; }
326
327 protected:
328 const std::string path_;
329
330 private:
331 bool should_remove_;
332 DISALLOW_COPY_AND_ASSIGN(ScopedDirRemover);
333};
334
335// Utility class to unmount a filesystem mounted on a temporary directory and
336// delete the temporary directory when it goes out of scope.
337class ScopedTempUnmounter : public ScopedDirRemover {
338 public:
339 explicit ScopedTempUnmounter(const std::string& path) :
340 ScopedDirRemover(path) {}
341 ~ScopedTempUnmounter() {
342 utils::UnmountFilesystem(path_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700343 }
344 private:
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800345 DISALLOW_COPY_AND_ASSIGN(ScopedTempUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000346};
347
348// A little object to call ActionComplete on the ActionProcessor when
349// it's destructed.
350class ScopedActionCompleter {
351 public:
352 explicit ScopedActionCompleter(ActionProcessor* processor,
353 AbstractAction* action)
354 : processor_(processor),
355 action_(action),
Darin Petkovc1a8b422010-07-19 11:34:49 -0700356 code_(kActionCodeError),
adlr@google.com3defe6a2009-12-04 20:57:17 +0000357 should_complete_(true) {}
358 ~ScopedActionCompleter() {
359 if (should_complete_)
Darin Petkovc1a8b422010-07-19 11:34:49 -0700360 processor_->ActionComplete(action_, code_);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000361 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700362 void set_code(ActionExitCode code) { code_ = code; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000363 void set_should_complete(bool should_complete) {
364 should_complete_ = should_complete;
365 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700366
adlr@google.com3defe6a2009-12-04 20:57:17 +0000367 private:
368 ActionProcessor* processor_;
369 AbstractAction* action_;
Darin Petkovc1a8b422010-07-19 11:34:49 -0700370 ActionExitCode code_;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000371 bool should_complete_;
372 DISALLOW_COPY_AND_ASSIGN(ScopedActionCompleter);
373};
374
375} // namespace chromeos_update_engine
376
377#define TEST_AND_RETURN_FALSE_ERRNO(_x) \
378 do { \
379 bool _success = (_x); \
380 if (!_success) { \
381 std::string _msg = \
382 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
383 LOG(ERROR) << #_x " failed: " << _msg; \
384 return false; \
385 } \
386 } while (0)
387
388#define TEST_AND_RETURN_FALSE(_x) \
389 do { \
390 bool _success = (_x); \
391 if (!_success) { \
392 LOG(ERROR) << #_x " failed."; \
393 return false; \
394 } \
395 } while (0)
396
397#define TEST_AND_RETURN_ERRNO(_x) \
398 do { \
399 bool _success = (_x); \
400 if (!_success) { \
401 std::string _msg = \
402 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
403 LOG(ERROR) << #_x " failed: " << _msg; \
404 return; \
405 } \
406 } while (0)
407
408#define TEST_AND_RETURN(_x) \
409 do { \
410 bool _success = (_x); \
411 if (!_success) { \
412 LOG(ERROR) << #_x " failed."; \
413 return; \
414 } \
415 } while (0)
416
Thieu Le5c7d9752010-12-15 16:09:28 -0800417#define TEST_AND_RETURN_FALSE_ERRCODE(_x) \
418 do { \
419 errcode_t _error = (_x); \
420 if (_error) { \
421 errno = _error; \
422 LOG(ERROR) << #_x " failed: " << _error; \
423 return false; \
424 } \
425 } while (0)
426
adlr@google.com3defe6a2009-12-04 20:57:17 +0000427
428
429#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_UTILS_H__