blob: 7983eecb146dce46e8e13ae48660159dd0ea7c84 [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
adlr@google.com3defe6a2009-12-04 20:57:17 +0000138// Returns the currently booted device. "/dev/sda1", for example.
139// 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
143} // namespace utils
144
145// Class to unmount FS when object goes out of scope
146class ScopedFilesystemUnmounter {
147 public:
148 explicit ScopedFilesystemUnmounter(const std::string& mountpoint)
149 : mountpoint_(mountpoint) {}
150 ~ScopedFilesystemUnmounter() {
151 utils::UnmountFilesystem(mountpoint_);
152 }
153 private:
154 const std::string mountpoint_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700155 DISALLOW_COPY_AND_ASSIGN(ScopedFilesystemUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000156};
157
158// Utility class to close a file descriptor
159class ScopedFdCloser {
160 public:
161 explicit ScopedFdCloser(int* fd) : fd_(fd), should_close_(true) {}
162 void set_should_close(bool should_close) { should_close_ = should_close; }
163 ~ScopedFdCloser() {
164 if (!should_close_)
165 return;
166 if (fd_ && (*fd_ >= 0)) {
167 close(*fd_);
168 *fd_ = -1;
169 }
170 }
171 private:
172 int* fd_;
173 bool should_close_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700174 DISALLOW_COPY_AND_ASSIGN(ScopedFdCloser);
175};
176
177// Utility class to delete a file when it goes out of scope.
178class ScopedPathUnlinker {
179 public:
180 explicit ScopedPathUnlinker(const std::string& path) : path_(path) {}
181 ~ScopedPathUnlinker() {
182 if (unlink(path_.c_str()) < 0) {
183 std::string err_message = strerror(errno);
184 LOG(ERROR) << "Unable to unlink path " << path_ << ": " << err_message;
185 }
186 }
187 private:
188 const std::string path_;
189 DISALLOW_COPY_AND_ASSIGN(ScopedPathUnlinker);
190};
191
192// Utility class to delete an empty directory when it goes out of scope.
193class ScopedDirRemover {
194 public:
195 explicit ScopedDirRemover(const std::string& path) : path_(path) {}
196 ~ScopedDirRemover() {
197 if (rmdir(path_.c_str()) < 0)
198 PLOG(ERROR) << "Unable to remove dir " << path_;
199 }
200 private:
201 const std::string path_;
202 DISALLOW_COPY_AND_ASSIGN(ScopedDirRemover);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000203};
204
205// A little object to call ActionComplete on the ActionProcessor when
206// it's destructed.
207class ScopedActionCompleter {
208 public:
209 explicit ScopedActionCompleter(ActionProcessor* processor,
210 AbstractAction* action)
211 : processor_(processor),
212 action_(action),
213 success_(false),
214 should_complete_(true) {}
215 ~ScopedActionCompleter() {
216 if (should_complete_)
217 processor_->ActionComplete(action_, success_);
218 }
219 void set_success(bool success) {
220 success_ = success;
221 }
222 void set_should_complete(bool should_complete) {
223 should_complete_ = should_complete;
224 }
225 private:
226 ActionProcessor* processor_;
227 AbstractAction* action_;
228 bool success_;
229 bool should_complete_;
230 DISALLOW_COPY_AND_ASSIGN(ScopedActionCompleter);
231};
232
233} // namespace chromeos_update_engine
234
235#define TEST_AND_RETURN_FALSE_ERRNO(_x) \
236 do { \
237 bool _success = (_x); \
238 if (!_success) { \
239 std::string _msg = \
240 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
241 LOG(ERROR) << #_x " failed: " << _msg; \
242 return false; \
243 } \
244 } while (0)
245
246#define TEST_AND_RETURN_FALSE(_x) \
247 do { \
248 bool _success = (_x); \
249 if (!_success) { \
250 LOG(ERROR) << #_x " failed."; \
251 return false; \
252 } \
253 } while (0)
254
255#define TEST_AND_RETURN_ERRNO(_x) \
256 do { \
257 bool _success = (_x); \
258 if (!_success) { \
259 std::string _msg = \
260 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
261 LOG(ERROR) << #_x " failed: " << _msg; \
262 return; \
263 } \
264 } while (0)
265
266#define TEST_AND_RETURN(_x) \
267 do { \
268 bool _success = (_x); \
269 if (!_success) { \
270 LOG(ERROR) << #_x " failed."; \
271 return; \
272 } \
273 } while (0)
274
275
276
277#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_UTILS_H__