blob: 497963627149758b1e5a1db7b2bf0129f08ac635 [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
Andrew de los Reyes970bb282009-12-09 16:34:04 -080032// Writes the data passed to path. The file at path will be overwritten if it
33// exists. Returns true on success, false otherwise.
34bool WriteFile(const char* path, const char* data, int data_len);
35
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070036// Calls write() or pwrite() repeatedly until all count bytes at buf are
37// written to fd or an error occurs. Returns true on success.
38bool WriteAll(int fd, const void* buf, size_t count);
39bool PWriteAll(int fd, const void* buf, size_t count, off_t offset);
40
41// Calls pread() repeatedly until count bytes are read, or EOF is reached.
42// Returns number of bytes read in *bytes_read. Returns true on success.
43bool PReadAll(int fd, void* buf, size_t count, off_t offset,
44 ssize_t* out_bytes_read);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070045
adlr@google.com3defe6a2009-12-04 20:57:17 +000046// Returns the entire contents of the file at path. Returns true on success.
47bool ReadFile(const std::string& path, std::vector<char>* out);
48bool ReadFileToString(const std::string& path, std::string* out);
49
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070050// Returns the size of the file at path. If the file doesn't exist or some
51// error occurrs, -1 is returned.
52off_t FileSize(const std::string& path);
53
adlr@google.com3defe6a2009-12-04 20:57:17 +000054std::string ErrnoNumberAsString(int err);
55
56// Strips duplicate slashes, and optionally removes all trailing slashes.
57// Does not compact /./ or /../.
58std::string NormalizePath(const std::string& path, bool strip_trailing_slash);
59
60// Returns true if the file exists for sure. Returns false if it doesn't exist,
61// or an error occurs.
62bool FileExists(const char* path);
63
Darin Petkov30291ed2010-11-12 10:23:06 -080064// Returns true if |path| exists and is a symbolic link.
65bool IsSymlink(const char* path);
66
adlr@google.com3defe6a2009-12-04 20:57:17 +000067// The last 6 chars of path must be XXXXXX. They will be randomly changed
68// and a non-existent path will be returned. Intentionally makes a copy
69// of the string passed in.
70// NEVER CALL THIS FUNCTION UNLESS YOU ARE SURE
71// THAT YOUR PROCESS WILL BE THE ONLY THING WRITING FILES IN THIS DIRECTORY.
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -080072std::string TempFilename(std::string path);
adlr@google.com3defe6a2009-12-04 20:57:17 +000073
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070074// Calls mkstemp() with the template passed. Returns the filename in the
75// out param filename. If fd is non-NULL, the file fd returned by mkstemp
76// is not close()d and is returned in the out param 'fd'. However, if
77// fd is NULL, the fd from mkstemp() will be closed.
78// The last six chars of the template must be XXXXXX.
79// Returns true on success.
80bool MakeTempFile(const std::string& filename_template,
81 std::string* filename,
82 int* fd);
83
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070084// Calls mkdtemp() with the tempate passed. Returns the generated dirname
85// in the dirname param. Returns TRUE on success. dirname must not be NULL.
86bool MakeTempDirectory(const std::string& dirname_template,
87 std::string* dirname);
88
adlr@google.com3defe6a2009-12-04 20:57:17 +000089// Deletes a directory and all its contents synchronously. Returns true
90// on success. This may be called with a regular file--it will just unlink it.
91// This WILL cross filesystem boundaries.
92bool RecursiveUnlinkDir(const std::string& path);
93
Andrew de los Reyesf9714432010-05-04 10:21:23 -070094// Returns the root device for a partition. For example,
Darin Petkovf74eb652010-08-04 12:08:38 -070095// RootDevice("/dev/sda3") returns "/dev/sda". Returns an empty string
96// if the input device is not of the "/dev/xyz" form.
Andrew de los Reyesf9714432010-05-04 10:21:23 -070097std::string RootDevice(const std::string& partition_device);
98
99// Returns the partition number, as a string, of partition_device. For example,
Darin Petkovf74eb652010-08-04 12:08:38 -0700100// PartitionNumber("/dev/sda3") returns "3".
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700101std::string PartitionNumber(const std::string& partition_device);
102
Darin Petkovf74eb652010-08-04 12:08:38 -0700103// Returns the sysfs block device for a root block device. For
104// example, SysfsBlockDevice("/dev/sda") returns
105// "/sys/block/sda". Returns an empty string if the input device is
106// not of the "/dev/xyz" form.
107std::string SysfsBlockDevice(const std::string& device);
108
109// Returns true if the root |device| (e.g., "/dev/sdb") is known to be
110// removable, false otherwise.
111bool IsRemovableDevice(const std::string& device);
112
adlr@google.com3defe6a2009-12-04 20:57:17 +0000113// Synchronously mount or unmount a filesystem. Return true on success.
114// Mounts as ext3 with default options.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700115bool MountFilesystem(const std::string& device, const std::string& mountpoint,
116 unsigned long flags);
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800117bool UnmountFilesystem(const std::string& mountpoint);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000118
Darin Petkovd3f8c892010-10-12 21:38:45 -0700119// Returns the block count and the block byte size of the ext3 file system on
120// |device| (which may be a real device or a path to a filesystem image) or on
121// an opened file descriptor |fd|. The actual file-system size is |block_count|
122// * |block_size| bytes. Returns true on success, false otherwise.
123bool GetFilesystemSize(const std::string& device,
124 int* out_block_count,
125 int* out_block_size);
126bool GetFilesystemSizeFromFD(int fd,
127 int* out_block_count,
128 int* out_block_size);
129
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700130enum BootLoader {
131 BootLoader_SYSLINUX = 0,
132 BootLoader_CHROME_FIRMWARE = 1
133};
134// Detects which bootloader this system uses and returns it via the out
135// param. Returns true on success.
136bool GetBootloader(BootLoader* out_bootloader);
137
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700138// Returns the error message, if any, from a GError pointer.
139const char* GetGErrorMessage(const GError* error);
140
Darin Petkov296889c2010-07-23 16:20:54 -0700141// Initiates a system reboot. Returns true on success, false otherwise.
142bool Reboot();
143
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700144// Fuzzes an integer |value| randomly in the range:
145// [value - range / 2, value + range - range / 2]
146int FuzzInt(int value, unsigned int range);
147
adlr@google.com3defe6a2009-12-04 20:57:17 +0000148// Log a string in hex to LOG(INFO). Useful for debugging.
149void HexDumpArray(const unsigned char* const arr, const size_t length);
150inline void HexDumpString(const std::string& str) {
151 HexDumpArray(reinterpret_cast<const unsigned char*>(str.data()), str.size());
152}
153inline void HexDumpVector(const std::vector<char>& vect) {
154 HexDumpArray(reinterpret_cast<const unsigned char*>(&vect[0]), vect.size());
155}
156
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800157extern const char* const kStatefulPartition;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000158
159bool StringHasSuffix(const std::string& str, const std::string& suffix);
160bool StringHasPrefix(const std::string& str, const std::string& prefix);
161
162template<typename KeyType, typename ValueType>
163bool MapContainsKey(const std::map<KeyType, ValueType>& m, const KeyType& k) {
164 return m.find(k) != m.end();
165}
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800166template<typename KeyType>
167bool SetContainsKey(const std::set<KeyType>& s, const KeyType& k) {
168 return s.find(k) != s.end();
169}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000170
171template<typename ValueType>
172std::set<ValueType> SetWithValue(const ValueType& value) {
173 std::set<ValueType> ret;
174 ret.insert(value);
175 return ret;
176}
177
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800178template<typename T>
179bool VectorContainsValue(const std::vector<T>& vect, const T& value) {
Darin Petkovc1a8b422010-07-19 11:34:49 -0700180 return std::find(vect.begin(), vect.end(), value) != vect.end();
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800181}
182
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700183template<typename T>
184bool VectorIndexOf(const std::vector<T>& vect, const T& value,
185 typename std::vector<T>::size_type* out_index) {
186 typename std::vector<T>::const_iterator it = std::find(vect.begin(),
187 vect.end(),
188 value);
189 if (it == vect.end()) {
190 return false;
191 } else {
192 *out_index = it - vect.begin();
193 return true;
194 }
195}
196
Andrew de los Reyescc92cd32010-10-05 16:56:14 -0700197template<typename ValueType>
198void ApplyMap(std::vector<ValueType>* collection,
199 const std::map<ValueType, ValueType>& the_map) {
200 for (typename std::vector<ValueType>::iterator it = collection->begin();
201 it != collection->end(); ++it) {
202 typename std::map<ValueType, ValueType>::const_iterator map_it =
203 the_map.find(*it);
204 if (map_it != the_map.end()) {
205 *it = map_it->second;
206 }
207 }
208}
209
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700210// Returns the currently booted device. "/dev/sda3", for example.
adlr@google.com3defe6a2009-12-04 20:57:17 +0000211// This will not interpret LABEL= or UUID=. You'll need to use findfs
212// or something with equivalent funcionality to interpret those.
213const std::string BootDevice();
214
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700215// Returns the currently booted kernel device, "dev/sda2", for example.
216// Client must pass in the boot device. The suggested calling convention
217// is: BootKernelDevice(BootDevice()).
218// This function works by doing string modification on boot_device.
219// Returns empty string on failure.
220const std::string BootKernelDevice(const std::string& boot_device);
221
Darin Petkovc6c135c2010-08-11 13:36:18 -0700222enum ProcessPriority {
223 kProcessPriorityHigh = -10,
224 kProcessPriorityNormal = 0,
225 kProcessPriorityLow = 10,
226};
227
228// Compares process priorities and returns an integer that is less
229// than, equal to or greater than 0 if |priority_lhs| is,
230// respectively, lower than, same as or higher than |priority_rhs|.
231int ComparePriorities(ProcessPriority priority_lhs,
232 ProcessPriority priority_rhs);
233
234// Sets the current process priority to |priority|. Returns true on
235// success, false otherwise.
236bool SetProcessPriority(ProcessPriority priority);
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700237
adlr@google.com3defe6a2009-12-04 20:57:17 +0000238} // namespace utils
239
240// Class to unmount FS when object goes out of scope
241class ScopedFilesystemUnmounter {
242 public:
243 explicit ScopedFilesystemUnmounter(const std::string& mountpoint)
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800244 : mountpoint_(mountpoint),
245 should_unmount_(true) {}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000246 ~ScopedFilesystemUnmounter() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800247 if (should_unmount_) {
248 utils::UnmountFilesystem(mountpoint_);
249 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000250 }
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800251 void set_should_unmount(bool unmount) { should_unmount_ = unmount; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000252 private:
253 const std::string mountpoint_;
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800254 bool should_unmount_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700255 DISALLOW_COPY_AND_ASSIGN(ScopedFilesystemUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000256};
257
258// Utility class to close a file descriptor
259class ScopedFdCloser {
260 public:
261 explicit ScopedFdCloser(int* fd) : fd_(fd), should_close_(true) {}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000262 ~ScopedFdCloser() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800263 if (should_close_ && fd_ && (*fd_ >= 0)) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000264 close(*fd_);
265 *fd_ = -1;
266 }
267 }
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800268 void set_should_close(bool should_close) { should_close_ = should_close; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000269 private:
270 int* fd_;
271 bool should_close_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700272 DISALLOW_COPY_AND_ASSIGN(ScopedFdCloser);
273};
274
Thieu Le5c7d9752010-12-15 16:09:28 -0800275// Utility class to close a file system
276class ScopedExt2fsCloser {
277 public:
278 explicit ScopedExt2fsCloser(ext2_filsys filsys) : filsys_(filsys) {}
279 ~ScopedExt2fsCloser() { ext2fs_close(filsys_); }
280
281 private:
282 ext2_filsys filsys_;
283 DISALLOW_COPY_AND_ASSIGN(ScopedExt2fsCloser);
284};
285
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700286// Utility class to delete a file when it goes out of scope.
287class ScopedPathUnlinker {
288 public:
289 explicit ScopedPathUnlinker(const std::string& path) : path_(path) {}
290 ~ScopedPathUnlinker() {
291 if (unlink(path_.c_str()) < 0) {
292 std::string err_message = strerror(errno);
293 LOG(ERROR) << "Unable to unlink path " << path_ << ": " << err_message;
294 }
295 }
296 private:
297 const std::string path_;
298 DISALLOW_COPY_AND_ASSIGN(ScopedPathUnlinker);
299};
300
301// Utility class to delete an empty directory when it goes out of scope.
302class ScopedDirRemover {
303 public:
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800304 explicit ScopedDirRemover(const std::string& path)
305 : path_(path),
306 should_remove_(true) {}
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700307 ~ScopedDirRemover() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800308 if (should_remove_ && (rmdir(path_.c_str()) < 0)) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700309 PLOG(ERROR) << "Unable to remove dir " << path_;
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800310 }
311 }
312 void set_should_remove(bool should_remove) { should_remove_ = should_remove; }
313
314 protected:
315 const std::string path_;
316
317 private:
318 bool should_remove_;
319 DISALLOW_COPY_AND_ASSIGN(ScopedDirRemover);
320};
321
322// Utility class to unmount a filesystem mounted on a temporary directory and
323// delete the temporary directory when it goes out of scope.
324class ScopedTempUnmounter : public ScopedDirRemover {
325 public:
326 explicit ScopedTempUnmounter(const std::string& path) :
327 ScopedDirRemover(path) {}
328 ~ScopedTempUnmounter() {
329 utils::UnmountFilesystem(path_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700330 }
331 private:
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800332 DISALLOW_COPY_AND_ASSIGN(ScopedTempUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000333};
334
335// A little object to call ActionComplete on the ActionProcessor when
336// it's destructed.
337class ScopedActionCompleter {
338 public:
339 explicit ScopedActionCompleter(ActionProcessor* processor,
340 AbstractAction* action)
341 : processor_(processor),
342 action_(action),
Darin Petkovc1a8b422010-07-19 11:34:49 -0700343 code_(kActionCodeError),
adlr@google.com3defe6a2009-12-04 20:57:17 +0000344 should_complete_(true) {}
345 ~ScopedActionCompleter() {
346 if (should_complete_)
Darin Petkovc1a8b422010-07-19 11:34:49 -0700347 processor_->ActionComplete(action_, code_);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000348 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700349 void set_code(ActionExitCode code) { code_ = code; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000350 void set_should_complete(bool should_complete) {
351 should_complete_ = should_complete;
352 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700353
adlr@google.com3defe6a2009-12-04 20:57:17 +0000354 private:
355 ActionProcessor* processor_;
356 AbstractAction* action_;
Darin Petkovc1a8b422010-07-19 11:34:49 -0700357 ActionExitCode code_;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000358 bool should_complete_;
359 DISALLOW_COPY_AND_ASSIGN(ScopedActionCompleter);
360};
361
362} // namespace chromeos_update_engine
363
364#define TEST_AND_RETURN_FALSE_ERRNO(_x) \
365 do { \
366 bool _success = (_x); \
367 if (!_success) { \
368 std::string _msg = \
369 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
370 LOG(ERROR) << #_x " failed: " << _msg; \
371 return false; \
372 } \
373 } while (0)
374
375#define TEST_AND_RETURN_FALSE(_x) \
376 do { \
377 bool _success = (_x); \
378 if (!_success) { \
379 LOG(ERROR) << #_x " failed."; \
380 return false; \
381 } \
382 } while (0)
383
384#define TEST_AND_RETURN_ERRNO(_x) \
385 do { \
386 bool _success = (_x); \
387 if (!_success) { \
388 std::string _msg = \
389 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
390 LOG(ERROR) << #_x " failed: " << _msg; \
391 return; \
392 } \
393 } while (0)
394
395#define TEST_AND_RETURN(_x) \
396 do { \
397 bool _success = (_x); \
398 if (!_success) { \
399 LOG(ERROR) << #_x " failed."; \
400 return; \
401 } \
402 } while (0)
403
Thieu Le5c7d9752010-12-15 16:09:28 -0800404#define TEST_AND_RETURN_FALSE_ERRCODE(_x) \
405 do { \
406 errcode_t _error = (_x); \
407 if (_error) { \
408 errno = _error; \
409 LOG(ERROR) << #_x " failed: " << _error; \
410 return false; \
411 } \
412 } while (0)
413
adlr@google.com3defe6a2009-12-04 20:57:17 +0000414
415
416#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_UTILS_H__