blob: 34b862e109195ec393e81fdbc9562679bb791a90 [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
Darin Petkov30291ed2010-11-12 10:23:06 -080063// Returns true if |path| exists and is a symbolic link.
64bool IsSymlink(const char* path);
65
adlr@google.com3defe6a2009-12-04 20:57:17 +000066// 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)
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800243 : mountpoint_(mountpoint),
244 should_unmount_(true) {}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000245 ~ScopedFilesystemUnmounter() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800246 if (should_unmount_) {
247 utils::UnmountFilesystem(mountpoint_);
248 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000249 }
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800250 void set_should_unmount(bool unmount) { should_unmount_ = unmount; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000251 private:
252 const std::string mountpoint_;
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800253 bool should_unmount_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700254 DISALLOW_COPY_AND_ASSIGN(ScopedFilesystemUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000255};
256
257// Utility class to close a file descriptor
258class ScopedFdCloser {
259 public:
260 explicit ScopedFdCloser(int* fd) : fd_(fd), should_close_(true) {}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000261 ~ScopedFdCloser() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800262 if (should_close_ && fd_ && (*fd_ >= 0)) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000263 close(*fd_);
264 *fd_ = -1;
265 }
266 }
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800267 void set_should_close(bool should_close) { should_close_ = should_close; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000268 private:
269 int* fd_;
270 bool should_close_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700271 DISALLOW_COPY_AND_ASSIGN(ScopedFdCloser);
272};
273
274// Utility class to delete a file when it goes out of scope.
275class ScopedPathUnlinker {
276 public:
277 explicit ScopedPathUnlinker(const std::string& path) : path_(path) {}
278 ~ScopedPathUnlinker() {
279 if (unlink(path_.c_str()) < 0) {
280 std::string err_message = strerror(errno);
281 LOG(ERROR) << "Unable to unlink path " << path_ << ": " << err_message;
282 }
283 }
284 private:
285 const std::string path_;
286 DISALLOW_COPY_AND_ASSIGN(ScopedPathUnlinker);
287};
288
289// Utility class to delete an empty directory when it goes out of scope.
290class ScopedDirRemover {
291 public:
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800292 explicit ScopedDirRemover(const std::string& path)
293 : path_(path),
294 should_remove_(true) {}
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700295 ~ScopedDirRemover() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800296 if (should_remove_ && (rmdir(path_.c_str()) < 0)) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700297 PLOG(ERROR) << "Unable to remove dir " << path_;
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800298 }
299 }
300 void set_should_remove(bool should_remove) { should_remove_ = should_remove; }
301
302 protected:
303 const std::string path_;
304
305 private:
306 bool should_remove_;
307 DISALLOW_COPY_AND_ASSIGN(ScopedDirRemover);
308};
309
310// Utility class to unmount a filesystem mounted on a temporary directory and
311// delete the temporary directory when it goes out of scope.
312class ScopedTempUnmounter : public ScopedDirRemover {
313 public:
314 explicit ScopedTempUnmounter(const std::string& path) :
315 ScopedDirRemover(path) {}
316 ~ScopedTempUnmounter() {
317 utils::UnmountFilesystem(path_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700318 }
319 private:
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800320 DISALLOW_COPY_AND_ASSIGN(ScopedTempUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000321};
322
323// A little object to call ActionComplete on the ActionProcessor when
324// it's destructed.
325class ScopedActionCompleter {
326 public:
327 explicit ScopedActionCompleter(ActionProcessor* processor,
328 AbstractAction* action)
329 : processor_(processor),
330 action_(action),
Darin Petkovc1a8b422010-07-19 11:34:49 -0700331 code_(kActionCodeError),
adlr@google.com3defe6a2009-12-04 20:57:17 +0000332 should_complete_(true) {}
333 ~ScopedActionCompleter() {
334 if (should_complete_)
Darin Petkovc1a8b422010-07-19 11:34:49 -0700335 processor_->ActionComplete(action_, code_);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000336 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700337 void set_code(ActionExitCode code) { code_ = code; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000338 void set_should_complete(bool should_complete) {
339 should_complete_ = should_complete;
340 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700341
adlr@google.com3defe6a2009-12-04 20:57:17 +0000342 private:
343 ActionProcessor* processor_;
344 AbstractAction* action_;
Darin Petkovc1a8b422010-07-19 11:34:49 -0700345 ActionExitCode code_;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000346 bool should_complete_;
347 DISALLOW_COPY_AND_ASSIGN(ScopedActionCompleter);
348};
349
350} // namespace chromeos_update_engine
351
352#define TEST_AND_RETURN_FALSE_ERRNO(_x) \
353 do { \
354 bool _success = (_x); \
355 if (!_success) { \
356 std::string _msg = \
357 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
358 LOG(ERROR) << #_x " failed: " << _msg; \
359 return false; \
360 } \
361 } while (0)
362
363#define TEST_AND_RETURN_FALSE(_x) \
364 do { \
365 bool _success = (_x); \
366 if (!_success) { \
367 LOG(ERROR) << #_x " failed."; \
368 return false; \
369 } \
370 } while (0)
371
372#define TEST_AND_RETURN_ERRNO(_x) \
373 do { \
374 bool _success = (_x); \
375 if (!_success) { \
376 std::string _msg = \
377 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
378 LOG(ERROR) << #_x " failed: " << _msg; \
379 return; \
380 } \
381 } while (0)
382
383#define TEST_AND_RETURN(_x) \
384 do { \
385 bool _success = (_x); \
386 if (!_success) { \
387 LOG(ERROR) << #_x " failed."; \
388 return; \
389 } \
390 } while (0)
391
392
393
394#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_UTILS_H__