blob: f7f734ed322bf38ae2a1fd088e8661b170999b5b [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,
87// RootDevice("/dev/sda3") returns "/dev/sda".
88std::string RootDevice(const std::string& partition_device);
89
90// Returns the partition number, as a string, of partition_device. For example,
91// PartitionNumber("/dev/sda3") return "3".
92std::string PartitionNumber(const std::string& partition_device);
93
adlr@google.com3defe6a2009-12-04 20:57:17 +000094// Synchronously mount or unmount a filesystem. Return true on success.
95// Mounts as ext3 with default options.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070096bool MountFilesystem(const std::string& device, const std::string& mountpoint,
97 unsigned long flags);
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -080098bool UnmountFilesystem(const std::string& mountpoint);
adlr@google.com3defe6a2009-12-04 20:57:17 +000099
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700100enum BootLoader {
101 BootLoader_SYSLINUX = 0,
102 BootLoader_CHROME_FIRMWARE = 1
103};
104// Detects which bootloader this system uses and returns it via the out
105// param. Returns true on success.
106bool GetBootloader(BootLoader* out_bootloader);
107
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700108// Returns the error message, if any, from a GError pointer.
109const char* GetGErrorMessage(const GError* error);
110
Darin Petkov296889c2010-07-23 16:20:54 -0700111// Initiates a system reboot. Returns true on success, false otherwise.
112bool Reboot();
113
adlr@google.com3defe6a2009-12-04 20:57:17 +0000114// Log a string in hex to LOG(INFO). Useful for debugging.
115void HexDumpArray(const unsigned char* const arr, const size_t length);
116inline void HexDumpString(const std::string& str) {
117 HexDumpArray(reinterpret_cast<const unsigned char*>(str.data()), str.size());
118}
119inline void HexDumpVector(const std::vector<char>& vect) {
120 HexDumpArray(reinterpret_cast<const unsigned char*>(&vect[0]), vect.size());
121}
122
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800123extern const char* const kStatefulPartition;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000124
125bool StringHasSuffix(const std::string& str, const std::string& suffix);
126bool StringHasPrefix(const std::string& str, const std::string& prefix);
127
128template<typename KeyType, typename ValueType>
129bool MapContainsKey(const std::map<KeyType, ValueType>& m, const KeyType& k) {
130 return m.find(k) != m.end();
131}
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800132template<typename KeyType>
133bool SetContainsKey(const std::set<KeyType>& s, const KeyType& k) {
134 return s.find(k) != s.end();
135}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000136
137template<typename ValueType>
138std::set<ValueType> SetWithValue(const ValueType& value) {
139 std::set<ValueType> ret;
140 ret.insert(value);
141 return ret;
142}
143
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800144template<typename T>
145bool VectorContainsValue(const std::vector<T>& vect, const T& value) {
Darin Petkovc1a8b422010-07-19 11:34:49 -0700146 return std::find(vect.begin(), vect.end(), value) != vect.end();
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800147}
148
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700149template<typename T>
150bool VectorIndexOf(const std::vector<T>& vect, const T& value,
151 typename std::vector<T>::size_type* out_index) {
152 typename std::vector<T>::const_iterator it = std::find(vect.begin(),
153 vect.end(),
154 value);
155 if (it == vect.end()) {
156 return false;
157 } else {
158 *out_index = it - vect.begin();
159 return true;
160 }
161}
162
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700163// Returns the currently booted device. "/dev/sda3", for example.
adlr@google.com3defe6a2009-12-04 20:57:17 +0000164// This will not interpret LABEL= or UUID=. You'll need to use findfs
165// or something with equivalent funcionality to interpret those.
166const std::string BootDevice();
167
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700168// Returns the currently booted kernel device, "dev/sda2", for example.
169// Client must pass in the boot device. The suggested calling convention
170// is: BootKernelDevice(BootDevice()).
171// This function works by doing string modification on boot_device.
172// Returns empty string on failure.
173const std::string BootKernelDevice(const std::string& boot_device);
174
175
adlr@google.com3defe6a2009-12-04 20:57:17 +0000176} // namespace utils
177
178// Class to unmount FS when object goes out of scope
179class ScopedFilesystemUnmounter {
180 public:
181 explicit ScopedFilesystemUnmounter(const std::string& mountpoint)
182 : mountpoint_(mountpoint) {}
183 ~ScopedFilesystemUnmounter() {
184 utils::UnmountFilesystem(mountpoint_);
185 }
186 private:
187 const std::string mountpoint_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700188 DISALLOW_COPY_AND_ASSIGN(ScopedFilesystemUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000189};
190
191// Utility class to close a file descriptor
192class ScopedFdCloser {
193 public:
194 explicit ScopedFdCloser(int* fd) : fd_(fd), should_close_(true) {}
195 void set_should_close(bool should_close) { should_close_ = should_close; }
196 ~ScopedFdCloser() {
197 if (!should_close_)
198 return;
199 if (fd_ && (*fd_ >= 0)) {
200 close(*fd_);
201 *fd_ = -1;
202 }
203 }
204 private:
205 int* fd_;
206 bool should_close_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700207 DISALLOW_COPY_AND_ASSIGN(ScopedFdCloser);
208};
209
210// Utility class to delete a file when it goes out of scope.
211class ScopedPathUnlinker {
212 public:
213 explicit ScopedPathUnlinker(const std::string& path) : path_(path) {}
214 ~ScopedPathUnlinker() {
215 if (unlink(path_.c_str()) < 0) {
216 std::string err_message = strerror(errno);
217 LOG(ERROR) << "Unable to unlink path " << path_ << ": " << err_message;
218 }
219 }
220 private:
221 const std::string path_;
222 DISALLOW_COPY_AND_ASSIGN(ScopedPathUnlinker);
223};
224
225// Utility class to delete an empty directory when it goes out of scope.
226class ScopedDirRemover {
227 public:
228 explicit ScopedDirRemover(const std::string& path) : path_(path) {}
229 ~ScopedDirRemover() {
230 if (rmdir(path_.c_str()) < 0)
231 PLOG(ERROR) << "Unable to remove dir " << path_;
232 }
233 private:
234 const std::string path_;
235 DISALLOW_COPY_AND_ASSIGN(ScopedDirRemover);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000236};
237
238// A little object to call ActionComplete on the ActionProcessor when
239// it's destructed.
240class ScopedActionCompleter {
241 public:
242 explicit ScopedActionCompleter(ActionProcessor* processor,
243 AbstractAction* action)
244 : processor_(processor),
245 action_(action),
Darin Petkovc1a8b422010-07-19 11:34:49 -0700246 code_(kActionCodeError),
adlr@google.com3defe6a2009-12-04 20:57:17 +0000247 should_complete_(true) {}
248 ~ScopedActionCompleter() {
249 if (should_complete_)
Darin Petkovc1a8b422010-07-19 11:34:49 -0700250 processor_->ActionComplete(action_, code_);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000251 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700252 void set_code(ActionExitCode code) { code_ = code; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000253 void set_should_complete(bool should_complete) {
254 should_complete_ = should_complete;
255 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700256
adlr@google.com3defe6a2009-12-04 20:57:17 +0000257 private:
258 ActionProcessor* processor_;
259 AbstractAction* action_;
Darin Petkovc1a8b422010-07-19 11:34:49 -0700260 ActionExitCode code_;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000261 bool should_complete_;
262 DISALLOW_COPY_AND_ASSIGN(ScopedActionCompleter);
263};
264
265} // namespace chromeos_update_engine
266
267#define TEST_AND_RETURN_FALSE_ERRNO(_x) \
268 do { \
269 bool _success = (_x); \
270 if (!_success) { \
271 std::string _msg = \
272 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
273 LOG(ERROR) << #_x " failed: " << _msg; \
274 return false; \
275 } \
276 } while (0)
277
278#define TEST_AND_RETURN_FALSE(_x) \
279 do { \
280 bool _success = (_x); \
281 if (!_success) { \
282 LOG(ERROR) << #_x " failed."; \
283 return false; \
284 } \
285 } while (0)
286
287#define TEST_AND_RETURN_ERRNO(_x) \
288 do { \
289 bool _success = (_x); \
290 if (!_success) { \
291 std::string _msg = \
292 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
293 LOG(ERROR) << #_x " failed: " << _msg; \
294 return; \
295 } \
296 } while (0)
297
298#define TEST_AND_RETURN(_x) \
299 do { \
300 bool _success = (_x); \
301 if (!_success) { \
302 LOG(ERROR) << #_x " failed."; \
303 return; \
304 } \
305 } while (0)
306
307
308
309#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_UTILS_H__