blob: fb30055b5f08501862c887f9f93253cf2de3df98 [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 Petkov44d98d92011-03-21 16:08:11 -070032// Returns true if the boot mode is normal or if it's unable to determine the
33// boot mode. Returns false if the boot mode is developer.
Darin Petkovc91dd6b2011-01-10 12:31:34 -080034bool 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
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800246// Assumes data points to a Closure. Runs it and returns FALSE;
247gboolean GlibRunClosure(gpointer data);
248
adlr@google.com3defe6a2009-12-04 20:57:17 +0000249} // namespace utils
250
251// Class to unmount FS when object goes out of scope
252class ScopedFilesystemUnmounter {
253 public:
254 explicit ScopedFilesystemUnmounter(const std::string& mountpoint)
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800255 : mountpoint_(mountpoint),
256 should_unmount_(true) {}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000257 ~ScopedFilesystemUnmounter() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800258 if (should_unmount_) {
259 utils::UnmountFilesystem(mountpoint_);
260 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000261 }
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800262 void set_should_unmount(bool unmount) { should_unmount_ = unmount; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000263 private:
264 const std::string mountpoint_;
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800265 bool should_unmount_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700266 DISALLOW_COPY_AND_ASSIGN(ScopedFilesystemUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000267};
268
269// Utility class to close a file descriptor
270class ScopedFdCloser {
271 public:
272 explicit ScopedFdCloser(int* fd) : fd_(fd), should_close_(true) {}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000273 ~ScopedFdCloser() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800274 if (should_close_ && fd_ && (*fd_ >= 0)) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000275 close(*fd_);
276 *fd_ = -1;
277 }
278 }
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800279 void set_should_close(bool should_close) { should_close_ = should_close; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000280 private:
281 int* fd_;
282 bool should_close_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700283 DISALLOW_COPY_AND_ASSIGN(ScopedFdCloser);
284};
285
Thieu Le5c7d9752010-12-15 16:09:28 -0800286// Utility class to close a file system
287class ScopedExt2fsCloser {
288 public:
289 explicit ScopedExt2fsCloser(ext2_filsys filsys) : filsys_(filsys) {}
290 ~ScopedExt2fsCloser() { ext2fs_close(filsys_); }
291
292 private:
293 ext2_filsys filsys_;
294 DISALLOW_COPY_AND_ASSIGN(ScopedExt2fsCloser);
295};
296
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700297// Utility class to delete a file when it goes out of scope.
298class ScopedPathUnlinker {
299 public:
Darin Petkov52dcaeb2011-01-14 15:33:06 -0800300 explicit ScopedPathUnlinker(const std::string& path)
301 : path_(path),
302 should_remove_(true) {}
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700303 ~ScopedPathUnlinker() {
Darin Petkov52dcaeb2011-01-14 15:33:06 -0800304 if (should_remove_ && unlink(path_.c_str()) < 0) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700305 std::string err_message = strerror(errno);
306 LOG(ERROR) << "Unable to unlink path " << path_ << ": " << err_message;
307 }
308 }
Darin Petkov52dcaeb2011-01-14 15:33:06 -0800309 void set_should_remove(bool should_remove) { should_remove_ = should_remove; }
310
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700311 private:
312 const std::string path_;
Darin Petkov52dcaeb2011-01-14 15:33:06 -0800313 bool should_remove_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700314 DISALLOW_COPY_AND_ASSIGN(ScopedPathUnlinker);
315};
316
317// Utility class to delete an empty directory when it goes out of scope.
318class ScopedDirRemover {
319 public:
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800320 explicit ScopedDirRemover(const std::string& path)
321 : path_(path),
322 should_remove_(true) {}
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700323 ~ScopedDirRemover() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800324 if (should_remove_ && (rmdir(path_.c_str()) < 0)) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700325 PLOG(ERROR) << "Unable to remove dir " << path_;
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800326 }
327 }
328 void set_should_remove(bool should_remove) { should_remove_ = should_remove; }
329
330 protected:
331 const std::string path_;
332
333 private:
334 bool should_remove_;
335 DISALLOW_COPY_AND_ASSIGN(ScopedDirRemover);
336};
337
338// Utility class to unmount a filesystem mounted on a temporary directory and
339// delete the temporary directory when it goes out of scope.
340class ScopedTempUnmounter : public ScopedDirRemover {
341 public:
342 explicit ScopedTempUnmounter(const std::string& path) :
343 ScopedDirRemover(path) {}
344 ~ScopedTempUnmounter() {
345 utils::UnmountFilesystem(path_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700346 }
347 private:
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800348 DISALLOW_COPY_AND_ASSIGN(ScopedTempUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000349};
350
351// A little object to call ActionComplete on the ActionProcessor when
352// it's destructed.
353class ScopedActionCompleter {
354 public:
355 explicit ScopedActionCompleter(ActionProcessor* processor,
356 AbstractAction* action)
357 : processor_(processor),
358 action_(action),
Darin Petkovc1a8b422010-07-19 11:34:49 -0700359 code_(kActionCodeError),
adlr@google.com3defe6a2009-12-04 20:57:17 +0000360 should_complete_(true) {}
361 ~ScopedActionCompleter() {
362 if (should_complete_)
Darin Petkovc1a8b422010-07-19 11:34:49 -0700363 processor_->ActionComplete(action_, code_);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000364 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700365 void set_code(ActionExitCode code) { code_ = code; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000366 void set_should_complete(bool should_complete) {
367 should_complete_ = should_complete;
368 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700369
adlr@google.com3defe6a2009-12-04 20:57:17 +0000370 private:
371 ActionProcessor* processor_;
372 AbstractAction* action_;
Darin Petkovc1a8b422010-07-19 11:34:49 -0700373 ActionExitCode code_;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000374 bool should_complete_;
375 DISALLOW_COPY_AND_ASSIGN(ScopedActionCompleter);
376};
377
378} // namespace chromeos_update_engine
379
380#define TEST_AND_RETURN_FALSE_ERRNO(_x) \
381 do { \
382 bool _success = (_x); \
383 if (!_success) { \
384 std::string _msg = \
385 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
386 LOG(ERROR) << #_x " failed: " << _msg; \
387 return false; \
388 } \
389 } while (0)
390
391#define TEST_AND_RETURN_FALSE(_x) \
392 do { \
393 bool _success = (_x); \
394 if (!_success) { \
395 LOG(ERROR) << #_x " failed."; \
396 return false; \
397 } \
398 } while (0)
399
400#define TEST_AND_RETURN_ERRNO(_x) \
401 do { \
402 bool _success = (_x); \
403 if (!_success) { \
404 std::string _msg = \
405 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
406 LOG(ERROR) << #_x " failed: " << _msg; \
407 return; \
408 } \
409 } while (0)
410
411#define TEST_AND_RETURN(_x) \
412 do { \
413 bool _success = (_x); \
414 if (!_success) { \
415 LOG(ERROR) << #_x " failed."; \
416 return; \
417 } \
418 } while (0)
419
Thieu Le5c7d9752010-12-15 16:09:28 -0800420#define TEST_AND_RETURN_FALSE_ERRCODE(_x) \
421 do { \
422 errcode_t _error = (_x); \
423 if (_error) { \
424 errno = _error; \
425 LOG(ERROR) << #_x " failed: " << _error; \
426 return false; \
427 } \
428 } while (0)
429
adlr@google.com3defe6a2009-12-04 20:57:17 +0000430
431
432#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_UTILS_H__