blob: bcbd8daae18b1c4db7e49712ba3f20ef959ced99 [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>
13#include "update_engine/action.h"
14#include "update_engine/action_processor.h"
15
16namespace chromeos_update_engine {
17
18namespace utils {
19
Andrew de los Reyes970bb282009-12-09 16:34:04 -080020// Writes the data passed to path. The file at path will be overwritten if it
21// exists. Returns true on success, false otherwise.
22bool WriteFile(const char* path, const char* data, int data_len);
23
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070024// Calls write() or pwrite() repeatedly until all count bytes at buf are
25// written to fd or an error occurs. Returns true on success.
26bool WriteAll(int fd, const void* buf, size_t count);
27bool PWriteAll(int fd, const void* buf, size_t count, off_t offset);
28
29// Calls pread() repeatedly until count bytes are read, or EOF is reached.
30// Returns number of bytes read in *bytes_read. Returns true on success.
31bool PReadAll(int fd, void* buf, size_t count, off_t offset,
32 ssize_t* out_bytes_read);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070033
adlr@google.com3defe6a2009-12-04 20:57:17 +000034// Returns the entire contents of the file at path. Returns true on success.
35bool ReadFile(const std::string& path, std::vector<char>* out);
36bool ReadFileToString(const std::string& path, std::string* out);
37
38std::string ErrnoNumberAsString(int err);
39
40// Strips duplicate slashes, and optionally removes all trailing slashes.
41// Does not compact /./ or /../.
42std::string NormalizePath(const std::string& path, bool strip_trailing_slash);
43
44// Returns true if the file exists for sure. Returns false if it doesn't exist,
45// or an error occurs.
46bool FileExists(const char* path);
47
48// The last 6 chars of path must be XXXXXX. They will be randomly changed
49// and a non-existent path will be returned. Intentionally makes a copy
50// of the string passed in.
51// NEVER CALL THIS FUNCTION UNLESS YOU ARE SURE
52// THAT YOUR PROCESS WILL BE THE ONLY THING WRITING FILES IN THIS DIRECTORY.
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -080053std::string TempFilename(std::string path);
adlr@google.com3defe6a2009-12-04 20:57:17 +000054
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070055// Calls mkstemp() with the template passed. Returns the filename in the
56// out param filename. If fd is non-NULL, the file fd returned by mkstemp
57// is not close()d and is returned in the out param 'fd'. However, if
58// fd is NULL, the fd from mkstemp() will be closed.
59// The last six chars of the template must be XXXXXX.
60// Returns true on success.
61bool MakeTempFile(const std::string& filename_template,
62 std::string* filename,
63 int* fd);
64
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070065// Calls mkdtemp() with the tempate passed. Returns the generated dirname
66// in the dirname param. Returns TRUE on success. dirname must not be NULL.
67bool MakeTempDirectory(const std::string& dirname_template,
68 std::string* dirname);
69
adlr@google.com3defe6a2009-12-04 20:57:17 +000070// Deletes a directory and all its contents synchronously. Returns true
71// on success. This may be called with a regular file--it will just unlink it.
72// This WILL cross filesystem boundaries.
73bool RecursiveUnlinkDir(const std::string& path);
74
75// Synchronously mount or unmount a filesystem. Return true on success.
76// Mounts as ext3 with default options.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070077bool MountFilesystem(const std::string& device, const std::string& mountpoint,
78 unsigned long flags);
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -080079bool UnmountFilesystem(const std::string& mountpoint);
adlr@google.com3defe6a2009-12-04 20:57:17 +000080
81// Log a string in hex to LOG(INFO). Useful for debugging.
82void HexDumpArray(const unsigned char* const arr, const size_t length);
83inline void HexDumpString(const std::string& str) {
84 HexDumpArray(reinterpret_cast<const unsigned char*>(str.data()), str.size());
85}
86inline void HexDumpVector(const std::vector<char>& vect) {
87 HexDumpArray(reinterpret_cast<const unsigned char*>(&vect[0]), vect.size());
88}
89
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -080090extern const char* const kStatefulPartition;
adlr@google.com3defe6a2009-12-04 20:57:17 +000091
92bool StringHasSuffix(const std::string& str, const std::string& suffix);
93bool StringHasPrefix(const std::string& str, const std::string& prefix);
94
95template<typename KeyType, typename ValueType>
96bool MapContainsKey(const std::map<KeyType, ValueType>& m, const KeyType& k) {
97 return m.find(k) != m.end();
98}
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -080099template<typename KeyType>
100bool SetContainsKey(const std::set<KeyType>& s, const KeyType& k) {
101 return s.find(k) != s.end();
102}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000103
104template<typename ValueType>
105std::set<ValueType> SetWithValue(const ValueType& value) {
106 std::set<ValueType> ret;
107 ret.insert(value);
108 return ret;
109}
110
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800111template<typename T>
112bool VectorContainsValue(const std::vector<T>& vect, const T& value) {
113 return std::find(vect.begin(), vect.end(), value) != vect.end();
114}
115
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700116template<typename T>
117bool VectorIndexOf(const std::vector<T>& vect, const T& value,
118 typename std::vector<T>::size_type* out_index) {
119 typename std::vector<T>::const_iterator it = std::find(vect.begin(),
120 vect.end(),
121 value);
122 if (it == vect.end()) {
123 return false;
124 } else {
125 *out_index = it - vect.begin();
126 return true;
127 }
128}
129
adlr@google.com3defe6a2009-12-04 20:57:17 +0000130// Returns the currently booted device. "/dev/sda1", for example.
131// This will not interpret LABEL= or UUID=. You'll need to use findfs
132// or something with equivalent funcionality to interpret those.
133const std::string BootDevice();
134
135} // namespace utils
136
137// Class to unmount FS when object goes out of scope
138class ScopedFilesystemUnmounter {
139 public:
140 explicit ScopedFilesystemUnmounter(const std::string& mountpoint)
141 : mountpoint_(mountpoint) {}
142 ~ScopedFilesystemUnmounter() {
143 utils::UnmountFilesystem(mountpoint_);
144 }
145 private:
146 const std::string mountpoint_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700147 DISALLOW_COPY_AND_ASSIGN(ScopedFilesystemUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000148};
149
150// Utility class to close a file descriptor
151class ScopedFdCloser {
152 public:
153 explicit ScopedFdCloser(int* fd) : fd_(fd), should_close_(true) {}
154 void set_should_close(bool should_close) { should_close_ = should_close; }
155 ~ScopedFdCloser() {
156 if (!should_close_)
157 return;
158 if (fd_ && (*fd_ >= 0)) {
159 close(*fd_);
160 *fd_ = -1;
161 }
162 }
163 private:
164 int* fd_;
165 bool should_close_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700166 DISALLOW_COPY_AND_ASSIGN(ScopedFdCloser);
167};
168
169// Utility class to delete a file when it goes out of scope.
170class ScopedPathUnlinker {
171 public:
172 explicit ScopedPathUnlinker(const std::string& path) : path_(path) {}
173 ~ScopedPathUnlinker() {
174 if (unlink(path_.c_str()) < 0) {
175 std::string err_message = strerror(errno);
176 LOG(ERROR) << "Unable to unlink path " << path_ << ": " << err_message;
177 }
178 }
179 private:
180 const std::string path_;
181 DISALLOW_COPY_AND_ASSIGN(ScopedPathUnlinker);
182};
183
184// Utility class to delete an empty directory when it goes out of scope.
185class ScopedDirRemover {
186 public:
187 explicit ScopedDirRemover(const std::string& path) : path_(path) {}
188 ~ScopedDirRemover() {
189 if (rmdir(path_.c_str()) < 0)
190 PLOG(ERROR) << "Unable to remove dir " << path_;
191 }
192 private:
193 const std::string path_;
194 DISALLOW_COPY_AND_ASSIGN(ScopedDirRemover);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000195};
196
197// A little object to call ActionComplete on the ActionProcessor when
198// it's destructed.
199class ScopedActionCompleter {
200 public:
201 explicit ScopedActionCompleter(ActionProcessor* processor,
202 AbstractAction* action)
203 : processor_(processor),
204 action_(action),
205 success_(false),
206 should_complete_(true) {}
207 ~ScopedActionCompleter() {
208 if (should_complete_)
209 processor_->ActionComplete(action_, success_);
210 }
211 void set_success(bool success) {
212 success_ = success;
213 }
214 void set_should_complete(bool should_complete) {
215 should_complete_ = should_complete;
216 }
217 private:
218 ActionProcessor* processor_;
219 AbstractAction* action_;
220 bool success_;
221 bool should_complete_;
222 DISALLOW_COPY_AND_ASSIGN(ScopedActionCompleter);
223};
224
225} // namespace chromeos_update_engine
226
227#define TEST_AND_RETURN_FALSE_ERRNO(_x) \
228 do { \
229 bool _success = (_x); \
230 if (!_success) { \
231 std::string _msg = \
232 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
233 LOG(ERROR) << #_x " failed: " << _msg; \
234 return false; \
235 } \
236 } while (0)
237
238#define TEST_AND_RETURN_FALSE(_x) \
239 do { \
240 bool _success = (_x); \
241 if (!_success) { \
242 LOG(ERROR) << #_x " failed."; \
243 return false; \
244 } \
245 } while (0)
246
247#define TEST_AND_RETURN_ERRNO(_x) \
248 do { \
249 bool _success = (_x); \
250 if (!_success) { \
251 std::string _msg = \
252 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
253 LOG(ERROR) << #_x " failed: " << _msg; \
254 return; \
255 } \
256 } while (0)
257
258#define TEST_AND_RETURN(_x) \
259 do { \
260 bool _success = (_x); \
261 if (!_success) { \
262 LOG(ERROR) << #_x " failed."; \
263 return; \
264 } \
265 } while (0)
266
267
268
269#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_UTILS_H__