blob: e5d099f1c94dccbef9461d7ec70e0b90c986ec08 [file] [log] [blame]
adlr@google.com3defe6a2009-12-04 20:57:17 +00001// Copyright (c) 2009 The Chromium Authors. All rights reserved.
2// 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
80// Synchronously mount or unmount a filesystem. Return true on success.
81// Mounts as ext3 with default options.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070082bool MountFilesystem(const std::string& device, const std::string& mountpoint,
83 unsigned long flags);
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -080084bool UnmountFilesystem(const std::string& mountpoint);
adlr@google.com3defe6a2009-12-04 20:57:17 +000085
Andrew de los Reyesc7020782010-04-28 10:46:04 -070086// Returns the error message, if any, from a GError pointer.
87const char* GetGErrorMessage(const GError* error);
88
adlr@google.com3defe6a2009-12-04 20:57:17 +000089// Log a string in hex to LOG(INFO). Useful for debugging.
90void HexDumpArray(const unsigned char* const arr, const size_t length);
91inline void HexDumpString(const std::string& str) {
92 HexDumpArray(reinterpret_cast<const unsigned char*>(str.data()), str.size());
93}
94inline void HexDumpVector(const std::vector<char>& vect) {
95 HexDumpArray(reinterpret_cast<const unsigned char*>(&vect[0]), vect.size());
96}
97
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -080098extern const char* const kStatefulPartition;
adlr@google.com3defe6a2009-12-04 20:57:17 +000099
100bool StringHasSuffix(const std::string& str, const std::string& suffix);
101bool StringHasPrefix(const std::string& str, const std::string& prefix);
102
103template<typename KeyType, typename ValueType>
104bool MapContainsKey(const std::map<KeyType, ValueType>& m, const KeyType& k) {
105 return m.find(k) != m.end();
106}
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800107template<typename KeyType>
108bool SetContainsKey(const std::set<KeyType>& s, const KeyType& k) {
109 return s.find(k) != s.end();
110}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000111
112template<typename ValueType>
113std::set<ValueType> SetWithValue(const ValueType& value) {
114 std::set<ValueType> ret;
115 ret.insert(value);
116 return ret;
117}
118
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800119template<typename T>
120bool VectorContainsValue(const std::vector<T>& vect, const T& value) {
121 return std::find(vect.begin(), vect.end(), value) != vect.end();
122}
123
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700124template<typename T>
125bool VectorIndexOf(const std::vector<T>& vect, const T& value,
126 typename std::vector<T>::size_type* out_index) {
127 typename std::vector<T>::const_iterator it = std::find(vect.begin(),
128 vect.end(),
129 value);
130 if (it == vect.end()) {
131 return false;
132 } else {
133 *out_index = it - vect.begin();
134 return true;
135 }
136}
137
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700138// Returns the currently booted device. "/dev/sda3", for example.
adlr@google.com3defe6a2009-12-04 20:57:17 +0000139// This will not interpret LABEL= or UUID=. You'll need to use findfs
140// or something with equivalent funcionality to interpret those.
141const std::string BootDevice();
142
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700143// Returns the currently booted kernel device, "dev/sda2", for example.
144// Client must pass in the boot device. The suggested calling convention
145// is: BootKernelDevice(BootDevice()).
146// This function works by doing string modification on boot_device.
147// Returns empty string on failure.
148const std::string BootKernelDevice(const std::string& boot_device);
149
150
adlr@google.com3defe6a2009-12-04 20:57:17 +0000151} // namespace utils
152
153// Class to unmount FS when object goes out of scope
154class ScopedFilesystemUnmounter {
155 public:
156 explicit ScopedFilesystemUnmounter(const std::string& mountpoint)
157 : mountpoint_(mountpoint) {}
158 ~ScopedFilesystemUnmounter() {
159 utils::UnmountFilesystem(mountpoint_);
160 }
161 private:
162 const std::string mountpoint_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700163 DISALLOW_COPY_AND_ASSIGN(ScopedFilesystemUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000164};
165
166// Utility class to close a file descriptor
167class ScopedFdCloser {
168 public:
169 explicit ScopedFdCloser(int* fd) : fd_(fd), should_close_(true) {}
170 void set_should_close(bool should_close) { should_close_ = should_close; }
171 ~ScopedFdCloser() {
172 if (!should_close_)
173 return;
174 if (fd_ && (*fd_ >= 0)) {
175 close(*fd_);
176 *fd_ = -1;
177 }
178 }
179 private:
180 int* fd_;
181 bool should_close_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700182 DISALLOW_COPY_AND_ASSIGN(ScopedFdCloser);
183};
184
185// Utility class to delete a file when it goes out of scope.
186class ScopedPathUnlinker {
187 public:
188 explicit ScopedPathUnlinker(const std::string& path) : path_(path) {}
189 ~ScopedPathUnlinker() {
190 if (unlink(path_.c_str()) < 0) {
191 std::string err_message = strerror(errno);
192 LOG(ERROR) << "Unable to unlink path " << path_ << ": " << err_message;
193 }
194 }
195 private:
196 const std::string path_;
197 DISALLOW_COPY_AND_ASSIGN(ScopedPathUnlinker);
198};
199
200// Utility class to delete an empty directory when it goes out of scope.
201class ScopedDirRemover {
202 public:
203 explicit ScopedDirRemover(const std::string& path) : path_(path) {}
204 ~ScopedDirRemover() {
205 if (rmdir(path_.c_str()) < 0)
206 PLOG(ERROR) << "Unable to remove dir " << path_;
207 }
208 private:
209 const std::string path_;
210 DISALLOW_COPY_AND_ASSIGN(ScopedDirRemover);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000211};
212
213// A little object to call ActionComplete on the ActionProcessor when
214// it's destructed.
215class ScopedActionCompleter {
216 public:
217 explicit ScopedActionCompleter(ActionProcessor* processor,
218 AbstractAction* action)
219 : processor_(processor),
220 action_(action),
221 success_(false),
222 should_complete_(true) {}
223 ~ScopedActionCompleter() {
224 if (should_complete_)
225 processor_->ActionComplete(action_, success_);
226 }
227 void set_success(bool success) {
228 success_ = success;
229 }
230 void set_should_complete(bool should_complete) {
231 should_complete_ = should_complete;
232 }
233 private:
234 ActionProcessor* processor_;
235 AbstractAction* action_;
236 bool success_;
237 bool should_complete_;
238 DISALLOW_COPY_AND_ASSIGN(ScopedActionCompleter);
239};
240
241} // namespace chromeos_update_engine
242
243#define TEST_AND_RETURN_FALSE_ERRNO(_x) \
244 do { \
245 bool _success = (_x); \
246 if (!_success) { \
247 std::string _msg = \
248 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
249 LOG(ERROR) << #_x " failed: " << _msg; \
250 return false; \
251 } \
252 } while (0)
253
254#define TEST_AND_RETURN_FALSE(_x) \
255 do { \
256 bool _success = (_x); \
257 if (!_success) { \
258 LOG(ERROR) << #_x " failed."; \
259 return false; \
260 } \
261 } while (0)
262
263#define TEST_AND_RETURN_ERRNO(_x) \
264 do { \
265 bool _success = (_x); \
266 if (!_success) { \
267 std::string _msg = \
268 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
269 LOG(ERROR) << #_x " failed: " << _msg; \
270 return; \
271 } \
272 } while (0)
273
274#define TEST_AND_RETURN(_x) \
275 do { \
276 bool _success = (_x); \
277 if (!_success) { \
278 LOG(ERROR) << #_x " failed."; \
279 return; \
280 } \
281 } while (0)
282
283
284
285#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_UTILS_H__