blob: 8b070ed157d3c256346d1c71f02897409d3482fd [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
Andrew de los Reyesc7020782010-04-28 10:46:04 -070015#include <glib.h>
Darin Petkovc6c135c2010-08-11 13:36:18 -070016
adlr@google.com3defe6a2009-12-04 20:57:17 +000017#include "update_engine/action.h"
18#include "update_engine/action_processor.h"
19
20namespace chromeos_update_engine {
21
22namespace utils {
23
Darin Petkov33d30642010-08-04 10:18:57 -070024// Returns true if this is an official Chrome OS build, false
25// otherwise. Currently, this routine errs on the official build side
26// -- if it doesn't recognize the update track as non-official, it
27// assumes the build is official.
28bool IsOfficialBuild();
29
Andrew de los Reyes970bb282009-12-09 16:34:04 -080030// Writes the data passed to path. The file at path will be overwritten if it
31// exists. Returns true on success, false otherwise.
32bool WriteFile(const char* path, const char* data, int data_len);
33
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070034// Calls write() or pwrite() repeatedly until all count bytes at buf are
35// written to fd or an error occurs. Returns true on success.
36bool WriteAll(int fd, const void* buf, size_t count);
37bool PWriteAll(int fd, const void* buf, size_t count, off_t offset);
38
39// Calls pread() repeatedly until count bytes are read, or EOF is reached.
40// Returns number of bytes read in *bytes_read. Returns true on success.
41bool PReadAll(int fd, void* buf, size_t count, off_t offset,
42 ssize_t* out_bytes_read);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070043
adlr@google.com3defe6a2009-12-04 20:57:17 +000044// Returns the entire contents of the file at path. Returns true on success.
45bool ReadFile(const std::string& path, std::vector<char>* out);
46bool ReadFileToString(const std::string& path, std::string* out);
47
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070048// Returns the size of the file at path. If the file doesn't exist or some
49// error occurrs, -1 is returned.
50off_t FileSize(const std::string& path);
51
adlr@google.com3defe6a2009-12-04 20:57:17 +000052std::string ErrnoNumberAsString(int err);
53
54// Strips duplicate slashes, and optionally removes all trailing slashes.
55// Does not compact /./ or /../.
56std::string NormalizePath(const std::string& path, bool strip_trailing_slash);
57
58// Returns true if the file exists for sure. Returns false if it doesn't exist,
59// or an error occurs.
60bool FileExists(const char* path);
61
62// The last 6 chars of path must be XXXXXX. They will be randomly changed
63// and a non-existent path will be returned. Intentionally makes a copy
64// of the string passed in.
65// NEVER CALL THIS FUNCTION UNLESS YOU ARE SURE
66// THAT YOUR PROCESS WILL BE THE ONLY THING WRITING FILES IN THIS DIRECTORY.
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -080067std::string TempFilename(std::string path);
adlr@google.com3defe6a2009-12-04 20:57:17 +000068
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070069// Calls mkstemp() with the template passed. Returns the filename in the
70// out param filename. If fd is non-NULL, the file fd returned by mkstemp
71// is not close()d and is returned in the out param 'fd'. However, if
72// fd is NULL, the fd from mkstemp() will be closed.
73// The last six chars of the template must be XXXXXX.
74// Returns true on success.
75bool MakeTempFile(const std::string& filename_template,
76 std::string* filename,
77 int* fd);
78
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070079// Calls mkdtemp() with the tempate passed. Returns the generated dirname
80// in the dirname param. Returns TRUE on success. dirname must not be NULL.
81bool MakeTempDirectory(const std::string& dirname_template,
82 std::string* dirname);
83
adlr@google.com3defe6a2009-12-04 20:57:17 +000084// Deletes a directory and all its contents synchronously. Returns true
85// on success. This may be called with a regular file--it will just unlink it.
86// This WILL cross filesystem boundaries.
87bool RecursiveUnlinkDir(const std::string& path);
88
Andrew de los Reyesf9714432010-05-04 10:21:23 -070089// Returns the root device for a partition. For example,
Darin Petkovf74eb652010-08-04 12:08:38 -070090// RootDevice("/dev/sda3") returns "/dev/sda". Returns an empty string
91// if the input device is not of the "/dev/xyz" form.
Andrew de los Reyesf9714432010-05-04 10:21:23 -070092std::string RootDevice(const std::string& partition_device);
93
94// Returns the partition number, as a string, of partition_device. For example,
Darin Petkovf74eb652010-08-04 12:08:38 -070095// PartitionNumber("/dev/sda3") returns "3".
Andrew de los Reyesf9714432010-05-04 10:21:23 -070096std::string PartitionNumber(const std::string& partition_device);
97
Darin Petkovf74eb652010-08-04 12:08:38 -070098// Returns the sysfs block device for a root block device. For
99// example, SysfsBlockDevice("/dev/sda") returns
100// "/sys/block/sda". Returns an empty string if the input device is
101// not of the "/dev/xyz" form.
102std::string SysfsBlockDevice(const std::string& device);
103
104// Returns true if the root |device| (e.g., "/dev/sdb") is known to be
105// removable, false otherwise.
106bool IsRemovableDevice(const std::string& device);
107
adlr@google.com3defe6a2009-12-04 20:57:17 +0000108// Synchronously mount or unmount a filesystem. Return true on success.
109// Mounts as ext3 with default options.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700110bool MountFilesystem(const std::string& device, const std::string& mountpoint,
111 unsigned long flags);
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800112bool UnmountFilesystem(const std::string& mountpoint);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000113
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700114enum BootLoader {
115 BootLoader_SYSLINUX = 0,
116 BootLoader_CHROME_FIRMWARE = 1
117};
118// Detects which bootloader this system uses and returns it via the out
119// param. Returns true on success.
120bool GetBootloader(BootLoader* out_bootloader);
121
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700122// Returns the error message, if any, from a GError pointer.
123const char* GetGErrorMessage(const GError* error);
124
Darin Petkov296889c2010-07-23 16:20:54 -0700125// Initiates a system reboot. Returns true on success, false otherwise.
126bool Reboot();
127
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700128// Fuzzes an integer |value| randomly in the range:
129// [value - range / 2, value + range - range / 2]
130int FuzzInt(int value, unsigned int range);
131
adlr@google.com3defe6a2009-12-04 20:57:17 +0000132// Log a string in hex to LOG(INFO). Useful for debugging.
133void HexDumpArray(const unsigned char* const arr, const size_t length);
134inline void HexDumpString(const std::string& str) {
135 HexDumpArray(reinterpret_cast<const unsigned char*>(str.data()), str.size());
136}
137inline void HexDumpVector(const std::vector<char>& vect) {
138 HexDumpArray(reinterpret_cast<const unsigned char*>(&vect[0]), vect.size());
139}
140
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800141extern const char* const kStatefulPartition;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000142
143bool StringHasSuffix(const std::string& str, const std::string& suffix);
144bool StringHasPrefix(const std::string& str, const std::string& prefix);
145
146template<typename KeyType, typename ValueType>
147bool MapContainsKey(const std::map<KeyType, ValueType>& m, const KeyType& k) {
148 return m.find(k) != m.end();
149}
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800150template<typename KeyType>
151bool SetContainsKey(const std::set<KeyType>& s, const KeyType& k) {
152 return s.find(k) != s.end();
153}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000154
155template<typename ValueType>
156std::set<ValueType> SetWithValue(const ValueType& value) {
157 std::set<ValueType> ret;
158 ret.insert(value);
159 return ret;
160}
161
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800162template<typename T>
163bool VectorContainsValue(const std::vector<T>& vect, const T& value) {
Darin Petkovc1a8b422010-07-19 11:34:49 -0700164 return std::find(vect.begin(), vect.end(), value) != vect.end();
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800165}
166
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700167template<typename T>
168bool VectorIndexOf(const std::vector<T>& vect, const T& value,
169 typename std::vector<T>::size_type* out_index) {
170 typename std::vector<T>::const_iterator it = std::find(vect.begin(),
171 vect.end(),
172 value);
173 if (it == vect.end()) {
174 return false;
175 } else {
176 *out_index = it - vect.begin();
177 return true;
178 }
179}
180
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700181// Returns the currently booted device. "/dev/sda3", for example.
adlr@google.com3defe6a2009-12-04 20:57:17 +0000182// This will not interpret LABEL= or UUID=. You'll need to use findfs
183// or something with equivalent funcionality to interpret those.
184const std::string BootDevice();
185
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700186// Returns the currently booted kernel device, "dev/sda2", for example.
187// Client must pass in the boot device. The suggested calling convention
188// is: BootKernelDevice(BootDevice()).
189// This function works by doing string modification on boot_device.
190// Returns empty string on failure.
191const std::string BootKernelDevice(const std::string& boot_device);
192
Darin Petkovc6c135c2010-08-11 13:36:18 -0700193enum ProcessPriority {
194 kProcessPriorityHigh = -10,
195 kProcessPriorityNormal = 0,
196 kProcessPriorityLow = 10,
197};
198
199// Compares process priorities and returns an integer that is less
200// than, equal to or greater than 0 if |priority_lhs| is,
201// respectively, lower than, same as or higher than |priority_rhs|.
202int ComparePriorities(ProcessPriority priority_lhs,
203 ProcessPriority priority_rhs);
204
205// Sets the current process priority to |priority|. Returns true on
206// success, false otherwise.
207bool SetProcessPriority(ProcessPriority priority);
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700208
adlr@google.com3defe6a2009-12-04 20:57:17 +0000209} // namespace utils
210
211// Class to unmount FS when object goes out of scope
212class ScopedFilesystemUnmounter {
213 public:
214 explicit ScopedFilesystemUnmounter(const std::string& mountpoint)
215 : mountpoint_(mountpoint) {}
216 ~ScopedFilesystemUnmounter() {
217 utils::UnmountFilesystem(mountpoint_);
218 }
219 private:
220 const std::string mountpoint_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700221 DISALLOW_COPY_AND_ASSIGN(ScopedFilesystemUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000222};
223
224// Utility class to close a file descriptor
225class ScopedFdCloser {
226 public:
227 explicit ScopedFdCloser(int* fd) : fd_(fd), should_close_(true) {}
228 void set_should_close(bool should_close) { should_close_ = should_close; }
229 ~ScopedFdCloser() {
230 if (!should_close_)
231 return;
232 if (fd_ && (*fd_ >= 0)) {
233 close(*fd_);
234 *fd_ = -1;
235 }
236 }
237 private:
238 int* fd_;
239 bool should_close_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700240 DISALLOW_COPY_AND_ASSIGN(ScopedFdCloser);
241};
242
243// Utility class to delete a file when it goes out of scope.
244class ScopedPathUnlinker {
245 public:
246 explicit ScopedPathUnlinker(const std::string& path) : path_(path) {}
247 ~ScopedPathUnlinker() {
248 if (unlink(path_.c_str()) < 0) {
249 std::string err_message = strerror(errno);
250 LOG(ERROR) << "Unable to unlink path " << path_ << ": " << err_message;
251 }
252 }
253 private:
254 const std::string path_;
255 DISALLOW_COPY_AND_ASSIGN(ScopedPathUnlinker);
256};
257
258// Utility class to delete an empty directory when it goes out of scope.
259class ScopedDirRemover {
260 public:
261 explicit ScopedDirRemover(const std::string& path) : path_(path) {}
262 ~ScopedDirRemover() {
263 if (rmdir(path_.c_str()) < 0)
264 PLOG(ERROR) << "Unable to remove dir " << path_;
265 }
266 private:
267 const std::string path_;
268 DISALLOW_COPY_AND_ASSIGN(ScopedDirRemover);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000269};
270
271// A little object to call ActionComplete on the ActionProcessor when
272// it's destructed.
273class ScopedActionCompleter {
274 public:
275 explicit ScopedActionCompleter(ActionProcessor* processor,
276 AbstractAction* action)
277 : processor_(processor),
278 action_(action),
Darin Petkovc1a8b422010-07-19 11:34:49 -0700279 code_(kActionCodeError),
adlr@google.com3defe6a2009-12-04 20:57:17 +0000280 should_complete_(true) {}
281 ~ScopedActionCompleter() {
282 if (should_complete_)
Darin Petkovc1a8b422010-07-19 11:34:49 -0700283 processor_->ActionComplete(action_, code_);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000284 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700285 void set_code(ActionExitCode code) { code_ = code; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000286 void set_should_complete(bool should_complete) {
287 should_complete_ = should_complete;
288 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700289
adlr@google.com3defe6a2009-12-04 20:57:17 +0000290 private:
291 ActionProcessor* processor_;
292 AbstractAction* action_;
Darin Petkovc1a8b422010-07-19 11:34:49 -0700293 ActionExitCode code_;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000294 bool should_complete_;
295 DISALLOW_COPY_AND_ASSIGN(ScopedActionCompleter);
296};
297
298} // namespace chromeos_update_engine
299
300#define TEST_AND_RETURN_FALSE_ERRNO(_x) \
301 do { \
302 bool _success = (_x); \
303 if (!_success) { \
304 std::string _msg = \
305 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
306 LOG(ERROR) << #_x " failed: " << _msg; \
307 return false; \
308 } \
309 } while (0)
310
311#define TEST_AND_RETURN_FALSE(_x) \
312 do { \
313 bool _success = (_x); \
314 if (!_success) { \
315 LOG(ERROR) << #_x " failed."; \
316 return false; \
317 } \
318 } while (0)
319
320#define TEST_AND_RETURN_ERRNO(_x) \
321 do { \
322 bool _success = (_x); \
323 if (!_success) { \
324 std::string _msg = \
325 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
326 LOG(ERROR) << #_x " failed: " << _msg; \
327 return; \
328 } \
329 } while (0)
330
331#define TEST_AND_RETURN(_x) \
332 do { \
333 bool _success = (_x); \
334 if (!_success) { \
335 LOG(ERROR) << #_x " failed."; \
336 return; \
337 } \
338 } while (0)
339
340
341
342#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_UTILS_H__