blob: 7b6fc102f199d9c4d63150e4a6d461e99819d412 [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
39std::string ErrnoNumberAsString(int err);
40
41// Strips duplicate slashes, and optionally removes all trailing slashes.
42// Does not compact /./ or /../.
43std::string NormalizePath(const std::string& path, bool strip_trailing_slash);
44
45// Returns true if the file exists for sure. Returns false if it doesn't exist,
46// or an error occurs.
47bool FileExists(const char* path);
48
49// The last 6 chars of path must be XXXXXX. They will be randomly changed
50// and a non-existent path will be returned. Intentionally makes a copy
51// of the string passed in.
52// NEVER CALL THIS FUNCTION UNLESS YOU ARE SURE
53// THAT YOUR PROCESS WILL BE THE ONLY THING WRITING FILES IN THIS DIRECTORY.
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -080054std::string TempFilename(std::string path);
adlr@google.com3defe6a2009-12-04 20:57:17 +000055
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070056// Calls mkstemp() with the template passed. Returns the filename in the
57// out param filename. If fd is non-NULL, the file fd returned by mkstemp
58// is not close()d and is returned in the out param 'fd'. However, if
59// fd is NULL, the fd from mkstemp() will be closed.
60// The last six chars of the template must be XXXXXX.
61// Returns true on success.
62bool MakeTempFile(const std::string& filename_template,
63 std::string* filename,
64 int* fd);
65
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070066// Calls mkdtemp() with the tempate passed. Returns the generated dirname
67// in the dirname param. Returns TRUE on success. dirname must not be NULL.
68bool MakeTempDirectory(const std::string& dirname_template,
69 std::string* dirname);
70
adlr@google.com3defe6a2009-12-04 20:57:17 +000071// Deletes a directory and all its contents synchronously. Returns true
72// on success. This may be called with a regular file--it will just unlink it.
73// This WILL cross filesystem boundaries.
74bool RecursiveUnlinkDir(const std::string& path);
75
76// Synchronously mount or unmount a filesystem. Return true on success.
77// Mounts as ext3 with default options.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070078bool MountFilesystem(const std::string& device, const std::string& mountpoint,
79 unsigned long flags);
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -080080bool UnmountFilesystem(const std::string& mountpoint);
adlr@google.com3defe6a2009-12-04 20:57:17 +000081
Andrew de los Reyesc7020782010-04-28 10:46:04 -070082// Returns the error message, if any, from a GError pointer.
83const char* GetGErrorMessage(const GError* error);
84
adlr@google.com3defe6a2009-12-04 20:57:17 +000085// Log a string in hex to LOG(INFO). Useful for debugging.
86void HexDumpArray(const unsigned char* const arr, const size_t length);
87inline void HexDumpString(const std::string& str) {
88 HexDumpArray(reinterpret_cast<const unsigned char*>(str.data()), str.size());
89}
90inline void HexDumpVector(const std::vector<char>& vect) {
91 HexDumpArray(reinterpret_cast<const unsigned char*>(&vect[0]), vect.size());
92}
93
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -080094extern const char* const kStatefulPartition;
adlr@google.com3defe6a2009-12-04 20:57:17 +000095
96bool StringHasSuffix(const std::string& str, const std::string& suffix);
97bool StringHasPrefix(const std::string& str, const std::string& prefix);
98
99template<typename KeyType, typename ValueType>
100bool MapContainsKey(const std::map<KeyType, ValueType>& m, const KeyType& k) {
101 return m.find(k) != m.end();
102}
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800103template<typename KeyType>
104bool SetContainsKey(const std::set<KeyType>& s, const KeyType& k) {
105 return s.find(k) != s.end();
106}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000107
108template<typename ValueType>
109std::set<ValueType> SetWithValue(const ValueType& value) {
110 std::set<ValueType> ret;
111 ret.insert(value);
112 return ret;
113}
114
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800115template<typename T>
116bool VectorContainsValue(const std::vector<T>& vect, const T& value) {
117 return std::find(vect.begin(), vect.end(), value) != vect.end();
118}
119
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700120template<typename T>
121bool VectorIndexOf(const std::vector<T>& vect, const T& value,
122 typename std::vector<T>::size_type* out_index) {
123 typename std::vector<T>::const_iterator it = std::find(vect.begin(),
124 vect.end(),
125 value);
126 if (it == vect.end()) {
127 return false;
128 } else {
129 *out_index = it - vect.begin();
130 return true;
131 }
132}
133
adlr@google.com3defe6a2009-12-04 20:57:17 +0000134// Returns the currently booted device. "/dev/sda1", for example.
135// This will not interpret LABEL= or UUID=. You'll need to use findfs
136// or something with equivalent funcionality to interpret those.
137const std::string BootDevice();
138
139} // namespace utils
140
141// Class to unmount FS when object goes out of scope
142class ScopedFilesystemUnmounter {
143 public:
144 explicit ScopedFilesystemUnmounter(const std::string& mountpoint)
145 : mountpoint_(mountpoint) {}
146 ~ScopedFilesystemUnmounter() {
147 utils::UnmountFilesystem(mountpoint_);
148 }
149 private:
150 const std::string mountpoint_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700151 DISALLOW_COPY_AND_ASSIGN(ScopedFilesystemUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000152};
153
154// Utility class to close a file descriptor
155class ScopedFdCloser {
156 public:
157 explicit ScopedFdCloser(int* fd) : fd_(fd), should_close_(true) {}
158 void set_should_close(bool should_close) { should_close_ = should_close; }
159 ~ScopedFdCloser() {
160 if (!should_close_)
161 return;
162 if (fd_ && (*fd_ >= 0)) {
163 close(*fd_);
164 *fd_ = -1;
165 }
166 }
167 private:
168 int* fd_;
169 bool should_close_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700170 DISALLOW_COPY_AND_ASSIGN(ScopedFdCloser);
171};
172
173// Utility class to delete a file when it goes out of scope.
174class ScopedPathUnlinker {
175 public:
176 explicit ScopedPathUnlinker(const std::string& path) : path_(path) {}
177 ~ScopedPathUnlinker() {
178 if (unlink(path_.c_str()) < 0) {
179 std::string err_message = strerror(errno);
180 LOG(ERROR) << "Unable to unlink path " << path_ << ": " << err_message;
181 }
182 }
183 private:
184 const std::string path_;
185 DISALLOW_COPY_AND_ASSIGN(ScopedPathUnlinker);
186};
187
188// Utility class to delete an empty directory when it goes out of scope.
189class ScopedDirRemover {
190 public:
191 explicit ScopedDirRemover(const std::string& path) : path_(path) {}
192 ~ScopedDirRemover() {
193 if (rmdir(path_.c_str()) < 0)
194 PLOG(ERROR) << "Unable to remove dir " << path_;
195 }
196 private:
197 const std::string path_;
198 DISALLOW_COPY_AND_ASSIGN(ScopedDirRemover);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000199};
200
201// A little object to call ActionComplete on the ActionProcessor when
202// it's destructed.
203class ScopedActionCompleter {
204 public:
205 explicit ScopedActionCompleter(ActionProcessor* processor,
206 AbstractAction* action)
207 : processor_(processor),
208 action_(action),
209 success_(false),
210 should_complete_(true) {}
211 ~ScopedActionCompleter() {
212 if (should_complete_)
213 processor_->ActionComplete(action_, success_);
214 }
215 void set_success(bool success) {
216 success_ = success;
217 }
218 void set_should_complete(bool should_complete) {
219 should_complete_ = should_complete;
220 }
221 private:
222 ActionProcessor* processor_;
223 AbstractAction* action_;
224 bool success_;
225 bool should_complete_;
226 DISALLOW_COPY_AND_ASSIGN(ScopedActionCompleter);
227};
228
229} // namespace chromeos_update_engine
230
231#define TEST_AND_RETURN_FALSE_ERRNO(_x) \
232 do { \
233 bool _success = (_x); \
234 if (!_success) { \
235 std::string _msg = \
236 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
237 LOG(ERROR) << #_x " failed: " << _msg; \
238 return false; \
239 } \
240 } while (0)
241
242#define TEST_AND_RETURN_FALSE(_x) \
243 do { \
244 bool _success = (_x); \
245 if (!_success) { \
246 LOG(ERROR) << #_x " failed."; \
247 return false; \
248 } \
249 } while (0)
250
251#define TEST_AND_RETURN_ERRNO(_x) \
252 do { \
253 bool _success = (_x); \
254 if (!_success) { \
255 std::string _msg = \
256 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
257 LOG(ERROR) << #_x " failed: " << _msg; \
258 return; \
259 } \
260 } while (0)
261
262#define TEST_AND_RETURN(_x) \
263 do { \
264 bool _success = (_x); \
265 if (!_success) { \
266 LOG(ERROR) << #_x " failed."; \
267 return; \
268 } \
269 } while (0)
270
271
272
273#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_UTILS_H__