blob: b0b28a8bbf3efea7c08a4df21ccc8abbc51bdc19 [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
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
Darin Petkovf2065b42011-05-17 16:36:27 -070036// Returns the HWID or an empty string on error.
37std::string GetHardwareClass();
38
Andrew de los Reyes970bb282009-12-09 16:34:04 -080039// Writes the data passed to path. The file at path will be overwritten if it
40// exists. Returns true on success, false otherwise.
41bool WriteFile(const char* path, const char* data, int data_len);
42
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070043// Calls write() or pwrite() repeatedly until all count bytes at buf are
44// written to fd or an error occurs. Returns true on success.
45bool WriteAll(int fd, const void* buf, size_t count);
46bool PWriteAll(int fd, const void* buf, size_t count, off_t offset);
47
48// Calls pread() repeatedly until count bytes are read, or EOF is reached.
49// Returns number of bytes read in *bytes_read. Returns true on success.
50bool PReadAll(int fd, void* buf, size_t count, off_t offset,
51 ssize_t* out_bytes_read);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070052
adlr@google.com3defe6a2009-12-04 20:57:17 +000053// Returns the entire contents of the file at path. Returns true on success.
54bool ReadFile(const std::string& path, std::vector<char>* out);
55bool ReadFileToString(const std::string& path, std::string* out);
56
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070057// Returns the size of the file at path. If the file doesn't exist or some
58// error occurrs, -1 is returned.
59off_t FileSize(const std::string& path);
60
adlr@google.com3defe6a2009-12-04 20:57:17 +000061std::string ErrnoNumberAsString(int err);
62
63// Strips duplicate slashes, and optionally removes all trailing slashes.
64// Does not compact /./ or /../.
65std::string NormalizePath(const std::string& path, bool strip_trailing_slash);
66
67// Returns true if the file exists for sure. Returns false if it doesn't exist,
68// or an error occurs.
69bool FileExists(const char* path);
70
Darin Petkov30291ed2010-11-12 10:23:06 -080071// Returns true if |path| exists and is a symbolic link.
72bool IsSymlink(const char* path);
73
adlr@google.com3defe6a2009-12-04 20:57:17 +000074// The last 6 chars of path must be XXXXXX. They will be randomly changed
75// and a non-existent path will be returned. Intentionally makes a copy
76// of the string passed in.
77// NEVER CALL THIS FUNCTION UNLESS YOU ARE SURE
78// THAT YOUR PROCESS WILL BE THE ONLY THING WRITING FILES IN THIS DIRECTORY.
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -080079std::string TempFilename(std::string path);
adlr@google.com3defe6a2009-12-04 20:57:17 +000080
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070081// Calls mkstemp() with the template passed. Returns the filename in the
82// out param filename. If fd is non-NULL, the file fd returned by mkstemp
83// is not close()d and is returned in the out param 'fd'. However, if
84// fd is NULL, the fd from mkstemp() will be closed.
85// The last six chars of the template must be XXXXXX.
86// Returns true on success.
87bool MakeTempFile(const std::string& filename_template,
88 std::string* filename,
89 int* fd);
90
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070091// Calls mkdtemp() with the tempate passed. Returns the generated dirname
92// in the dirname param. Returns TRUE on success. dirname must not be NULL.
93bool MakeTempDirectory(const std::string& dirname_template,
94 std::string* dirname);
95
adlr@google.com3defe6a2009-12-04 20:57:17 +000096// Deletes a directory and all its contents synchronously. Returns true
97// on success. This may be called with a regular file--it will just unlink it.
98// This WILL cross filesystem boundaries.
99bool RecursiveUnlinkDir(const std::string& path);
100
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700101// Returns the root device for a partition. For example,
Darin Petkovf74eb652010-08-04 12:08:38 -0700102// RootDevice("/dev/sda3") returns "/dev/sda". Returns an empty string
103// if the input device is not of the "/dev/xyz" form.
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700104std::string RootDevice(const std::string& partition_device);
105
106// Returns the partition number, as a string, of partition_device. For example,
Darin Petkovf74eb652010-08-04 12:08:38 -0700107// PartitionNumber("/dev/sda3") returns "3".
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700108std::string PartitionNumber(const std::string& partition_device);
109
Darin Petkovf74eb652010-08-04 12:08:38 -0700110// Returns the sysfs block device for a root block device. For
111// example, SysfsBlockDevice("/dev/sda") returns
112// "/sys/block/sda". Returns an empty string if the input device is
113// not of the "/dev/xyz" form.
114std::string SysfsBlockDevice(const std::string& device);
115
116// Returns true if the root |device| (e.g., "/dev/sdb") is known to be
117// removable, false otherwise.
118bool IsRemovableDevice(const std::string& device);
119
adlr@google.com3defe6a2009-12-04 20:57:17 +0000120// Synchronously mount or unmount a filesystem. Return true on success.
121// Mounts as ext3 with default options.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700122bool MountFilesystem(const std::string& device, const std::string& mountpoint,
123 unsigned long flags);
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800124bool UnmountFilesystem(const std::string& mountpoint);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000125
Darin Petkovd3f8c892010-10-12 21:38:45 -0700126// Returns the block count and the block byte size of the ext3 file system on
127// |device| (which may be a real device or a path to a filesystem image) or on
128// an opened file descriptor |fd|. The actual file-system size is |block_count|
129// * |block_size| bytes. Returns true on success, false otherwise.
130bool GetFilesystemSize(const std::string& device,
131 int* out_block_count,
132 int* out_block_size);
133bool GetFilesystemSizeFromFD(int fd,
134 int* out_block_count,
135 int* out_block_size);
136
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700137enum BootLoader {
138 BootLoader_SYSLINUX = 0,
139 BootLoader_CHROME_FIRMWARE = 1
140};
141// Detects which bootloader this system uses and returns it via the out
142// param. Returns true on success.
143bool GetBootloader(BootLoader* out_bootloader);
144
Darin Petkova0b9e772011-10-06 05:05:56 -0700145// Returns the error message, if any, from a GError pointer. Frees the GError
146// object and resets error to NULL.
147std::string GetAndFreeGError(GError** error);
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700148
Darin Petkov296889c2010-07-23 16:20:54 -0700149// Initiates a system reboot. Returns true on success, false otherwise.
150bool Reboot();
151
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800152// Schedules a Main Loop callback to trigger the crash reporter to perform an
153// upload as if this process had crashed.
154void ScheduleCrashReporterUpload();
155
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700156// Fuzzes an integer |value| randomly in the range:
157// [value - range / 2, value + range - range / 2]
158int FuzzInt(int value, unsigned int range);
159
adlr@google.com3defe6a2009-12-04 20:57:17 +0000160// Log a string in hex to LOG(INFO). Useful for debugging.
161void HexDumpArray(const unsigned char* const arr, const size_t length);
162inline void HexDumpString(const std::string& str) {
163 HexDumpArray(reinterpret_cast<const unsigned char*>(str.data()), str.size());
164}
165inline void HexDumpVector(const std::vector<char>& vect) {
166 HexDumpArray(reinterpret_cast<const unsigned char*>(&vect[0]), vect.size());
167}
168
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800169extern const char* const kStatefulPartition;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000170
171bool StringHasSuffix(const std::string& str, const std::string& suffix);
172bool StringHasPrefix(const std::string& str, const std::string& prefix);
173
174template<typename KeyType, typename ValueType>
175bool MapContainsKey(const std::map<KeyType, ValueType>& m, const KeyType& k) {
176 return m.find(k) != m.end();
177}
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800178template<typename KeyType>
179bool SetContainsKey(const std::set<KeyType>& s, const KeyType& k) {
180 return s.find(k) != s.end();
181}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000182
183template<typename ValueType>
184std::set<ValueType> SetWithValue(const ValueType& value) {
185 std::set<ValueType> ret;
186 ret.insert(value);
187 return ret;
188}
189
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800190template<typename T>
191bool VectorContainsValue(const std::vector<T>& vect, const T& value) {
Darin Petkovc1a8b422010-07-19 11:34:49 -0700192 return std::find(vect.begin(), vect.end(), value) != vect.end();
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800193}
194
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700195template<typename T>
196bool VectorIndexOf(const std::vector<T>& vect, const T& value,
197 typename std::vector<T>::size_type* out_index) {
198 typename std::vector<T>::const_iterator it = std::find(vect.begin(),
199 vect.end(),
200 value);
201 if (it == vect.end()) {
202 return false;
203 } else {
204 *out_index = it - vect.begin();
205 return true;
206 }
207}
208
Andrew de los Reyescc92cd32010-10-05 16:56:14 -0700209template<typename ValueType>
210void ApplyMap(std::vector<ValueType>* collection,
211 const std::map<ValueType, ValueType>& the_map) {
212 for (typename std::vector<ValueType>::iterator it = collection->begin();
213 it != collection->end(); ++it) {
214 typename std::map<ValueType, ValueType>::const_iterator map_it =
215 the_map.find(*it);
216 if (map_it != the_map.end()) {
217 *it = map_it->second;
218 }
219 }
220}
221
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700222// Returns the currently booted device. "/dev/sda3", for example.
adlr@google.com3defe6a2009-12-04 20:57:17 +0000223// This will not interpret LABEL= or UUID=. You'll need to use findfs
224// or something with equivalent funcionality to interpret those.
225const std::string BootDevice();
226
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700227// Returns the currently booted kernel device, "dev/sda2", for example.
228// Client must pass in the boot device. The suggested calling convention
229// is: BootKernelDevice(BootDevice()).
230// This function works by doing string modification on boot_device.
231// Returns empty string on failure.
232const std::string BootKernelDevice(const std::string& boot_device);
233
Darin Petkovc6c135c2010-08-11 13:36:18 -0700234enum ProcessPriority {
235 kProcessPriorityHigh = -10,
236 kProcessPriorityNormal = 0,
237 kProcessPriorityLow = 10,
238};
239
240// Compares process priorities and returns an integer that is less
241// than, equal to or greater than 0 if |priority_lhs| is,
242// respectively, lower than, same as or higher than |priority_rhs|.
243int ComparePriorities(ProcessPriority priority_lhs,
244 ProcessPriority priority_rhs);
245
246// Sets the current process priority to |priority|. Returns true on
247// success, false otherwise.
248bool SetProcessPriority(ProcessPriority priority);
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700249
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800250// Assumes data points to a Closure. Runs it and returns FALSE;
251gboolean GlibRunClosure(gpointer data);
252
adlr@google.com3defe6a2009-12-04 20:57:17 +0000253} // namespace utils
254
255// Class to unmount FS when object goes out of scope
256class ScopedFilesystemUnmounter {
257 public:
258 explicit ScopedFilesystemUnmounter(const std::string& mountpoint)
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800259 : mountpoint_(mountpoint),
260 should_unmount_(true) {}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000261 ~ScopedFilesystemUnmounter() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800262 if (should_unmount_) {
263 utils::UnmountFilesystem(mountpoint_);
264 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000265 }
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800266 void set_should_unmount(bool unmount) { should_unmount_ = unmount; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000267 private:
268 const std::string mountpoint_;
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800269 bool should_unmount_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700270 DISALLOW_COPY_AND_ASSIGN(ScopedFilesystemUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000271};
272
273// Utility class to close a file descriptor
274class ScopedFdCloser {
275 public:
276 explicit ScopedFdCloser(int* fd) : fd_(fd), should_close_(true) {}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000277 ~ScopedFdCloser() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800278 if (should_close_ && fd_ && (*fd_ >= 0)) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000279 close(*fd_);
280 *fd_ = -1;
281 }
282 }
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800283 void set_should_close(bool should_close) { should_close_ = should_close; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000284 private:
285 int* fd_;
286 bool should_close_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700287 DISALLOW_COPY_AND_ASSIGN(ScopedFdCloser);
288};
289
Thieu Le5c7d9752010-12-15 16:09:28 -0800290// Utility class to close a file system
291class ScopedExt2fsCloser {
292 public:
293 explicit ScopedExt2fsCloser(ext2_filsys filsys) : filsys_(filsys) {}
294 ~ScopedExt2fsCloser() { ext2fs_close(filsys_); }
295
296 private:
297 ext2_filsys filsys_;
298 DISALLOW_COPY_AND_ASSIGN(ScopedExt2fsCloser);
299};
300
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700301// Utility class to delete a file when it goes out of scope.
302class ScopedPathUnlinker {
303 public:
Darin Petkov52dcaeb2011-01-14 15:33:06 -0800304 explicit ScopedPathUnlinker(const std::string& path)
305 : path_(path),
306 should_remove_(true) {}
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700307 ~ScopedPathUnlinker() {
Darin Petkov52dcaeb2011-01-14 15:33:06 -0800308 if (should_remove_ && unlink(path_.c_str()) < 0) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700309 std::string err_message = strerror(errno);
310 LOG(ERROR) << "Unable to unlink path " << path_ << ": " << err_message;
311 }
312 }
Darin Petkov52dcaeb2011-01-14 15:33:06 -0800313 void set_should_remove(bool should_remove) { should_remove_ = should_remove; }
314
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700315 private:
316 const std::string path_;
Darin Petkov52dcaeb2011-01-14 15:33:06 -0800317 bool should_remove_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700318 DISALLOW_COPY_AND_ASSIGN(ScopedPathUnlinker);
319};
320
321// Utility class to delete an empty directory when it goes out of scope.
322class ScopedDirRemover {
323 public:
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800324 explicit ScopedDirRemover(const std::string& path)
325 : path_(path),
326 should_remove_(true) {}
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700327 ~ScopedDirRemover() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800328 if (should_remove_ && (rmdir(path_.c_str()) < 0)) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700329 PLOG(ERROR) << "Unable to remove dir " << path_;
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800330 }
331 }
332 void set_should_remove(bool should_remove) { should_remove_ = should_remove; }
333
334 protected:
335 const std::string path_;
336
337 private:
338 bool should_remove_;
339 DISALLOW_COPY_AND_ASSIGN(ScopedDirRemover);
340};
341
342// Utility class to unmount a filesystem mounted on a temporary directory and
343// delete the temporary directory when it goes out of scope.
344class ScopedTempUnmounter : public ScopedDirRemover {
345 public:
346 explicit ScopedTempUnmounter(const std::string& path) :
347 ScopedDirRemover(path) {}
348 ~ScopedTempUnmounter() {
349 utils::UnmountFilesystem(path_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700350 }
351 private:
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800352 DISALLOW_COPY_AND_ASSIGN(ScopedTempUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000353};
354
355// A little object to call ActionComplete on the ActionProcessor when
356// it's destructed.
357class ScopedActionCompleter {
358 public:
359 explicit ScopedActionCompleter(ActionProcessor* processor,
360 AbstractAction* action)
361 : processor_(processor),
362 action_(action),
Darin Petkovc1a8b422010-07-19 11:34:49 -0700363 code_(kActionCodeError),
adlr@google.com3defe6a2009-12-04 20:57:17 +0000364 should_complete_(true) {}
365 ~ScopedActionCompleter() {
366 if (should_complete_)
Darin Petkovc1a8b422010-07-19 11:34:49 -0700367 processor_->ActionComplete(action_, code_);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000368 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700369 void set_code(ActionExitCode code) { code_ = code; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000370 void set_should_complete(bool should_complete) {
371 should_complete_ = should_complete;
372 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700373
adlr@google.com3defe6a2009-12-04 20:57:17 +0000374 private:
375 ActionProcessor* processor_;
376 AbstractAction* action_;
Darin Petkovc1a8b422010-07-19 11:34:49 -0700377 ActionExitCode code_;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000378 bool should_complete_;
379 DISALLOW_COPY_AND_ASSIGN(ScopedActionCompleter);
380};
381
382} // namespace chromeos_update_engine
383
384#define TEST_AND_RETURN_FALSE_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 false; \
392 } \
393 } while (0)
394
395#define TEST_AND_RETURN_FALSE(_x) \
396 do { \
397 bool _success = (_x); \
398 if (!_success) { \
399 LOG(ERROR) << #_x " failed."; \
400 return false; \
401 } \
402 } while (0)
403
404#define TEST_AND_RETURN_ERRNO(_x) \
405 do { \
406 bool _success = (_x); \
407 if (!_success) { \
408 std::string _msg = \
409 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
410 LOG(ERROR) << #_x " failed: " << _msg; \
411 return; \
412 } \
413 } while (0)
414
415#define TEST_AND_RETURN(_x) \
416 do { \
417 bool _success = (_x); \
418 if (!_success) { \
419 LOG(ERROR) << #_x " failed."; \
420 return; \
421 } \
422 } while (0)
423
Thieu Le5c7d9752010-12-15 16:09:28 -0800424#define TEST_AND_RETURN_FALSE_ERRCODE(_x) \
425 do { \
426 errcode_t _error = (_x); \
427 if (_error) { \
428 errno = _error; \
429 LOG(ERROR) << #_x " failed: " << _error; \
430 return false; \
431 } \
432 } while (0)
433
adlr@google.com3defe6a2009-12-04 20:57:17 +0000434
435
436#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_UTILS_H__