blob: 5a3efe94414c1499a1ae7ea8c1ffc1a9c58f8049 [file] [log] [blame]
Darin Petkovc1a8b422010-07-19 11:34:49 -07001// Copyright (c) 2010 The Chromium 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
adlr@google.com3defe6a2009-12-04 20:57:17 +0000105// Log a string in hex to LOG(INFO). Useful for debugging.
106void HexDumpArray(const unsigned char* const arr, const size_t length);
107inline void HexDumpString(const std::string& str) {
108 HexDumpArray(reinterpret_cast<const unsigned char*>(str.data()), str.size());
109}
110inline void HexDumpVector(const std::vector<char>& vect) {
111 HexDumpArray(reinterpret_cast<const unsigned char*>(&vect[0]), vect.size());
112}
113
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800114extern const char* const kStatefulPartition;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000115
116bool StringHasSuffix(const std::string& str, const std::string& suffix);
117bool StringHasPrefix(const std::string& str, const std::string& prefix);
118
119template<typename KeyType, typename ValueType>
120bool MapContainsKey(const std::map<KeyType, ValueType>& m, const KeyType& k) {
121 return m.find(k) != m.end();
122}
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800123template<typename KeyType>
124bool SetContainsKey(const std::set<KeyType>& s, const KeyType& k) {
125 return s.find(k) != s.end();
126}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000127
128template<typename ValueType>
129std::set<ValueType> SetWithValue(const ValueType& value) {
130 std::set<ValueType> ret;
131 ret.insert(value);
132 return ret;
133}
134
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800135template<typename T>
136bool VectorContainsValue(const std::vector<T>& vect, const T& value) {
Darin Petkovc1a8b422010-07-19 11:34:49 -0700137 return std::find(vect.begin(), vect.end(), value) != vect.end();
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800138}
139
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700140template<typename T>
141bool VectorIndexOf(const std::vector<T>& vect, const T& value,
142 typename std::vector<T>::size_type* out_index) {
143 typename std::vector<T>::const_iterator it = std::find(vect.begin(),
144 vect.end(),
145 value);
146 if (it == vect.end()) {
147 return false;
148 } else {
149 *out_index = it - vect.begin();
150 return true;
151 }
152}
153
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700154// Returns the currently booted device. "/dev/sda3", for example.
adlr@google.com3defe6a2009-12-04 20:57:17 +0000155// This will not interpret LABEL= or UUID=. You'll need to use findfs
156// or something with equivalent funcionality to interpret those.
157const std::string BootDevice();
158
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700159// Returns the currently booted kernel device, "dev/sda2", for example.
160// Client must pass in the boot device. The suggested calling convention
161// is: BootKernelDevice(BootDevice()).
162// This function works by doing string modification on boot_device.
163// Returns empty string on failure.
164const std::string BootKernelDevice(const std::string& boot_device);
165
166
adlr@google.com3defe6a2009-12-04 20:57:17 +0000167} // namespace utils
168
169// Class to unmount FS when object goes out of scope
170class ScopedFilesystemUnmounter {
171 public:
172 explicit ScopedFilesystemUnmounter(const std::string& mountpoint)
173 : mountpoint_(mountpoint) {}
174 ~ScopedFilesystemUnmounter() {
175 utils::UnmountFilesystem(mountpoint_);
176 }
177 private:
178 const std::string mountpoint_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700179 DISALLOW_COPY_AND_ASSIGN(ScopedFilesystemUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000180};
181
182// Utility class to close a file descriptor
183class ScopedFdCloser {
184 public:
185 explicit ScopedFdCloser(int* fd) : fd_(fd), should_close_(true) {}
186 void set_should_close(bool should_close) { should_close_ = should_close; }
187 ~ScopedFdCloser() {
188 if (!should_close_)
189 return;
190 if (fd_ && (*fd_ >= 0)) {
191 close(*fd_);
192 *fd_ = -1;
193 }
194 }
195 private:
196 int* fd_;
197 bool should_close_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700198 DISALLOW_COPY_AND_ASSIGN(ScopedFdCloser);
199};
200
201// Utility class to delete a file when it goes out of scope.
202class ScopedPathUnlinker {
203 public:
204 explicit ScopedPathUnlinker(const std::string& path) : path_(path) {}
205 ~ScopedPathUnlinker() {
206 if (unlink(path_.c_str()) < 0) {
207 std::string err_message = strerror(errno);
208 LOG(ERROR) << "Unable to unlink path " << path_ << ": " << err_message;
209 }
210 }
211 private:
212 const std::string path_;
213 DISALLOW_COPY_AND_ASSIGN(ScopedPathUnlinker);
214};
215
216// Utility class to delete an empty directory when it goes out of scope.
217class ScopedDirRemover {
218 public:
219 explicit ScopedDirRemover(const std::string& path) : path_(path) {}
220 ~ScopedDirRemover() {
221 if (rmdir(path_.c_str()) < 0)
222 PLOG(ERROR) << "Unable to remove dir " << path_;
223 }
224 private:
225 const std::string path_;
226 DISALLOW_COPY_AND_ASSIGN(ScopedDirRemover);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000227};
228
229// A little object to call ActionComplete on the ActionProcessor when
230// it's destructed.
231class ScopedActionCompleter {
232 public:
233 explicit ScopedActionCompleter(ActionProcessor* processor,
234 AbstractAction* action)
235 : processor_(processor),
236 action_(action),
Darin Petkovc1a8b422010-07-19 11:34:49 -0700237 code_(kActionCodeError),
adlr@google.com3defe6a2009-12-04 20:57:17 +0000238 should_complete_(true) {}
239 ~ScopedActionCompleter() {
240 if (should_complete_)
Darin Petkovc1a8b422010-07-19 11:34:49 -0700241 processor_->ActionComplete(action_, code_);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000242 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700243 void set_code(ActionExitCode code) { code_ = code; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000244 void set_should_complete(bool should_complete) {
245 should_complete_ = should_complete;
246 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700247
adlr@google.com3defe6a2009-12-04 20:57:17 +0000248 private:
249 ActionProcessor* processor_;
250 AbstractAction* action_;
Darin Petkovc1a8b422010-07-19 11:34:49 -0700251 ActionExitCode code_;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000252 bool should_complete_;
253 DISALLOW_COPY_AND_ASSIGN(ScopedActionCompleter);
254};
255
256} // namespace chromeos_update_engine
257
258#define TEST_AND_RETURN_FALSE_ERRNO(_x) \
259 do { \
260 bool _success = (_x); \
261 if (!_success) { \
262 std::string _msg = \
263 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
264 LOG(ERROR) << #_x " failed: " << _msg; \
265 return false; \
266 } \
267 } while (0)
268
269#define TEST_AND_RETURN_FALSE(_x) \
270 do { \
271 bool _success = (_x); \
272 if (!_success) { \
273 LOG(ERROR) << #_x " failed."; \
274 return false; \
275 } \
276 } while (0)
277
278#define TEST_AND_RETURN_ERRNO(_x) \
279 do { \
280 bool _success = (_x); \
281 if (!_success) { \
282 std::string _msg = \
283 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
284 LOG(ERROR) << #_x " failed: " << _msg; \
285 return; \
286 } \
287 } while (0)
288
289#define TEST_AND_RETURN(_x) \
290 do { \
291 bool _success = (_x); \
292 if (!_success) { \
293 LOG(ERROR) << #_x " failed."; \
294 return; \
295 } \
296 } while (0)
297
298
299
300#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_UTILS_H__