blob: 8438313808caedffa0181e0eea9899cf3fe4bb22 [file] [log] [blame]
Darin Petkov296889c2010-07-23 16:20:54 -07001// Copyright (c) 2010 The Chromium OS 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>
Darin Petkovc6c135c2010-08-11 13:36:18 -07009
Andrew de los Reyes81ebcd82010-03-09 15:56:18 -080010#include <algorithm>
adlr@google.com3defe6a2009-12-04 20:57:17 +000011#include <set>
12#include <string>
13#include <vector>
Darin Petkovc6c135c2010-08-11 13:36:18 -070014
Andrew de los Reyesc7020782010-04-28 10:46:04 -070015#include <glib.h>
Darin Petkovc6c135c2010-08-11 13:36:18 -070016
adlr@google.com3defe6a2009-12-04 20:57:17 +000017#include "update_engine/action.h"
18#include "update_engine/action_processor.h"
19
20namespace chromeos_update_engine {
21
22namespace utils {
23
Darin Petkov33d30642010-08-04 10:18:57 -070024// Returns true if this is an official Chrome OS build, false
25// otherwise. Currently, this routine errs on the official build side
26// -- if it doesn't recognize the update track as non-official, it
27// assumes the build is official.
28bool IsOfficialBuild();
29
Andrew de los Reyes970bb282009-12-09 16:34:04 -080030// Writes the data passed to path. The file at path will be overwritten if it
31// exists. Returns true on success, false otherwise.
32bool WriteFile(const char* path, const char* data, int data_len);
33
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070034// Calls write() or pwrite() repeatedly until all count bytes at buf are
35// written to fd or an error occurs. Returns true on success.
36bool WriteAll(int fd, const void* buf, size_t count);
37bool PWriteAll(int fd, const void* buf, size_t count, off_t offset);
38
39// Calls pread() repeatedly until count bytes are read, or EOF is reached.
40// Returns number of bytes read in *bytes_read. Returns true on success.
41bool PReadAll(int fd, void* buf, size_t count, off_t offset,
42 ssize_t* out_bytes_read);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070043
adlr@google.com3defe6a2009-12-04 20:57:17 +000044// Returns the entire contents of the file at path. Returns true on success.
45bool ReadFile(const std::string& path, std::vector<char>* out);
46bool ReadFileToString(const std::string& path, std::string* out);
47
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070048// Returns the size of the file at path. If the file doesn't exist or some
49// error occurrs, -1 is returned.
50off_t FileSize(const std::string& path);
51
adlr@google.com3defe6a2009-12-04 20:57:17 +000052std::string ErrnoNumberAsString(int err);
53
54// Strips duplicate slashes, and optionally removes all trailing slashes.
55// Does not compact /./ or /../.
56std::string NormalizePath(const std::string& path, bool strip_trailing_slash);
57
58// Returns true if the file exists for sure. Returns false if it doesn't exist,
59// or an error occurs.
60bool FileExists(const char* path);
61
62// The last 6 chars of path must be XXXXXX. They will be randomly changed
63// and a non-existent path will be returned. Intentionally makes a copy
64// of the string passed in.
65// NEVER CALL THIS FUNCTION UNLESS YOU ARE SURE
66// THAT YOUR PROCESS WILL BE THE ONLY THING WRITING FILES IN THIS DIRECTORY.
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -080067std::string TempFilename(std::string path);
adlr@google.com3defe6a2009-12-04 20:57:17 +000068
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070069// Calls mkstemp() with the template passed. Returns the filename in the
70// out param filename. If fd is non-NULL, the file fd returned by mkstemp
71// is not close()d and is returned in the out param 'fd'. However, if
72// fd is NULL, the fd from mkstemp() will be closed.
73// The last six chars of the template must be XXXXXX.
74// Returns true on success.
75bool MakeTempFile(const std::string& filename_template,
76 std::string* filename,
77 int* fd);
78
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070079// Calls mkdtemp() with the tempate passed. Returns the generated dirname
80// in the dirname param. Returns TRUE on success. dirname must not be NULL.
81bool MakeTempDirectory(const std::string& dirname_template,
82 std::string* dirname);
83
adlr@google.com3defe6a2009-12-04 20:57:17 +000084// Deletes a directory and all its contents synchronously. Returns true
85// on success. This may be called with a regular file--it will just unlink it.
86// This WILL cross filesystem boundaries.
87bool RecursiveUnlinkDir(const std::string& path);
88
Andrew de los Reyesf9714432010-05-04 10:21:23 -070089// Returns the root device for a partition. For example,
Darin Petkovf74eb652010-08-04 12:08:38 -070090// RootDevice("/dev/sda3") returns "/dev/sda". Returns an empty string
91// if the input device is not of the "/dev/xyz" form.
Andrew de los Reyesf9714432010-05-04 10:21:23 -070092std::string RootDevice(const std::string& partition_device);
93
94// Returns the partition number, as a string, of partition_device. For example,
Darin Petkovf74eb652010-08-04 12:08:38 -070095// PartitionNumber("/dev/sda3") returns "3".
Andrew de los Reyesf9714432010-05-04 10:21:23 -070096std::string PartitionNumber(const std::string& partition_device);
97
Darin Petkovf74eb652010-08-04 12:08:38 -070098// Returns the sysfs block device for a root block device. For
99// example, SysfsBlockDevice("/dev/sda") returns
100// "/sys/block/sda". Returns an empty string if the input device is
101// not of the "/dev/xyz" form.
102std::string SysfsBlockDevice(const std::string& device);
103
104// Returns true if the root |device| (e.g., "/dev/sdb") is known to be
105// removable, false otherwise.
106bool IsRemovableDevice(const std::string& device);
107
adlr@google.com3defe6a2009-12-04 20:57:17 +0000108// Synchronously mount or unmount a filesystem. Return true on success.
109// Mounts as ext3 with default options.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700110bool MountFilesystem(const std::string& device, const std::string& mountpoint,
111 unsigned long flags);
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800112bool UnmountFilesystem(const std::string& mountpoint);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000113
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700114enum BootLoader {
115 BootLoader_SYSLINUX = 0,
116 BootLoader_CHROME_FIRMWARE = 1
117};
118// Detects which bootloader this system uses and returns it via the out
119// param. Returns true on success.
120bool GetBootloader(BootLoader* out_bootloader);
121
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700122// Returns the error message, if any, from a GError pointer.
123const char* GetGErrorMessage(const GError* error);
124
Darin Petkov296889c2010-07-23 16:20:54 -0700125// Initiates a system reboot. Returns true on success, false otherwise.
126bool Reboot();
127
adlr@google.com3defe6a2009-12-04 20:57:17 +0000128// Log a string in hex to LOG(INFO). Useful for debugging.
129void HexDumpArray(const unsigned char* const arr, const size_t length);
130inline void HexDumpString(const std::string& str) {
131 HexDumpArray(reinterpret_cast<const unsigned char*>(str.data()), str.size());
132}
133inline void HexDumpVector(const std::vector<char>& vect) {
134 HexDumpArray(reinterpret_cast<const unsigned char*>(&vect[0]), vect.size());
135}
136
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800137extern const char* const kStatefulPartition;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000138
139bool StringHasSuffix(const std::string& str, const std::string& suffix);
140bool StringHasPrefix(const std::string& str, const std::string& prefix);
141
142template<typename KeyType, typename ValueType>
143bool MapContainsKey(const std::map<KeyType, ValueType>& m, const KeyType& k) {
144 return m.find(k) != m.end();
145}
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800146template<typename KeyType>
147bool SetContainsKey(const std::set<KeyType>& s, const KeyType& k) {
148 return s.find(k) != s.end();
149}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000150
151template<typename ValueType>
152std::set<ValueType> SetWithValue(const ValueType& value) {
153 std::set<ValueType> ret;
154 ret.insert(value);
155 return ret;
156}
157
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800158template<typename T>
159bool VectorContainsValue(const std::vector<T>& vect, const T& value) {
Darin Petkovc1a8b422010-07-19 11:34:49 -0700160 return std::find(vect.begin(), vect.end(), value) != vect.end();
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800161}
162
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700163template<typename T>
164bool VectorIndexOf(const std::vector<T>& vect, const T& value,
165 typename std::vector<T>::size_type* out_index) {
166 typename std::vector<T>::const_iterator it = std::find(vect.begin(),
167 vect.end(),
168 value);
169 if (it == vect.end()) {
170 return false;
171 } else {
172 *out_index = it - vect.begin();
173 return true;
174 }
175}
176
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700177// Returns the currently booted device. "/dev/sda3", for example.
adlr@google.com3defe6a2009-12-04 20:57:17 +0000178// This will not interpret LABEL= or UUID=. You'll need to use findfs
179// or something with equivalent funcionality to interpret those.
180const std::string BootDevice();
181
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700182// Returns the currently booted kernel device, "dev/sda2", for example.
183// Client must pass in the boot device. The suggested calling convention
184// is: BootKernelDevice(BootDevice()).
185// This function works by doing string modification on boot_device.
186// Returns empty string on failure.
187const std::string BootKernelDevice(const std::string& boot_device);
188
Darin Petkovc6c135c2010-08-11 13:36:18 -0700189enum ProcessPriority {
190 kProcessPriorityHigh = -10,
191 kProcessPriorityNormal = 0,
192 kProcessPriorityLow = 10,
193};
194
195// Compares process priorities and returns an integer that is less
196// than, equal to or greater than 0 if |priority_lhs| is,
197// respectively, lower than, same as or higher than |priority_rhs|.
198int ComparePriorities(ProcessPriority priority_lhs,
199 ProcessPriority priority_rhs);
200
201// Sets the current process priority to |priority|. Returns true on
202// success, false otherwise.
203bool SetProcessPriority(ProcessPriority priority);
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700204
adlr@google.com3defe6a2009-12-04 20:57:17 +0000205} // namespace utils
206
207// Class to unmount FS when object goes out of scope
208class ScopedFilesystemUnmounter {
209 public:
210 explicit ScopedFilesystemUnmounter(const std::string& mountpoint)
211 : mountpoint_(mountpoint) {}
212 ~ScopedFilesystemUnmounter() {
213 utils::UnmountFilesystem(mountpoint_);
214 }
215 private:
216 const std::string mountpoint_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700217 DISALLOW_COPY_AND_ASSIGN(ScopedFilesystemUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000218};
219
220// Utility class to close a file descriptor
221class ScopedFdCloser {
222 public:
223 explicit ScopedFdCloser(int* fd) : fd_(fd), should_close_(true) {}
224 void set_should_close(bool should_close) { should_close_ = should_close; }
225 ~ScopedFdCloser() {
226 if (!should_close_)
227 return;
228 if (fd_ && (*fd_ >= 0)) {
229 close(*fd_);
230 *fd_ = -1;
231 }
232 }
233 private:
234 int* fd_;
235 bool should_close_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700236 DISALLOW_COPY_AND_ASSIGN(ScopedFdCloser);
237};
238
239// Utility class to delete a file when it goes out of scope.
240class ScopedPathUnlinker {
241 public:
242 explicit ScopedPathUnlinker(const std::string& path) : path_(path) {}
243 ~ScopedPathUnlinker() {
244 if (unlink(path_.c_str()) < 0) {
245 std::string err_message = strerror(errno);
246 LOG(ERROR) << "Unable to unlink path " << path_ << ": " << err_message;
247 }
248 }
249 private:
250 const std::string path_;
251 DISALLOW_COPY_AND_ASSIGN(ScopedPathUnlinker);
252};
253
254// Utility class to delete an empty directory when it goes out of scope.
255class ScopedDirRemover {
256 public:
257 explicit ScopedDirRemover(const std::string& path) : path_(path) {}
258 ~ScopedDirRemover() {
259 if (rmdir(path_.c_str()) < 0)
260 PLOG(ERROR) << "Unable to remove dir " << path_;
261 }
262 private:
263 const std::string path_;
264 DISALLOW_COPY_AND_ASSIGN(ScopedDirRemover);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000265};
266
267// A little object to call ActionComplete on the ActionProcessor when
268// it's destructed.
269class ScopedActionCompleter {
270 public:
271 explicit ScopedActionCompleter(ActionProcessor* processor,
272 AbstractAction* action)
273 : processor_(processor),
274 action_(action),
Darin Petkovc1a8b422010-07-19 11:34:49 -0700275 code_(kActionCodeError),
adlr@google.com3defe6a2009-12-04 20:57:17 +0000276 should_complete_(true) {}
277 ~ScopedActionCompleter() {
278 if (should_complete_)
Darin Petkovc1a8b422010-07-19 11:34:49 -0700279 processor_->ActionComplete(action_, code_);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000280 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700281 void set_code(ActionExitCode code) { code_ = code; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000282 void set_should_complete(bool should_complete) {
283 should_complete_ = should_complete;
284 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700285
adlr@google.com3defe6a2009-12-04 20:57:17 +0000286 private:
287 ActionProcessor* processor_;
288 AbstractAction* action_;
Darin Petkovc1a8b422010-07-19 11:34:49 -0700289 ActionExitCode code_;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000290 bool should_complete_;
291 DISALLOW_COPY_AND_ASSIGN(ScopedActionCompleter);
292};
293
294} // namespace chromeos_update_engine
295
296#define TEST_AND_RETURN_FALSE_ERRNO(_x) \
297 do { \
298 bool _success = (_x); \
299 if (!_success) { \
300 std::string _msg = \
301 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
302 LOG(ERROR) << #_x " failed: " << _msg; \
303 return false; \
304 } \
305 } while (0)
306
307#define TEST_AND_RETURN_FALSE(_x) \
308 do { \
309 bool _success = (_x); \
310 if (!_success) { \
311 LOG(ERROR) << #_x " failed."; \
312 return false; \
313 } \
314 } while (0)
315
316#define TEST_AND_RETURN_ERRNO(_x) \
317 do { \
318 bool _success = (_x); \
319 if (!_success) { \
320 std::string _msg = \
321 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
322 LOG(ERROR) << #_x " failed: " << _msg; \
323 return; \
324 } \
325 } while (0)
326
327#define TEST_AND_RETURN(_x) \
328 do { \
329 bool _success = (_x); \
330 if (!_success) { \
331 LOG(ERROR) << #_x " failed."; \
332 return; \
333 } \
334 } while (0)
335
336
337
338#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_UTILS_H__