blob: 9beae04b9bb025ed1782c57db4efc7562e49c4e0 [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
Darin Petkovd3f8c892010-10-12 21:38:45 -0700118// Returns the block count and the block byte size of the ext3 file system on
119// |device| (which may be a real device or a path to a filesystem image) or on
120// an opened file descriptor |fd|. The actual file-system size is |block_count|
121// * |block_size| bytes. Returns true on success, false otherwise.
122bool GetFilesystemSize(const std::string& device,
123 int* out_block_count,
124 int* out_block_size);
125bool GetFilesystemSizeFromFD(int fd,
126 int* out_block_count,
127 int* out_block_size);
128
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700129enum BootLoader {
130 BootLoader_SYSLINUX = 0,
131 BootLoader_CHROME_FIRMWARE = 1
132};
133// Detects which bootloader this system uses and returns it via the out
134// param. Returns true on success.
135bool GetBootloader(BootLoader* out_bootloader);
136
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700137// Returns the error message, if any, from a GError pointer.
138const char* GetGErrorMessage(const GError* error);
139
Darin Petkov296889c2010-07-23 16:20:54 -0700140// Initiates a system reboot. Returns true on success, false otherwise.
141bool Reboot();
142
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700143// Fuzzes an integer |value| randomly in the range:
144// [value - range / 2, value + range - range / 2]
145int FuzzInt(int value, unsigned int range);
146
adlr@google.com3defe6a2009-12-04 20:57:17 +0000147// Log a string in hex to LOG(INFO). Useful for debugging.
148void HexDumpArray(const unsigned char* const arr, const size_t length);
149inline void HexDumpString(const std::string& str) {
150 HexDumpArray(reinterpret_cast<const unsigned char*>(str.data()), str.size());
151}
152inline void HexDumpVector(const std::vector<char>& vect) {
153 HexDumpArray(reinterpret_cast<const unsigned char*>(&vect[0]), vect.size());
154}
155
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800156extern const char* const kStatefulPartition;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000157
158bool StringHasSuffix(const std::string& str, const std::string& suffix);
159bool StringHasPrefix(const std::string& str, const std::string& prefix);
160
161template<typename KeyType, typename ValueType>
162bool MapContainsKey(const std::map<KeyType, ValueType>& m, const KeyType& k) {
163 return m.find(k) != m.end();
164}
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800165template<typename KeyType>
166bool SetContainsKey(const std::set<KeyType>& s, const KeyType& k) {
167 return s.find(k) != s.end();
168}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000169
170template<typename ValueType>
171std::set<ValueType> SetWithValue(const ValueType& value) {
172 std::set<ValueType> ret;
173 ret.insert(value);
174 return ret;
175}
176
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800177template<typename T>
178bool VectorContainsValue(const std::vector<T>& vect, const T& value) {
Darin Petkovc1a8b422010-07-19 11:34:49 -0700179 return std::find(vect.begin(), vect.end(), value) != vect.end();
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800180}
181
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700182template<typename T>
183bool VectorIndexOf(const std::vector<T>& vect, const T& value,
184 typename std::vector<T>::size_type* out_index) {
185 typename std::vector<T>::const_iterator it = std::find(vect.begin(),
186 vect.end(),
187 value);
188 if (it == vect.end()) {
189 return false;
190 } else {
191 *out_index = it - vect.begin();
192 return true;
193 }
194}
195
Andrew de los Reyescc92cd32010-10-05 16:56:14 -0700196template<typename ValueType>
197void ApplyMap(std::vector<ValueType>* collection,
198 const std::map<ValueType, ValueType>& the_map) {
199 for (typename std::vector<ValueType>::iterator it = collection->begin();
200 it != collection->end(); ++it) {
201 typename std::map<ValueType, ValueType>::const_iterator map_it =
202 the_map.find(*it);
203 if (map_it != the_map.end()) {
204 *it = map_it->second;
205 }
206 }
207}
208
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700209// Returns the currently booted device. "/dev/sda3", for example.
adlr@google.com3defe6a2009-12-04 20:57:17 +0000210// This will not interpret LABEL= or UUID=. You'll need to use findfs
211// or something with equivalent funcionality to interpret those.
212const std::string BootDevice();
213
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700214// Returns the currently booted kernel device, "dev/sda2", for example.
215// Client must pass in the boot device. The suggested calling convention
216// is: BootKernelDevice(BootDevice()).
217// This function works by doing string modification on boot_device.
218// Returns empty string on failure.
219const std::string BootKernelDevice(const std::string& boot_device);
220
Darin Petkovc6c135c2010-08-11 13:36:18 -0700221enum ProcessPriority {
222 kProcessPriorityHigh = -10,
223 kProcessPriorityNormal = 0,
224 kProcessPriorityLow = 10,
225};
226
227// Compares process priorities and returns an integer that is less
228// than, equal to or greater than 0 if |priority_lhs| is,
229// respectively, lower than, same as or higher than |priority_rhs|.
230int ComparePriorities(ProcessPriority priority_lhs,
231 ProcessPriority priority_rhs);
232
233// Sets the current process priority to |priority|. Returns true on
234// success, false otherwise.
235bool SetProcessPriority(ProcessPriority priority);
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700236
adlr@google.com3defe6a2009-12-04 20:57:17 +0000237} // namespace utils
238
239// Class to unmount FS when object goes out of scope
240class ScopedFilesystemUnmounter {
241 public:
242 explicit ScopedFilesystemUnmounter(const std::string& mountpoint)
243 : mountpoint_(mountpoint) {}
244 ~ScopedFilesystemUnmounter() {
245 utils::UnmountFilesystem(mountpoint_);
246 }
247 private:
248 const std::string mountpoint_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700249 DISALLOW_COPY_AND_ASSIGN(ScopedFilesystemUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000250};
251
252// Utility class to close a file descriptor
253class ScopedFdCloser {
254 public:
255 explicit ScopedFdCloser(int* fd) : fd_(fd), should_close_(true) {}
256 void set_should_close(bool should_close) { should_close_ = should_close; }
257 ~ScopedFdCloser() {
258 if (!should_close_)
259 return;
260 if (fd_ && (*fd_ >= 0)) {
261 close(*fd_);
262 *fd_ = -1;
263 }
264 }
265 private:
266 int* fd_;
267 bool should_close_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700268 DISALLOW_COPY_AND_ASSIGN(ScopedFdCloser);
269};
270
271// Utility class to delete a file when it goes out of scope.
272class ScopedPathUnlinker {
273 public:
274 explicit ScopedPathUnlinker(const std::string& path) : path_(path) {}
275 ~ScopedPathUnlinker() {
276 if (unlink(path_.c_str()) < 0) {
277 std::string err_message = strerror(errno);
278 LOG(ERROR) << "Unable to unlink path " << path_ << ": " << err_message;
279 }
280 }
281 private:
282 const std::string path_;
283 DISALLOW_COPY_AND_ASSIGN(ScopedPathUnlinker);
284};
285
286// Utility class to delete an empty directory when it goes out of scope.
287class ScopedDirRemover {
288 public:
289 explicit ScopedDirRemover(const std::string& path) : path_(path) {}
290 ~ScopedDirRemover() {
291 if (rmdir(path_.c_str()) < 0)
292 PLOG(ERROR) << "Unable to remove dir " << path_;
293 }
294 private:
295 const std::string path_;
296 DISALLOW_COPY_AND_ASSIGN(ScopedDirRemover);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000297};
298
299// A little object to call ActionComplete on the ActionProcessor when
300// it's destructed.
301class ScopedActionCompleter {
302 public:
303 explicit ScopedActionCompleter(ActionProcessor* processor,
304 AbstractAction* action)
305 : processor_(processor),
306 action_(action),
Darin Petkovc1a8b422010-07-19 11:34:49 -0700307 code_(kActionCodeError),
adlr@google.com3defe6a2009-12-04 20:57:17 +0000308 should_complete_(true) {}
309 ~ScopedActionCompleter() {
310 if (should_complete_)
Darin Petkovc1a8b422010-07-19 11:34:49 -0700311 processor_->ActionComplete(action_, code_);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000312 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700313 void set_code(ActionExitCode code) { code_ = code; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000314 void set_should_complete(bool should_complete) {
315 should_complete_ = should_complete;
316 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700317
adlr@google.com3defe6a2009-12-04 20:57:17 +0000318 private:
319 ActionProcessor* processor_;
320 AbstractAction* action_;
Darin Petkovc1a8b422010-07-19 11:34:49 -0700321 ActionExitCode code_;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000322 bool should_complete_;
323 DISALLOW_COPY_AND_ASSIGN(ScopedActionCompleter);
324};
325
326} // namespace chromeos_update_engine
327
328#define TEST_AND_RETURN_FALSE_ERRNO(_x) \
329 do { \
330 bool _success = (_x); \
331 if (!_success) { \
332 std::string _msg = \
333 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
334 LOG(ERROR) << #_x " failed: " << _msg; \
335 return false; \
336 } \
337 } while (0)
338
339#define TEST_AND_RETURN_FALSE(_x) \
340 do { \
341 bool _success = (_x); \
342 if (!_success) { \
343 LOG(ERROR) << #_x " failed."; \
344 return false; \
345 } \
346 } while (0)
347
348#define TEST_AND_RETURN_ERRNO(_x) \
349 do { \
350 bool _success = (_x); \
351 if (!_success) { \
352 std::string _msg = \
353 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
354 LOG(ERROR) << #_x " failed: " << _msg; \
355 return; \
356 } \
357 } while (0)
358
359#define TEST_AND_RETURN(_x) \
360 do { \
361 bool _success = (_x); \
362 if (!_success) { \
363 LOG(ERROR) << #_x " failed."; \
364 return; \
365 } \
366 } while (0)
367
368
369
370#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_UTILS_H__