blob: 57fb3bb36adc735f32cbccc0615f14b065bcf3e3 [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 Petkova07586b2010-10-20 13:41:15 -070024// Returns true if this is an official Chrome OS build, false otherwise.
Darin Petkov33d30642010-08-04 10:18:57 -070025bool IsOfficialBuild();
26
Darin Petkov2a0e6332010-09-24 14:43:41 -070027// Returns true if the OOBE process has been completed and EULA accepted, false
28// otherwise.
29bool IsOOBEComplete();
30
Andrew de los Reyes970bb282009-12-09 16:34:04 -080031// Writes the data passed to path. The file at path will be overwritten if it
32// exists. Returns true on success, false otherwise.
33bool WriteFile(const char* path, const char* data, int data_len);
34
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070035// Calls write() or pwrite() repeatedly until all count bytes at buf are
36// written to fd or an error occurs. Returns true on success.
37bool WriteAll(int fd, const void* buf, size_t count);
38bool PWriteAll(int fd, const void* buf, size_t count, off_t offset);
39
40// Calls pread() repeatedly until count bytes are read, or EOF is reached.
41// Returns number of bytes read in *bytes_read. Returns true on success.
42bool PReadAll(int fd, void* buf, size_t count, off_t offset,
43 ssize_t* out_bytes_read);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070044
adlr@google.com3defe6a2009-12-04 20:57:17 +000045// Returns the entire contents of the file at path. Returns true on success.
46bool ReadFile(const std::string& path, std::vector<char>* out);
47bool ReadFileToString(const std::string& path, std::string* out);
48
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070049// Returns the size of the file at path. If the file doesn't exist or some
50// error occurrs, -1 is returned.
51off_t FileSize(const std::string& path);
52
adlr@google.com3defe6a2009-12-04 20:57:17 +000053std::string ErrnoNumberAsString(int err);
54
55// Strips duplicate slashes, and optionally removes all trailing slashes.
56// Does not compact /./ or /../.
57std::string NormalizePath(const std::string& path, bool strip_trailing_slash);
58
59// Returns true if the file exists for sure. Returns false if it doesn't exist,
60// or an error occurs.
61bool FileExists(const char* path);
62
63// The last 6 chars of path must be XXXXXX. They will be randomly changed
64// and a non-existent path will be returned. Intentionally makes a copy
65// of the string passed in.
66// NEVER CALL THIS FUNCTION UNLESS YOU ARE SURE
67// THAT YOUR PROCESS WILL BE THE ONLY THING WRITING FILES IN THIS DIRECTORY.
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -080068std::string TempFilename(std::string path);
adlr@google.com3defe6a2009-12-04 20:57:17 +000069
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070070// Calls mkstemp() with the template passed. Returns the filename in the
71// out param filename. If fd is non-NULL, the file fd returned by mkstemp
72// is not close()d and is returned in the out param 'fd'. However, if
73// fd is NULL, the fd from mkstemp() will be closed.
74// The last six chars of the template must be XXXXXX.
75// Returns true on success.
76bool MakeTempFile(const std::string& filename_template,
77 std::string* filename,
78 int* fd);
79
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070080// Calls mkdtemp() with the tempate passed. Returns the generated dirname
81// in the dirname param. Returns TRUE on success. dirname must not be NULL.
82bool MakeTempDirectory(const std::string& dirname_template,
83 std::string* dirname);
84
adlr@google.com3defe6a2009-12-04 20:57:17 +000085// Deletes a directory and all its contents synchronously. Returns true
86// on success. This may be called with a regular file--it will just unlink it.
87// This WILL cross filesystem boundaries.
88bool RecursiveUnlinkDir(const std::string& path);
89
Andrew de los Reyesf9714432010-05-04 10:21:23 -070090// Returns the root device for a partition. For example,
Darin Petkovf74eb652010-08-04 12:08:38 -070091// RootDevice("/dev/sda3") returns "/dev/sda". Returns an empty string
92// if the input device is not of the "/dev/xyz" form.
Andrew de los Reyesf9714432010-05-04 10:21:23 -070093std::string RootDevice(const std::string& partition_device);
94
95// Returns the partition number, as a string, of partition_device. For example,
Darin Petkovf74eb652010-08-04 12:08:38 -070096// PartitionNumber("/dev/sda3") returns "3".
Andrew de los Reyesf9714432010-05-04 10:21:23 -070097std::string PartitionNumber(const std::string& partition_device);
98
Darin Petkovf74eb652010-08-04 12:08:38 -070099// Returns the sysfs block device for a root block device. For
100// example, SysfsBlockDevice("/dev/sda") returns
101// "/sys/block/sda". Returns an empty string if the input device is
102// not of the "/dev/xyz" form.
103std::string SysfsBlockDevice(const std::string& device);
104
105// Returns true if the root |device| (e.g., "/dev/sdb") is known to be
106// removable, false otherwise.
107bool IsRemovableDevice(const std::string& device);
108
adlr@google.com3defe6a2009-12-04 20:57:17 +0000109// Synchronously mount or unmount a filesystem. Return true on success.
110// Mounts as ext3 with default options.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700111bool MountFilesystem(const std::string& device, const std::string& mountpoint,
112 unsigned long flags);
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800113bool UnmountFilesystem(const std::string& mountpoint);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000114
Darin Petkovd3f8c892010-10-12 21:38:45 -0700115// Returns the block count and the block byte size of the ext3 file system on
116// |device| (which may be a real device or a path to a filesystem image) or on
117// an opened file descriptor |fd|. The actual file-system size is |block_count|
118// * |block_size| bytes. Returns true on success, false otherwise.
119bool GetFilesystemSize(const std::string& device,
120 int* out_block_count,
121 int* out_block_size);
122bool GetFilesystemSizeFromFD(int fd,
123 int* out_block_count,
124 int* out_block_size);
125
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700126enum BootLoader {
127 BootLoader_SYSLINUX = 0,
128 BootLoader_CHROME_FIRMWARE = 1
129};
130// Detects which bootloader this system uses and returns it via the out
131// param. Returns true on success.
132bool GetBootloader(BootLoader* out_bootloader);
133
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700134// Returns the error message, if any, from a GError pointer.
135const char* GetGErrorMessage(const GError* error);
136
Darin Petkov296889c2010-07-23 16:20:54 -0700137// Initiates a system reboot. Returns true on success, false otherwise.
138bool Reboot();
139
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700140// Fuzzes an integer |value| randomly in the range:
141// [value - range / 2, value + range - range / 2]
142int FuzzInt(int value, unsigned int range);
143
adlr@google.com3defe6a2009-12-04 20:57:17 +0000144// Log a string in hex to LOG(INFO). Useful for debugging.
145void HexDumpArray(const unsigned char* const arr, const size_t length);
146inline void HexDumpString(const std::string& str) {
147 HexDumpArray(reinterpret_cast<const unsigned char*>(str.data()), str.size());
148}
149inline void HexDumpVector(const std::vector<char>& vect) {
150 HexDumpArray(reinterpret_cast<const unsigned char*>(&vect[0]), vect.size());
151}
152
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800153extern const char* const kStatefulPartition;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000154
155bool StringHasSuffix(const std::string& str, const std::string& suffix);
156bool StringHasPrefix(const std::string& str, const std::string& prefix);
157
158template<typename KeyType, typename ValueType>
159bool MapContainsKey(const std::map<KeyType, ValueType>& m, const KeyType& k) {
160 return m.find(k) != m.end();
161}
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800162template<typename KeyType>
163bool SetContainsKey(const std::set<KeyType>& s, const KeyType& k) {
164 return s.find(k) != s.end();
165}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000166
167template<typename ValueType>
168std::set<ValueType> SetWithValue(const ValueType& value) {
169 std::set<ValueType> ret;
170 ret.insert(value);
171 return ret;
172}
173
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800174template<typename T>
175bool VectorContainsValue(const std::vector<T>& vect, const T& value) {
Darin Petkovc1a8b422010-07-19 11:34:49 -0700176 return std::find(vect.begin(), vect.end(), value) != vect.end();
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800177}
178
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700179template<typename T>
180bool VectorIndexOf(const std::vector<T>& vect, const T& value,
181 typename std::vector<T>::size_type* out_index) {
182 typename std::vector<T>::const_iterator it = std::find(vect.begin(),
183 vect.end(),
184 value);
185 if (it == vect.end()) {
186 return false;
187 } else {
188 *out_index = it - vect.begin();
189 return true;
190 }
191}
192
Andrew de los Reyescc92cd32010-10-05 16:56:14 -0700193template<typename ValueType>
194void ApplyMap(std::vector<ValueType>* collection,
195 const std::map<ValueType, ValueType>& the_map) {
196 for (typename std::vector<ValueType>::iterator it = collection->begin();
197 it != collection->end(); ++it) {
198 typename std::map<ValueType, ValueType>::const_iterator map_it =
199 the_map.find(*it);
200 if (map_it != the_map.end()) {
201 *it = map_it->second;
202 }
203 }
204}
205
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700206// Returns the currently booted device. "/dev/sda3", for example.
adlr@google.com3defe6a2009-12-04 20:57:17 +0000207// This will not interpret LABEL= or UUID=. You'll need to use findfs
208// or something with equivalent funcionality to interpret those.
209const std::string BootDevice();
210
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700211// Returns the currently booted kernel device, "dev/sda2", for example.
212// Client must pass in the boot device. The suggested calling convention
213// is: BootKernelDevice(BootDevice()).
214// This function works by doing string modification on boot_device.
215// Returns empty string on failure.
216const std::string BootKernelDevice(const std::string& boot_device);
217
Darin Petkovc6c135c2010-08-11 13:36:18 -0700218enum ProcessPriority {
219 kProcessPriorityHigh = -10,
220 kProcessPriorityNormal = 0,
221 kProcessPriorityLow = 10,
222};
223
224// Compares process priorities and returns an integer that is less
225// than, equal to or greater than 0 if |priority_lhs| is,
226// respectively, lower than, same as or higher than |priority_rhs|.
227int ComparePriorities(ProcessPriority priority_lhs,
228 ProcessPriority priority_rhs);
229
230// Sets the current process priority to |priority|. Returns true on
231// success, false otherwise.
232bool SetProcessPriority(ProcessPriority priority);
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700233
adlr@google.com3defe6a2009-12-04 20:57:17 +0000234} // namespace utils
235
236// Class to unmount FS when object goes out of scope
237class ScopedFilesystemUnmounter {
238 public:
239 explicit ScopedFilesystemUnmounter(const std::string& mountpoint)
240 : mountpoint_(mountpoint) {}
241 ~ScopedFilesystemUnmounter() {
242 utils::UnmountFilesystem(mountpoint_);
243 }
244 private:
245 const std::string mountpoint_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700246 DISALLOW_COPY_AND_ASSIGN(ScopedFilesystemUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000247};
248
249// Utility class to close a file descriptor
250class ScopedFdCloser {
251 public:
252 explicit ScopedFdCloser(int* fd) : fd_(fd), should_close_(true) {}
253 void set_should_close(bool should_close) { should_close_ = should_close; }
254 ~ScopedFdCloser() {
255 if (!should_close_)
256 return;
257 if (fd_ && (*fd_ >= 0)) {
258 close(*fd_);
259 *fd_ = -1;
260 }
261 }
262 private:
263 int* fd_;
264 bool should_close_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700265 DISALLOW_COPY_AND_ASSIGN(ScopedFdCloser);
266};
267
268// Utility class to delete a file when it goes out of scope.
269class ScopedPathUnlinker {
270 public:
271 explicit ScopedPathUnlinker(const std::string& path) : path_(path) {}
272 ~ScopedPathUnlinker() {
273 if (unlink(path_.c_str()) < 0) {
274 std::string err_message = strerror(errno);
275 LOG(ERROR) << "Unable to unlink path " << path_ << ": " << err_message;
276 }
277 }
278 private:
279 const std::string path_;
280 DISALLOW_COPY_AND_ASSIGN(ScopedPathUnlinker);
281};
282
283// Utility class to delete an empty directory when it goes out of scope.
284class ScopedDirRemover {
285 public:
286 explicit ScopedDirRemover(const std::string& path) : path_(path) {}
287 ~ScopedDirRemover() {
288 if (rmdir(path_.c_str()) < 0)
289 PLOG(ERROR) << "Unable to remove dir " << path_;
290 }
291 private:
292 const std::string path_;
293 DISALLOW_COPY_AND_ASSIGN(ScopedDirRemover);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000294};
295
296// A little object to call ActionComplete on the ActionProcessor when
297// it's destructed.
298class ScopedActionCompleter {
299 public:
300 explicit ScopedActionCompleter(ActionProcessor* processor,
301 AbstractAction* action)
302 : processor_(processor),
303 action_(action),
Darin Petkovc1a8b422010-07-19 11:34:49 -0700304 code_(kActionCodeError),
adlr@google.com3defe6a2009-12-04 20:57:17 +0000305 should_complete_(true) {}
306 ~ScopedActionCompleter() {
307 if (should_complete_)
Darin Petkovc1a8b422010-07-19 11:34:49 -0700308 processor_->ActionComplete(action_, code_);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000309 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700310 void set_code(ActionExitCode code) { code_ = code; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000311 void set_should_complete(bool should_complete) {
312 should_complete_ = should_complete;
313 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700314
adlr@google.com3defe6a2009-12-04 20:57:17 +0000315 private:
316 ActionProcessor* processor_;
317 AbstractAction* action_;
Darin Petkovc1a8b422010-07-19 11:34:49 -0700318 ActionExitCode code_;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000319 bool should_complete_;
320 DISALLOW_COPY_AND_ASSIGN(ScopedActionCompleter);
321};
322
323} // namespace chromeos_update_engine
324
325#define TEST_AND_RETURN_FALSE_ERRNO(_x) \
326 do { \
327 bool _success = (_x); \
328 if (!_success) { \
329 std::string _msg = \
330 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
331 LOG(ERROR) << #_x " failed: " << _msg; \
332 return false; \
333 } \
334 } while (0)
335
336#define TEST_AND_RETURN_FALSE(_x) \
337 do { \
338 bool _success = (_x); \
339 if (!_success) { \
340 LOG(ERROR) << #_x " failed."; \
341 return false; \
342 } \
343 } while (0)
344
345#define TEST_AND_RETURN_ERRNO(_x) \
346 do { \
347 bool _success = (_x); \
348 if (!_success) { \
349 std::string _msg = \
350 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
351 LOG(ERROR) << #_x " failed: " << _msg; \
352 return; \
353 } \
354 } while (0)
355
356#define TEST_AND_RETURN(_x) \
357 do { \
358 bool _success = (_x); \
359 if (!_success) { \
360 LOG(ERROR) << #_x " failed."; \
361 return; \
362 } \
363 } while (0)
364
365
366
367#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_UTILS_H__