blob: bfe73784d9d940e971ed4330d84eba3ff1ece04c [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
Darin Petkov2a0e6332010-09-24 14:43:41 -070030// Returns true if the OOBE process has been completed and EULA accepted, false
31// otherwise.
32bool IsOOBEComplete();
33
Andrew de los Reyes970bb282009-12-09 16:34:04 -080034// Writes the data passed to path. The file at path will be overwritten if it
35// exists. Returns true on success, false otherwise.
36bool WriteFile(const char* path, const char* data, int data_len);
37
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070038// Calls write() or pwrite() repeatedly until all count bytes at buf are
39// written to fd or an error occurs. Returns true on success.
40bool WriteAll(int fd, const void* buf, size_t count);
41bool PWriteAll(int fd, const void* buf, size_t count, off_t offset);
42
43// Calls pread() repeatedly until count bytes are read, or EOF is reached.
44// Returns number of bytes read in *bytes_read. Returns true on success.
45bool PReadAll(int fd, void* buf, size_t count, off_t offset,
46 ssize_t* out_bytes_read);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070047
adlr@google.com3defe6a2009-12-04 20:57:17 +000048// Returns the entire contents of the file at path. Returns true on success.
49bool ReadFile(const std::string& path, std::vector<char>* out);
50bool ReadFileToString(const std::string& path, std::string* out);
51
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070052// Returns the size of the file at path. If the file doesn't exist or some
53// error occurrs, -1 is returned.
54off_t FileSize(const std::string& path);
55
adlr@google.com3defe6a2009-12-04 20:57:17 +000056std::string ErrnoNumberAsString(int err);
57
58// Strips duplicate slashes, and optionally removes all trailing slashes.
59// Does not compact /./ or /../.
60std::string NormalizePath(const std::string& path, bool strip_trailing_slash);
61
62// Returns true if the file exists for sure. Returns false if it doesn't exist,
63// or an error occurs.
64bool FileExists(const char* path);
65
66// The last 6 chars of path must be XXXXXX. They will be randomly changed
67// and a non-existent path will be returned. Intentionally makes a copy
68// of the string passed in.
69// NEVER CALL THIS FUNCTION UNLESS YOU ARE SURE
70// THAT YOUR PROCESS WILL BE THE ONLY THING WRITING FILES IN THIS DIRECTORY.
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -080071std::string TempFilename(std::string path);
adlr@google.com3defe6a2009-12-04 20:57:17 +000072
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070073// Calls mkstemp() with the template passed. Returns the filename in the
74// out param filename. If fd is non-NULL, the file fd returned by mkstemp
75// is not close()d and is returned in the out param 'fd'. However, if
76// fd is NULL, the fd from mkstemp() will be closed.
77// The last six chars of the template must be XXXXXX.
78// Returns true on success.
79bool MakeTempFile(const std::string& filename_template,
80 std::string* filename,
81 int* fd);
82
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070083// Calls mkdtemp() with the tempate passed. Returns the generated dirname
84// in the dirname param. Returns TRUE on success. dirname must not be NULL.
85bool MakeTempDirectory(const std::string& dirname_template,
86 std::string* dirname);
87
adlr@google.com3defe6a2009-12-04 20:57:17 +000088// Deletes a directory and all its contents synchronously. Returns true
89// on success. This may be called with a regular file--it will just unlink it.
90// This WILL cross filesystem boundaries.
91bool RecursiveUnlinkDir(const std::string& path);
92
Andrew de los Reyesf9714432010-05-04 10:21:23 -070093// Returns the root device for a partition. For example,
Darin Petkovf74eb652010-08-04 12:08:38 -070094// RootDevice("/dev/sda3") returns "/dev/sda". Returns an empty string
95// if the input device is not of the "/dev/xyz" form.
Andrew de los Reyesf9714432010-05-04 10:21:23 -070096std::string RootDevice(const std::string& partition_device);
97
98// Returns the partition number, as a string, of partition_device. For example,
Darin Petkovf74eb652010-08-04 12:08:38 -070099// PartitionNumber("/dev/sda3") returns "3".
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700100std::string PartitionNumber(const std::string& partition_device);
101
Darin Petkovf74eb652010-08-04 12:08:38 -0700102// Returns the sysfs block device for a root block device. For
103// example, SysfsBlockDevice("/dev/sda") returns
104// "/sys/block/sda". Returns an empty string if the input device is
105// not of the "/dev/xyz" form.
106std::string SysfsBlockDevice(const std::string& device);
107
108// Returns true if the root |device| (e.g., "/dev/sdb") is known to be
109// removable, false otherwise.
110bool IsRemovableDevice(const std::string& device);
111
adlr@google.com3defe6a2009-12-04 20:57:17 +0000112// Synchronously mount or unmount a filesystem. Return true on success.
113// Mounts as ext3 with default options.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700114bool MountFilesystem(const std::string& device, const std::string& mountpoint,
115 unsigned long flags);
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800116bool UnmountFilesystem(const std::string& mountpoint);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000117
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700118enum BootLoader {
119 BootLoader_SYSLINUX = 0,
120 BootLoader_CHROME_FIRMWARE = 1
121};
122// Detects which bootloader this system uses and returns it via the out
123// param. Returns true on success.
124bool GetBootloader(BootLoader* out_bootloader);
125
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700126// Returns the error message, if any, from a GError pointer.
127const char* GetGErrorMessage(const GError* error);
128
Darin Petkov296889c2010-07-23 16:20:54 -0700129// Initiates a system reboot. Returns true on success, false otherwise.
130bool Reboot();
131
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700132// Fuzzes an integer |value| randomly in the range:
133// [value - range / 2, value + range - range / 2]
134int FuzzInt(int value, unsigned int range);
135
adlr@google.com3defe6a2009-12-04 20:57:17 +0000136// Log a string in hex to LOG(INFO). Useful for debugging.
137void HexDumpArray(const unsigned char* const arr, const size_t length);
138inline void HexDumpString(const std::string& str) {
139 HexDumpArray(reinterpret_cast<const unsigned char*>(str.data()), str.size());
140}
141inline void HexDumpVector(const std::vector<char>& vect) {
142 HexDumpArray(reinterpret_cast<const unsigned char*>(&vect[0]), vect.size());
143}
144
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800145extern const char* const kStatefulPartition;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000146
147bool StringHasSuffix(const std::string& str, const std::string& suffix);
148bool StringHasPrefix(const std::string& str, const std::string& prefix);
149
150template<typename KeyType, typename ValueType>
151bool MapContainsKey(const std::map<KeyType, ValueType>& m, const KeyType& k) {
152 return m.find(k) != m.end();
153}
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800154template<typename KeyType>
155bool SetContainsKey(const std::set<KeyType>& s, const KeyType& k) {
156 return s.find(k) != s.end();
157}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000158
159template<typename ValueType>
160std::set<ValueType> SetWithValue(const ValueType& value) {
161 std::set<ValueType> ret;
162 ret.insert(value);
163 return ret;
164}
165
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800166template<typename T>
167bool VectorContainsValue(const std::vector<T>& vect, const T& value) {
Darin Petkovc1a8b422010-07-19 11:34:49 -0700168 return std::find(vect.begin(), vect.end(), value) != vect.end();
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800169}
170
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700171template<typename T>
172bool VectorIndexOf(const std::vector<T>& vect, const T& value,
173 typename std::vector<T>::size_type* out_index) {
174 typename std::vector<T>::const_iterator it = std::find(vect.begin(),
175 vect.end(),
176 value);
177 if (it == vect.end()) {
178 return false;
179 } else {
180 *out_index = it - vect.begin();
181 return true;
182 }
183}
184
Andrew de los Reyescc92cd32010-10-05 16:56:14 -0700185template<typename ValueType>
186void ApplyMap(std::vector<ValueType>* collection,
187 const std::map<ValueType, ValueType>& the_map) {
188 for (typename std::vector<ValueType>::iterator it = collection->begin();
189 it != collection->end(); ++it) {
190 typename std::map<ValueType, ValueType>::const_iterator map_it =
191 the_map.find(*it);
192 if (map_it != the_map.end()) {
193 *it = map_it->second;
194 }
195 }
196}
197
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700198// Returns the currently booted device. "/dev/sda3", for example.
adlr@google.com3defe6a2009-12-04 20:57:17 +0000199// This will not interpret LABEL= or UUID=. You'll need to use findfs
200// or something with equivalent funcionality to interpret those.
201const std::string BootDevice();
202
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700203// Returns the currently booted kernel device, "dev/sda2", for example.
204// Client must pass in the boot device. The suggested calling convention
205// is: BootKernelDevice(BootDevice()).
206// This function works by doing string modification on boot_device.
207// Returns empty string on failure.
208const std::string BootKernelDevice(const std::string& boot_device);
209
Darin Petkovc6c135c2010-08-11 13:36:18 -0700210enum ProcessPriority {
211 kProcessPriorityHigh = -10,
212 kProcessPriorityNormal = 0,
213 kProcessPriorityLow = 10,
214};
215
216// Compares process priorities and returns an integer that is less
217// than, equal to or greater than 0 if |priority_lhs| is,
218// respectively, lower than, same as or higher than |priority_rhs|.
219int ComparePriorities(ProcessPriority priority_lhs,
220 ProcessPriority priority_rhs);
221
222// Sets the current process priority to |priority|. Returns true on
223// success, false otherwise.
224bool SetProcessPriority(ProcessPriority priority);
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700225
adlr@google.com3defe6a2009-12-04 20:57:17 +0000226} // namespace utils
227
228// Class to unmount FS when object goes out of scope
229class ScopedFilesystemUnmounter {
230 public:
231 explicit ScopedFilesystemUnmounter(const std::string& mountpoint)
232 : mountpoint_(mountpoint) {}
233 ~ScopedFilesystemUnmounter() {
234 utils::UnmountFilesystem(mountpoint_);
235 }
236 private:
237 const std::string mountpoint_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700238 DISALLOW_COPY_AND_ASSIGN(ScopedFilesystemUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000239};
240
241// Utility class to close a file descriptor
242class ScopedFdCloser {
243 public:
244 explicit ScopedFdCloser(int* fd) : fd_(fd), should_close_(true) {}
245 void set_should_close(bool should_close) { should_close_ = should_close; }
246 ~ScopedFdCloser() {
247 if (!should_close_)
248 return;
249 if (fd_ && (*fd_ >= 0)) {
250 close(*fd_);
251 *fd_ = -1;
252 }
253 }
254 private:
255 int* fd_;
256 bool should_close_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700257 DISALLOW_COPY_AND_ASSIGN(ScopedFdCloser);
258};
259
260// Utility class to delete a file when it goes out of scope.
261class ScopedPathUnlinker {
262 public:
263 explicit ScopedPathUnlinker(const std::string& path) : path_(path) {}
264 ~ScopedPathUnlinker() {
265 if (unlink(path_.c_str()) < 0) {
266 std::string err_message = strerror(errno);
267 LOG(ERROR) << "Unable to unlink path " << path_ << ": " << err_message;
268 }
269 }
270 private:
271 const std::string path_;
272 DISALLOW_COPY_AND_ASSIGN(ScopedPathUnlinker);
273};
274
275// Utility class to delete an empty directory when it goes out of scope.
276class ScopedDirRemover {
277 public:
278 explicit ScopedDirRemover(const std::string& path) : path_(path) {}
279 ~ScopedDirRemover() {
280 if (rmdir(path_.c_str()) < 0)
281 PLOG(ERROR) << "Unable to remove dir " << path_;
282 }
283 private:
284 const std::string path_;
285 DISALLOW_COPY_AND_ASSIGN(ScopedDirRemover);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000286};
287
288// A little object to call ActionComplete on the ActionProcessor when
289// it's destructed.
290class ScopedActionCompleter {
291 public:
292 explicit ScopedActionCompleter(ActionProcessor* processor,
293 AbstractAction* action)
294 : processor_(processor),
295 action_(action),
Darin Petkovc1a8b422010-07-19 11:34:49 -0700296 code_(kActionCodeError),
adlr@google.com3defe6a2009-12-04 20:57:17 +0000297 should_complete_(true) {}
298 ~ScopedActionCompleter() {
299 if (should_complete_)
Darin Petkovc1a8b422010-07-19 11:34:49 -0700300 processor_->ActionComplete(action_, code_);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000301 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700302 void set_code(ActionExitCode code) { code_ = code; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000303 void set_should_complete(bool should_complete) {
304 should_complete_ = should_complete;
305 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700306
adlr@google.com3defe6a2009-12-04 20:57:17 +0000307 private:
308 ActionProcessor* processor_;
309 AbstractAction* action_;
Darin Petkovc1a8b422010-07-19 11:34:49 -0700310 ActionExitCode code_;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000311 bool should_complete_;
312 DISALLOW_COPY_AND_ASSIGN(ScopedActionCompleter);
313};
314
315} // namespace chromeos_update_engine
316
317#define TEST_AND_RETURN_FALSE_ERRNO(_x) \
318 do { \
319 bool _success = (_x); \
320 if (!_success) { \
321 std::string _msg = \
322 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
323 LOG(ERROR) << #_x " failed: " << _msg; \
324 return false; \
325 } \
326 } while (0)
327
328#define TEST_AND_RETURN_FALSE(_x) \
329 do { \
330 bool _success = (_x); \
331 if (!_success) { \
332 LOG(ERROR) << #_x " failed."; \
333 return false; \
334 } \
335 } while (0)
336
337#define TEST_AND_RETURN_ERRNO(_x) \
338 do { \
339 bool _success = (_x); \
340 if (!_success) { \
341 std::string _msg = \
342 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
343 LOG(ERROR) << #_x " failed: " << _msg; \
344 return; \
345 } \
346 } while (0)
347
348#define TEST_AND_RETURN(_x) \
349 do { \
350 bool _success = (_x); \
351 if (!_success) { \
352 LOG(ERROR) << #_x " failed."; \
353 return; \
354 } \
355 } while (0)
356
357
358
359#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_UTILS_H__