blob: 9be2509793e9acfaffdee502a2ef4967fd4809a3 [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
Andrew de los Reyes970bb282009-12-09 16:34:04 -080021// Writes the data passed to path. The file at path will be overwritten if it
22// exists. Returns true on success, false otherwise.
23bool WriteFile(const char* path, const char* data, int data_len);
24
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070025// Calls write() or pwrite() repeatedly until all count bytes at buf are
26// written to fd or an error occurs. Returns true on success.
27bool WriteAll(int fd, const void* buf, size_t count);
28bool PWriteAll(int fd, const void* buf, size_t count, off_t offset);
29
30// Calls pread() repeatedly until count bytes are read, or EOF is reached.
31// Returns number of bytes read in *bytes_read. Returns true on success.
32bool PReadAll(int fd, void* buf, size_t count, off_t offset,
33 ssize_t* out_bytes_read);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070034
adlr@google.com3defe6a2009-12-04 20:57:17 +000035// Returns the entire contents of the file at path. Returns true on success.
36bool ReadFile(const std::string& path, std::vector<char>* out);
37bool ReadFileToString(const std::string& path, std::string* out);
38
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070039// Returns the size of the file at path. If the file doesn't exist or some
40// error occurrs, -1 is returned.
41off_t FileSize(const std::string& path);
42
adlr@google.com3defe6a2009-12-04 20:57:17 +000043std::string ErrnoNumberAsString(int err);
44
45// Strips duplicate slashes, and optionally removes all trailing slashes.
46// Does not compact /./ or /../.
47std::string NormalizePath(const std::string& path, bool strip_trailing_slash);
48
49// Returns true if the file exists for sure. Returns false if it doesn't exist,
50// or an error occurs.
51bool FileExists(const char* path);
52
53// The last 6 chars of path must be XXXXXX. They will be randomly changed
54// and a non-existent path will be returned. Intentionally makes a copy
55// of the string passed in.
56// NEVER CALL THIS FUNCTION UNLESS YOU ARE SURE
57// THAT YOUR PROCESS WILL BE THE ONLY THING WRITING FILES IN THIS DIRECTORY.
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -080058std::string TempFilename(std::string path);
adlr@google.com3defe6a2009-12-04 20:57:17 +000059
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070060// Calls mkstemp() with the template passed. Returns the filename in the
61// out param filename. If fd is non-NULL, the file fd returned by mkstemp
62// is not close()d and is returned in the out param 'fd'. However, if
63// fd is NULL, the fd from mkstemp() will be closed.
64// The last six chars of the template must be XXXXXX.
65// Returns true on success.
66bool MakeTempFile(const std::string& filename_template,
67 std::string* filename,
68 int* fd);
69
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070070// Calls mkdtemp() with the tempate passed. Returns the generated dirname
71// in the dirname param. Returns TRUE on success. dirname must not be NULL.
72bool MakeTempDirectory(const std::string& dirname_template,
73 std::string* dirname);
74
adlr@google.com3defe6a2009-12-04 20:57:17 +000075// Deletes a directory and all its contents synchronously. Returns true
76// on success. This may be called with a regular file--it will just unlink it.
77// This WILL cross filesystem boundaries.
78bool RecursiveUnlinkDir(const std::string& path);
79
Andrew de los Reyesf9714432010-05-04 10:21:23 -070080// Returns the root device for a partition. For example,
81// RootDevice("/dev/sda3") returns "/dev/sda".
82std::string RootDevice(const std::string& partition_device);
83
84// Returns the partition number, as a string, of partition_device. For example,
85// PartitionNumber("/dev/sda3") return "3".
86std::string PartitionNumber(const std::string& partition_device);
87
adlr@google.com3defe6a2009-12-04 20:57:17 +000088// Synchronously mount or unmount a filesystem. Return true on success.
89// Mounts as ext3 with default options.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070090bool MountFilesystem(const std::string& device, const std::string& mountpoint,
91 unsigned long flags);
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -080092bool UnmountFilesystem(const std::string& mountpoint);
adlr@google.com3defe6a2009-12-04 20:57:17 +000093
Andrew de los Reyesf9714432010-05-04 10:21:23 -070094enum BootLoader {
95 BootLoader_SYSLINUX = 0,
96 BootLoader_CHROME_FIRMWARE = 1
97};
98// Detects which bootloader this system uses and returns it via the out
99// param. Returns true on success.
100bool GetBootloader(BootLoader* out_bootloader);
101
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700102// Returns the error message, if any, from a GError pointer.
103const char* GetGErrorMessage(const GError* error);
104
Darin Petkov296889c2010-07-23 16:20:54 -0700105// Initiates a system reboot. Returns true on success, false otherwise.
106bool Reboot();
107
adlr@google.com3defe6a2009-12-04 20:57:17 +0000108// Log a string in hex to LOG(INFO). Useful for debugging.
109void HexDumpArray(const unsigned char* const arr, const size_t length);
110inline void HexDumpString(const std::string& str) {
111 HexDumpArray(reinterpret_cast<const unsigned char*>(str.data()), str.size());
112}
113inline void HexDumpVector(const std::vector<char>& vect) {
114 HexDumpArray(reinterpret_cast<const unsigned char*>(&vect[0]), vect.size());
115}
116
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800117extern const char* const kStatefulPartition;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000118
119bool StringHasSuffix(const std::string& str, const std::string& suffix);
120bool StringHasPrefix(const std::string& str, const std::string& prefix);
121
122template<typename KeyType, typename ValueType>
123bool MapContainsKey(const std::map<KeyType, ValueType>& m, const KeyType& k) {
124 return m.find(k) != m.end();
125}
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800126template<typename KeyType>
127bool SetContainsKey(const std::set<KeyType>& s, const KeyType& k) {
128 return s.find(k) != s.end();
129}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000130
131template<typename ValueType>
132std::set<ValueType> SetWithValue(const ValueType& value) {
133 std::set<ValueType> ret;
134 ret.insert(value);
135 return ret;
136}
137
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800138template<typename T>
139bool VectorContainsValue(const std::vector<T>& vect, const T& value) {
Darin Petkovc1a8b422010-07-19 11:34:49 -0700140 return std::find(vect.begin(), vect.end(), value) != vect.end();
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800141}
142
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700143template<typename T>
144bool VectorIndexOf(const std::vector<T>& vect, const T& value,
145 typename std::vector<T>::size_type* out_index) {
146 typename std::vector<T>::const_iterator it = std::find(vect.begin(),
147 vect.end(),
148 value);
149 if (it == vect.end()) {
150 return false;
151 } else {
152 *out_index = it - vect.begin();
153 return true;
154 }
155}
156
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700157// Returns the currently booted device. "/dev/sda3", for example.
adlr@google.com3defe6a2009-12-04 20:57:17 +0000158// This will not interpret LABEL= or UUID=. You'll need to use findfs
159// or something with equivalent funcionality to interpret those.
160const std::string BootDevice();
161
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700162// Returns the currently booted kernel device, "dev/sda2", for example.
163// Client must pass in the boot device. The suggested calling convention
164// is: BootKernelDevice(BootDevice()).
165// This function works by doing string modification on boot_device.
166// Returns empty string on failure.
167const std::string BootKernelDevice(const std::string& boot_device);
168
169
adlr@google.com3defe6a2009-12-04 20:57:17 +0000170} // namespace utils
171
172// Class to unmount FS when object goes out of scope
173class ScopedFilesystemUnmounter {
174 public:
175 explicit ScopedFilesystemUnmounter(const std::string& mountpoint)
176 : mountpoint_(mountpoint) {}
177 ~ScopedFilesystemUnmounter() {
178 utils::UnmountFilesystem(mountpoint_);
179 }
180 private:
181 const std::string mountpoint_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700182 DISALLOW_COPY_AND_ASSIGN(ScopedFilesystemUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000183};
184
185// Utility class to close a file descriptor
186class ScopedFdCloser {
187 public:
188 explicit ScopedFdCloser(int* fd) : fd_(fd), should_close_(true) {}
189 void set_should_close(bool should_close) { should_close_ = should_close; }
190 ~ScopedFdCloser() {
191 if (!should_close_)
192 return;
193 if (fd_ && (*fd_ >= 0)) {
194 close(*fd_);
195 *fd_ = -1;
196 }
197 }
198 private:
199 int* fd_;
200 bool should_close_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700201 DISALLOW_COPY_AND_ASSIGN(ScopedFdCloser);
202};
203
204// Utility class to delete a file when it goes out of scope.
205class ScopedPathUnlinker {
206 public:
207 explicit ScopedPathUnlinker(const std::string& path) : path_(path) {}
208 ~ScopedPathUnlinker() {
209 if (unlink(path_.c_str()) < 0) {
210 std::string err_message = strerror(errno);
211 LOG(ERROR) << "Unable to unlink path " << path_ << ": " << err_message;
212 }
213 }
214 private:
215 const std::string path_;
216 DISALLOW_COPY_AND_ASSIGN(ScopedPathUnlinker);
217};
218
219// Utility class to delete an empty directory when it goes out of scope.
220class ScopedDirRemover {
221 public:
222 explicit ScopedDirRemover(const std::string& path) : path_(path) {}
223 ~ScopedDirRemover() {
224 if (rmdir(path_.c_str()) < 0)
225 PLOG(ERROR) << "Unable to remove dir " << path_;
226 }
227 private:
228 const std::string path_;
229 DISALLOW_COPY_AND_ASSIGN(ScopedDirRemover);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000230};
231
232// A little object to call ActionComplete on the ActionProcessor when
233// it's destructed.
234class ScopedActionCompleter {
235 public:
236 explicit ScopedActionCompleter(ActionProcessor* processor,
237 AbstractAction* action)
238 : processor_(processor),
239 action_(action),
Darin Petkovc1a8b422010-07-19 11:34:49 -0700240 code_(kActionCodeError),
adlr@google.com3defe6a2009-12-04 20:57:17 +0000241 should_complete_(true) {}
242 ~ScopedActionCompleter() {
243 if (should_complete_)
Darin Petkovc1a8b422010-07-19 11:34:49 -0700244 processor_->ActionComplete(action_, code_);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000245 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700246 void set_code(ActionExitCode code) { code_ = code; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000247 void set_should_complete(bool should_complete) {
248 should_complete_ = should_complete;
249 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700250
adlr@google.com3defe6a2009-12-04 20:57:17 +0000251 private:
252 ActionProcessor* processor_;
253 AbstractAction* action_;
Darin Petkovc1a8b422010-07-19 11:34:49 -0700254 ActionExitCode code_;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000255 bool should_complete_;
256 DISALLOW_COPY_AND_ASSIGN(ScopedActionCompleter);
257};
258
259} // namespace chromeos_update_engine
260
261#define TEST_AND_RETURN_FALSE_ERRNO(_x) \
262 do { \
263 bool _success = (_x); \
264 if (!_success) { \
265 std::string _msg = \
266 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
267 LOG(ERROR) << #_x " failed: " << _msg; \
268 return false; \
269 } \
270 } while (0)
271
272#define TEST_AND_RETURN_FALSE(_x) \
273 do { \
274 bool _success = (_x); \
275 if (!_success) { \
276 LOG(ERROR) << #_x " failed."; \
277 return false; \
278 } \
279 } while (0)
280
281#define TEST_AND_RETURN_ERRNO(_x) \
282 do { \
283 bool _success = (_x); \
284 if (!_success) { \
285 std::string _msg = \
286 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
287 LOG(ERROR) << #_x " failed: " << _msg; \
288 return; \
289 } \
290 } while (0)
291
292#define TEST_AND_RETURN(_x) \
293 do { \
294 bool _success = (_x); \
295 if (!_success) { \
296 LOG(ERROR) << #_x " failed."; \
297 return; \
298 } \
299 } while (0)
300
301
302
303#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_UTILS_H__