blob: 7b39cd47e07947c3dc37044a7812ddf5fb36f41f [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
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700145// Returns the error message, if any, from a GError pointer.
146const char* GetGErrorMessage(const GError* error);
147
Darin Petkov296889c2010-07-23 16:20:54 -0700148// Initiates a system reboot. Returns true on success, false otherwise.
149bool Reboot();
150
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800151// Schedules a Main Loop callback to trigger the crash reporter to perform an
152// upload as if this process had crashed.
153void ScheduleCrashReporterUpload();
154
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700155// Fuzzes an integer |value| randomly in the range:
156// [value - range / 2, value + range - range / 2]
157int FuzzInt(int value, unsigned int range);
158
adlr@google.com3defe6a2009-12-04 20:57:17 +0000159// Log a string in hex to LOG(INFO). Useful for debugging.
160void HexDumpArray(const unsigned char* const arr, const size_t length);
161inline void HexDumpString(const std::string& str) {
162 HexDumpArray(reinterpret_cast<const unsigned char*>(str.data()), str.size());
163}
164inline void HexDumpVector(const std::vector<char>& vect) {
165 HexDumpArray(reinterpret_cast<const unsigned char*>(&vect[0]), vect.size());
166}
167
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800168extern const char* const kStatefulPartition;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000169
170bool StringHasSuffix(const std::string& str, const std::string& suffix);
171bool StringHasPrefix(const std::string& str, const std::string& prefix);
172
173template<typename KeyType, typename ValueType>
174bool MapContainsKey(const std::map<KeyType, ValueType>& m, const KeyType& k) {
175 return m.find(k) != m.end();
176}
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800177template<typename KeyType>
178bool SetContainsKey(const std::set<KeyType>& s, const KeyType& k) {
179 return s.find(k) != s.end();
180}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000181
182template<typename ValueType>
183std::set<ValueType> SetWithValue(const ValueType& value) {
184 std::set<ValueType> ret;
185 ret.insert(value);
186 return ret;
187}
188
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800189template<typename T>
190bool VectorContainsValue(const std::vector<T>& vect, const T& value) {
Darin Petkovc1a8b422010-07-19 11:34:49 -0700191 return std::find(vect.begin(), vect.end(), value) != vect.end();
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800192}
193
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700194template<typename T>
195bool VectorIndexOf(const std::vector<T>& vect, const T& value,
196 typename std::vector<T>::size_type* out_index) {
197 typename std::vector<T>::const_iterator it = std::find(vect.begin(),
198 vect.end(),
199 value);
200 if (it == vect.end()) {
201 return false;
202 } else {
203 *out_index = it - vect.begin();
204 return true;
205 }
206}
207
Andrew de los Reyescc92cd32010-10-05 16:56:14 -0700208template<typename ValueType>
209void ApplyMap(std::vector<ValueType>* collection,
210 const std::map<ValueType, ValueType>& the_map) {
211 for (typename std::vector<ValueType>::iterator it = collection->begin();
212 it != collection->end(); ++it) {
213 typename std::map<ValueType, ValueType>::const_iterator map_it =
214 the_map.find(*it);
215 if (map_it != the_map.end()) {
216 *it = map_it->second;
217 }
218 }
219}
220
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700221// Returns the currently booted device. "/dev/sda3", for example.
adlr@google.com3defe6a2009-12-04 20:57:17 +0000222// This will not interpret LABEL= or UUID=. You'll need to use findfs
223// or something with equivalent funcionality to interpret those.
224const std::string BootDevice();
225
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700226// Returns the currently booted kernel device, "dev/sda2", for example.
227// Client must pass in the boot device. The suggested calling convention
228// is: BootKernelDevice(BootDevice()).
229// This function works by doing string modification on boot_device.
230// Returns empty string on failure.
231const std::string BootKernelDevice(const std::string& boot_device);
232
Darin Petkovc6c135c2010-08-11 13:36:18 -0700233enum ProcessPriority {
234 kProcessPriorityHigh = -10,
235 kProcessPriorityNormal = 0,
236 kProcessPriorityLow = 10,
237};
238
239// Compares process priorities and returns an integer that is less
240// than, equal to or greater than 0 if |priority_lhs| is,
241// respectively, lower than, same as or higher than |priority_rhs|.
242int ComparePriorities(ProcessPriority priority_lhs,
243 ProcessPriority priority_rhs);
244
245// Sets the current process priority to |priority|. Returns true on
246// success, false otherwise.
247bool SetProcessPriority(ProcessPriority priority);
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700248
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800249// Assumes data points to a Closure. Runs it and returns FALSE;
250gboolean GlibRunClosure(gpointer data);
251
adlr@google.com3defe6a2009-12-04 20:57:17 +0000252} // namespace utils
253
254// Class to unmount FS when object goes out of scope
255class ScopedFilesystemUnmounter {
256 public:
257 explicit ScopedFilesystemUnmounter(const std::string& mountpoint)
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800258 : mountpoint_(mountpoint),
259 should_unmount_(true) {}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000260 ~ScopedFilesystemUnmounter() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800261 if (should_unmount_) {
262 utils::UnmountFilesystem(mountpoint_);
263 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000264 }
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800265 void set_should_unmount(bool unmount) { should_unmount_ = unmount; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000266 private:
267 const std::string mountpoint_;
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800268 bool should_unmount_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700269 DISALLOW_COPY_AND_ASSIGN(ScopedFilesystemUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000270};
271
272// Utility class to close a file descriptor
273class ScopedFdCloser {
274 public:
275 explicit ScopedFdCloser(int* fd) : fd_(fd), should_close_(true) {}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000276 ~ScopedFdCloser() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800277 if (should_close_ && fd_ && (*fd_ >= 0)) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000278 close(*fd_);
279 *fd_ = -1;
280 }
281 }
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800282 void set_should_close(bool should_close) { should_close_ = should_close; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000283 private:
284 int* fd_;
285 bool should_close_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700286 DISALLOW_COPY_AND_ASSIGN(ScopedFdCloser);
287};
288
Thieu Le5c7d9752010-12-15 16:09:28 -0800289// Utility class to close a file system
290class ScopedExt2fsCloser {
291 public:
292 explicit ScopedExt2fsCloser(ext2_filsys filsys) : filsys_(filsys) {}
293 ~ScopedExt2fsCloser() { ext2fs_close(filsys_); }
294
295 private:
296 ext2_filsys filsys_;
297 DISALLOW_COPY_AND_ASSIGN(ScopedExt2fsCloser);
298};
299
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700300// Utility class to delete a file when it goes out of scope.
301class ScopedPathUnlinker {
302 public:
Darin Petkov52dcaeb2011-01-14 15:33:06 -0800303 explicit ScopedPathUnlinker(const std::string& path)
304 : path_(path),
305 should_remove_(true) {}
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700306 ~ScopedPathUnlinker() {
Darin Petkov52dcaeb2011-01-14 15:33:06 -0800307 if (should_remove_ && unlink(path_.c_str()) < 0) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700308 std::string err_message = strerror(errno);
309 LOG(ERROR) << "Unable to unlink path " << path_ << ": " << err_message;
310 }
311 }
Darin Petkov52dcaeb2011-01-14 15:33:06 -0800312 void set_should_remove(bool should_remove) { should_remove_ = should_remove; }
313
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700314 private:
315 const std::string path_;
Darin Petkov52dcaeb2011-01-14 15:33:06 -0800316 bool should_remove_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700317 DISALLOW_COPY_AND_ASSIGN(ScopedPathUnlinker);
318};
319
320// Utility class to delete an empty directory when it goes out of scope.
321class ScopedDirRemover {
322 public:
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800323 explicit ScopedDirRemover(const std::string& path)
324 : path_(path),
325 should_remove_(true) {}
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700326 ~ScopedDirRemover() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800327 if (should_remove_ && (rmdir(path_.c_str()) < 0)) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700328 PLOG(ERROR) << "Unable to remove dir " << path_;
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800329 }
330 }
331 void set_should_remove(bool should_remove) { should_remove_ = should_remove; }
332
333 protected:
334 const std::string path_;
335
336 private:
337 bool should_remove_;
338 DISALLOW_COPY_AND_ASSIGN(ScopedDirRemover);
339};
340
341// Utility class to unmount a filesystem mounted on a temporary directory and
342// delete the temporary directory when it goes out of scope.
343class ScopedTempUnmounter : public ScopedDirRemover {
344 public:
345 explicit ScopedTempUnmounter(const std::string& path) :
346 ScopedDirRemover(path) {}
347 ~ScopedTempUnmounter() {
348 utils::UnmountFilesystem(path_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700349 }
350 private:
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800351 DISALLOW_COPY_AND_ASSIGN(ScopedTempUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000352};
353
354// A little object to call ActionComplete on the ActionProcessor when
355// it's destructed.
356class ScopedActionCompleter {
357 public:
358 explicit ScopedActionCompleter(ActionProcessor* processor,
359 AbstractAction* action)
360 : processor_(processor),
361 action_(action),
Darin Petkovc1a8b422010-07-19 11:34:49 -0700362 code_(kActionCodeError),
adlr@google.com3defe6a2009-12-04 20:57:17 +0000363 should_complete_(true) {}
364 ~ScopedActionCompleter() {
365 if (should_complete_)
Darin Petkovc1a8b422010-07-19 11:34:49 -0700366 processor_->ActionComplete(action_, code_);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000367 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700368 void set_code(ActionExitCode code) { code_ = code; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000369 void set_should_complete(bool should_complete) {
370 should_complete_ = should_complete;
371 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700372
adlr@google.com3defe6a2009-12-04 20:57:17 +0000373 private:
374 ActionProcessor* processor_;
375 AbstractAction* action_;
Darin Petkovc1a8b422010-07-19 11:34:49 -0700376 ActionExitCode code_;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000377 bool should_complete_;
378 DISALLOW_COPY_AND_ASSIGN(ScopedActionCompleter);
379};
380
381} // namespace chromeos_update_engine
382
383#define TEST_AND_RETURN_FALSE_ERRNO(_x) \
384 do { \
385 bool _success = (_x); \
386 if (!_success) { \
387 std::string _msg = \
388 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
389 LOG(ERROR) << #_x " failed: " << _msg; \
390 return false; \
391 } \
392 } while (0)
393
394#define TEST_AND_RETURN_FALSE(_x) \
395 do { \
396 bool _success = (_x); \
397 if (!_success) { \
398 LOG(ERROR) << #_x " failed."; \
399 return false; \
400 } \
401 } while (0)
402
403#define TEST_AND_RETURN_ERRNO(_x) \
404 do { \
405 bool _success = (_x); \
406 if (!_success) { \
407 std::string _msg = \
408 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
409 LOG(ERROR) << #_x " failed: " << _msg; \
410 return; \
411 } \
412 } while (0)
413
414#define TEST_AND_RETURN(_x) \
415 do { \
416 bool _success = (_x); \
417 if (!_success) { \
418 LOG(ERROR) << #_x " failed."; \
419 return; \
420 } \
421 } while (0)
422
Thieu Le5c7d9752010-12-15 16:09:28 -0800423#define TEST_AND_RETURN_FALSE_ERRCODE(_x) \
424 do { \
425 errcode_t _error = (_x); \
426 if (_error) { \
427 errno = _error; \
428 LOG(ERROR) << #_x " failed: " << _error; \
429 return false; \
430 } \
431 } while (0)
432
adlr@google.com3defe6a2009-12-04 20:57:17 +0000433
434
435#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_UTILS_H__