blob: 208abe8d48c2a2e976b5b9173b9e935d5baeca64 [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)
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800240 : mountpoint_(mountpoint),
241 should_unmount_(true) {}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000242 ~ScopedFilesystemUnmounter() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800243 if (should_unmount_) {
244 utils::UnmountFilesystem(mountpoint_);
245 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000246 }
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800247 void set_should_unmount(bool unmount) { should_unmount_ = unmount; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000248 private:
249 const std::string mountpoint_;
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800250 bool should_unmount_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700251 DISALLOW_COPY_AND_ASSIGN(ScopedFilesystemUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000252};
253
254// Utility class to close a file descriptor
255class ScopedFdCloser {
256 public:
257 explicit ScopedFdCloser(int* fd) : fd_(fd), should_close_(true) {}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000258 ~ScopedFdCloser() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800259 if (should_close_ && fd_ && (*fd_ >= 0)) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000260 close(*fd_);
261 *fd_ = -1;
262 }
263 }
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800264 void set_should_close(bool should_close) { should_close_ = should_close; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000265 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:
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800289 explicit ScopedDirRemover(const std::string& path)
290 : path_(path),
291 should_remove_(true) {}
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700292 ~ScopedDirRemover() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800293 if (should_remove_ && (rmdir(path_.c_str()) < 0)) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700294 PLOG(ERROR) << "Unable to remove dir " << path_;
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800295 }
296 }
297 void set_should_remove(bool should_remove) { should_remove_ = should_remove; }
298
299 protected:
300 const std::string path_;
301
302 private:
303 bool should_remove_;
304 DISALLOW_COPY_AND_ASSIGN(ScopedDirRemover);
305};
306
307// Utility class to unmount a filesystem mounted on a temporary directory and
308// delete the temporary directory when it goes out of scope.
309class ScopedTempUnmounter : public ScopedDirRemover {
310 public:
311 explicit ScopedTempUnmounter(const std::string& path) :
312 ScopedDirRemover(path) {}
313 ~ScopedTempUnmounter() {
314 utils::UnmountFilesystem(path_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700315 }
316 private:
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800317 DISALLOW_COPY_AND_ASSIGN(ScopedTempUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000318};
319
320// A little object to call ActionComplete on the ActionProcessor when
321// it's destructed.
322class ScopedActionCompleter {
323 public:
324 explicit ScopedActionCompleter(ActionProcessor* processor,
325 AbstractAction* action)
326 : processor_(processor),
327 action_(action),
Darin Petkovc1a8b422010-07-19 11:34:49 -0700328 code_(kActionCodeError),
adlr@google.com3defe6a2009-12-04 20:57:17 +0000329 should_complete_(true) {}
330 ~ScopedActionCompleter() {
331 if (should_complete_)
Darin Petkovc1a8b422010-07-19 11:34:49 -0700332 processor_->ActionComplete(action_, code_);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000333 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700334 void set_code(ActionExitCode code) { code_ = code; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000335 void set_should_complete(bool should_complete) {
336 should_complete_ = should_complete;
337 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700338
adlr@google.com3defe6a2009-12-04 20:57:17 +0000339 private:
340 ActionProcessor* processor_;
341 AbstractAction* action_;
Darin Petkovc1a8b422010-07-19 11:34:49 -0700342 ActionExitCode code_;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000343 bool should_complete_;
344 DISALLOW_COPY_AND_ASSIGN(ScopedActionCompleter);
345};
346
347} // namespace chromeos_update_engine
348
349#define TEST_AND_RETURN_FALSE_ERRNO(_x) \
350 do { \
351 bool _success = (_x); \
352 if (!_success) { \
353 std::string _msg = \
354 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
355 LOG(ERROR) << #_x " failed: " << _msg; \
356 return false; \
357 } \
358 } while (0)
359
360#define TEST_AND_RETURN_FALSE(_x) \
361 do { \
362 bool _success = (_x); \
363 if (!_success) { \
364 LOG(ERROR) << #_x " failed."; \
365 return false; \
366 } \
367 } while (0)
368
369#define TEST_AND_RETURN_ERRNO(_x) \
370 do { \
371 bool _success = (_x); \
372 if (!_success) { \
373 std::string _msg = \
374 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
375 LOG(ERROR) << #_x " failed: " << _msg; \
376 return; \
377 } \
378 } while (0)
379
380#define TEST_AND_RETURN(_x) \
381 do { \
382 bool _success = (_x); \
383 if (!_success) { \
384 LOG(ERROR) << #_x " failed."; \
385 return; \
386 } \
387 } while (0)
388
389
390
391#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_UTILS_H__