blob: 6ce4cf36ad20ed219ddc8d681af902af63b58024 [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>
Andrew de los Reyes81ebcd82010-03-09 15:56:18 -08009#include <algorithm>
adlr@google.com3defe6a2009-12-04 20:57:17 +000010#include <set>
11#include <string>
12#include <vector>
Andrew de los Reyesc7020782010-04-28 10:46:04 -070013#include <glib.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000014#include "update_engine/action.h"
15#include "update_engine/action_processor.h"
16
17namespace chromeos_update_engine {
18
19namespace utils {
20
Darin Petkov33d30642010-08-04 10:18:57 -070021// Returns true if this is an official Chrome OS build, false
22// otherwise. Currently, this routine errs on the official build side
23// -- if it doesn't recognize the update track as non-official, it
24// assumes the build is official.
25bool IsOfficialBuild();
26
Andrew de los Reyes970bb282009-12-09 16:34:04 -080027// Writes the data passed to path. The file at path will be overwritten if it
28// exists. Returns true on success, false otherwise.
29bool WriteFile(const char* path, const char* data, int data_len);
30
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070031// Calls write() or pwrite() repeatedly until all count bytes at buf are
32// written to fd or an error occurs. Returns true on success.
33bool WriteAll(int fd, const void* buf, size_t count);
34bool PWriteAll(int fd, const void* buf, size_t count, off_t offset);
35
36// Calls pread() repeatedly until count bytes are read, or EOF is reached.
37// Returns number of bytes read in *bytes_read. Returns true on success.
38bool PReadAll(int fd, void* buf, size_t count, off_t offset,
39 ssize_t* out_bytes_read);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070040
adlr@google.com3defe6a2009-12-04 20:57:17 +000041// Returns the entire contents of the file at path. Returns true on success.
42bool ReadFile(const std::string& path, std::vector<char>* out);
43bool ReadFileToString(const std::string& path, std::string* out);
44
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070045// Returns the size of the file at path. If the file doesn't exist or some
46// error occurrs, -1 is returned.
47off_t FileSize(const std::string& path);
48
adlr@google.com3defe6a2009-12-04 20:57:17 +000049std::string ErrnoNumberAsString(int err);
50
51// Strips duplicate slashes, and optionally removes all trailing slashes.
52// Does not compact /./ or /../.
53std::string NormalizePath(const std::string& path, bool strip_trailing_slash);
54
55// Returns true if the file exists for sure. Returns false if it doesn't exist,
56// or an error occurs.
57bool FileExists(const char* path);
58
59// The last 6 chars of path must be XXXXXX. They will be randomly changed
60// and a non-existent path will be returned. Intentionally makes a copy
61// of the string passed in.
62// NEVER CALL THIS FUNCTION UNLESS YOU ARE SURE
63// THAT YOUR PROCESS WILL BE THE ONLY THING WRITING FILES IN THIS DIRECTORY.
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -080064std::string TempFilename(std::string path);
adlr@google.com3defe6a2009-12-04 20:57:17 +000065
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070066// Calls mkstemp() with the template passed. Returns the filename in the
67// out param filename. If fd is non-NULL, the file fd returned by mkstemp
68// is not close()d and is returned in the out param 'fd'. However, if
69// fd is NULL, the fd from mkstemp() will be closed.
70// The last six chars of the template must be XXXXXX.
71// Returns true on success.
72bool MakeTempFile(const std::string& filename_template,
73 std::string* filename,
74 int* fd);
75
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070076// Calls mkdtemp() with the tempate passed. Returns the generated dirname
77// in the dirname param. Returns TRUE on success. dirname must not be NULL.
78bool MakeTempDirectory(const std::string& dirname_template,
79 std::string* dirname);
80
adlr@google.com3defe6a2009-12-04 20:57:17 +000081// Deletes a directory and all its contents synchronously. Returns true
82// on success. This may be called with a regular file--it will just unlink it.
83// This WILL cross filesystem boundaries.
84bool RecursiveUnlinkDir(const std::string& path);
85
Andrew de los Reyesf9714432010-05-04 10:21:23 -070086// Returns the root device for a partition. For example,
Darin Petkovf74eb652010-08-04 12:08:38 -070087// RootDevice("/dev/sda3") returns "/dev/sda". Returns an empty string
88// if the input device is not of the "/dev/xyz" form.
Andrew de los Reyesf9714432010-05-04 10:21:23 -070089std::string RootDevice(const std::string& partition_device);
90
91// Returns the partition number, as a string, of partition_device. For example,
Darin Petkovf74eb652010-08-04 12:08:38 -070092// PartitionNumber("/dev/sda3") returns "3".
Andrew de los Reyesf9714432010-05-04 10:21:23 -070093std::string PartitionNumber(const std::string& partition_device);
94
Darin Petkovf74eb652010-08-04 12:08:38 -070095// Returns the sysfs block device for a root block device. For
96// example, SysfsBlockDevice("/dev/sda") returns
97// "/sys/block/sda". Returns an empty string if the input device is
98// not of the "/dev/xyz" form.
99std::string SysfsBlockDevice(const std::string& device);
100
101// Returns true if the root |device| (e.g., "/dev/sdb") is known to be
102// removable, false otherwise.
103bool IsRemovableDevice(const std::string& device);
104
adlr@google.com3defe6a2009-12-04 20:57:17 +0000105// Synchronously mount or unmount a filesystem. Return true on success.
106// Mounts as ext3 with default options.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700107bool MountFilesystem(const std::string& device, const std::string& mountpoint,
108 unsigned long flags);
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800109bool UnmountFilesystem(const std::string& mountpoint);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000110
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700111enum BootLoader {
112 BootLoader_SYSLINUX = 0,
113 BootLoader_CHROME_FIRMWARE = 1
114};
115// Detects which bootloader this system uses and returns it via the out
116// param. Returns true on success.
117bool GetBootloader(BootLoader* out_bootloader);
118
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700119// Returns the error message, if any, from a GError pointer.
120const char* GetGErrorMessage(const GError* error);
121
Darin Petkov296889c2010-07-23 16:20:54 -0700122// Initiates a system reboot. Returns true on success, false otherwise.
123bool Reboot();
124
adlr@google.com3defe6a2009-12-04 20:57:17 +0000125// Log a string in hex to LOG(INFO). Useful for debugging.
126void HexDumpArray(const unsigned char* const arr, const size_t length);
127inline void HexDumpString(const std::string& str) {
128 HexDumpArray(reinterpret_cast<const unsigned char*>(str.data()), str.size());
129}
130inline void HexDumpVector(const std::vector<char>& vect) {
131 HexDumpArray(reinterpret_cast<const unsigned char*>(&vect[0]), vect.size());
132}
133
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800134extern const char* const kStatefulPartition;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000135
136bool StringHasSuffix(const std::string& str, const std::string& suffix);
137bool StringHasPrefix(const std::string& str, const std::string& prefix);
138
139template<typename KeyType, typename ValueType>
140bool MapContainsKey(const std::map<KeyType, ValueType>& m, const KeyType& k) {
141 return m.find(k) != m.end();
142}
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800143template<typename KeyType>
144bool SetContainsKey(const std::set<KeyType>& s, const KeyType& k) {
145 return s.find(k) != s.end();
146}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000147
148template<typename ValueType>
149std::set<ValueType> SetWithValue(const ValueType& value) {
150 std::set<ValueType> ret;
151 ret.insert(value);
152 return ret;
153}
154
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800155template<typename T>
156bool VectorContainsValue(const std::vector<T>& vect, const T& value) {
Darin Petkovc1a8b422010-07-19 11:34:49 -0700157 return std::find(vect.begin(), vect.end(), value) != vect.end();
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800158}
159
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700160template<typename T>
161bool VectorIndexOf(const std::vector<T>& vect, const T& value,
162 typename std::vector<T>::size_type* out_index) {
163 typename std::vector<T>::const_iterator it = std::find(vect.begin(),
164 vect.end(),
165 value);
166 if (it == vect.end()) {
167 return false;
168 } else {
169 *out_index = it - vect.begin();
170 return true;
171 }
172}
173
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700174// Returns the currently booted device. "/dev/sda3", for example.
adlr@google.com3defe6a2009-12-04 20:57:17 +0000175// This will not interpret LABEL= or UUID=. You'll need to use findfs
176// or something with equivalent funcionality to interpret those.
177const std::string BootDevice();
178
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700179// Returns the currently booted kernel device, "dev/sda2", for example.
180// Client must pass in the boot device. The suggested calling convention
181// is: BootKernelDevice(BootDevice()).
182// This function works by doing string modification on boot_device.
183// Returns empty string on failure.
184const std::string BootKernelDevice(const std::string& boot_device);
185
186
adlr@google.com3defe6a2009-12-04 20:57:17 +0000187} // namespace utils
188
189// Class to unmount FS when object goes out of scope
190class ScopedFilesystemUnmounter {
191 public:
192 explicit ScopedFilesystemUnmounter(const std::string& mountpoint)
193 : mountpoint_(mountpoint) {}
194 ~ScopedFilesystemUnmounter() {
195 utils::UnmountFilesystem(mountpoint_);
196 }
197 private:
198 const std::string mountpoint_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700199 DISALLOW_COPY_AND_ASSIGN(ScopedFilesystemUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000200};
201
202// Utility class to close a file descriptor
203class ScopedFdCloser {
204 public:
205 explicit ScopedFdCloser(int* fd) : fd_(fd), should_close_(true) {}
206 void set_should_close(bool should_close) { should_close_ = should_close; }
207 ~ScopedFdCloser() {
208 if (!should_close_)
209 return;
210 if (fd_ && (*fd_ >= 0)) {
211 close(*fd_);
212 *fd_ = -1;
213 }
214 }
215 private:
216 int* fd_;
217 bool should_close_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700218 DISALLOW_COPY_AND_ASSIGN(ScopedFdCloser);
219};
220
221// Utility class to delete a file when it goes out of scope.
222class ScopedPathUnlinker {
223 public:
224 explicit ScopedPathUnlinker(const std::string& path) : path_(path) {}
225 ~ScopedPathUnlinker() {
226 if (unlink(path_.c_str()) < 0) {
227 std::string err_message = strerror(errno);
228 LOG(ERROR) << "Unable to unlink path " << path_ << ": " << err_message;
229 }
230 }
231 private:
232 const std::string path_;
233 DISALLOW_COPY_AND_ASSIGN(ScopedPathUnlinker);
234};
235
236// Utility class to delete an empty directory when it goes out of scope.
237class ScopedDirRemover {
238 public:
239 explicit ScopedDirRemover(const std::string& path) : path_(path) {}
240 ~ScopedDirRemover() {
241 if (rmdir(path_.c_str()) < 0)
242 PLOG(ERROR) << "Unable to remove dir " << path_;
243 }
244 private:
245 const std::string path_;
246 DISALLOW_COPY_AND_ASSIGN(ScopedDirRemover);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000247};
248
249// A little object to call ActionComplete on the ActionProcessor when
250// it's destructed.
251class ScopedActionCompleter {
252 public:
253 explicit ScopedActionCompleter(ActionProcessor* processor,
254 AbstractAction* action)
255 : processor_(processor),
256 action_(action),
Darin Petkovc1a8b422010-07-19 11:34:49 -0700257 code_(kActionCodeError),
adlr@google.com3defe6a2009-12-04 20:57:17 +0000258 should_complete_(true) {}
259 ~ScopedActionCompleter() {
260 if (should_complete_)
Darin Petkovc1a8b422010-07-19 11:34:49 -0700261 processor_->ActionComplete(action_, code_);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000262 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700263 void set_code(ActionExitCode code) { code_ = code; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000264 void set_should_complete(bool should_complete) {
265 should_complete_ = should_complete;
266 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700267
adlr@google.com3defe6a2009-12-04 20:57:17 +0000268 private:
269 ActionProcessor* processor_;
270 AbstractAction* action_;
Darin Petkovc1a8b422010-07-19 11:34:49 -0700271 ActionExitCode code_;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000272 bool should_complete_;
273 DISALLOW_COPY_AND_ASSIGN(ScopedActionCompleter);
274};
275
276} // namespace chromeos_update_engine
277
278#define TEST_AND_RETURN_FALSE_ERRNO(_x) \
279 do { \
280 bool _success = (_x); \
281 if (!_success) { \
282 std::string _msg = \
283 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
284 LOG(ERROR) << #_x " failed: " << _msg; \
285 return false; \
286 } \
287 } while (0)
288
289#define TEST_AND_RETURN_FALSE(_x) \
290 do { \
291 bool _success = (_x); \
292 if (!_success) { \
293 LOG(ERROR) << #_x " failed."; \
294 return false; \
295 } \
296 } while (0)
297
298#define TEST_AND_RETURN_ERRNO(_x) \
299 do { \
300 bool _success = (_x); \
301 if (!_success) { \
302 std::string _msg = \
303 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
304 LOG(ERROR) << #_x " failed: " << _msg; \
305 return; \
306 } \
307 } while (0)
308
309#define TEST_AND_RETURN(_x) \
310 do { \
311 bool _success = (_x); \
312 if (!_success) { \
313 LOG(ERROR) << #_x " failed."; \
314 return; \
315 } \
316 } while (0)
317
318
319
320#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_UTILS_H__