blob: 776fc22b7b5439645da8d7c3caf82b52dcd08676 [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
Thieu Le5c7d9752010-12-15 16:09:28 -080015#include <ext2fs/ext2fs.h>
Andrew de los Reyesc7020782010-04-28 10:46:04 -070016#include <glib.h>
Darin Petkovc6c135c2010-08-11 13:36:18 -070017
adlr@google.com3defe6a2009-12-04 20:57:17 +000018#include "update_engine/action.h"
19#include "update_engine/action_processor.h"
20
21namespace chromeos_update_engine {
22
23namespace utils {
24
Darin Petkova07586b2010-10-20 13:41:15 -070025// Returns true if this is an official Chrome OS build, false otherwise.
Darin Petkov33d30642010-08-04 10:18:57 -070026bool IsOfficialBuild();
27
Darin Petkov2a0e6332010-09-24 14:43:41 -070028// Returns true if the OOBE process has been completed and EULA accepted, false
29// otherwise.
30bool IsOOBEComplete();
31
Andrew de los Reyes970bb282009-12-09 16:34:04 -080032// Writes the data passed to path. The file at path will be overwritten if it
33// exists. Returns true on success, false otherwise.
34bool WriteFile(const char* path, const char* data, int data_len);
35
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070036// Calls write() or pwrite() repeatedly until all count bytes at buf are
37// written to fd or an error occurs. Returns true on success.
38bool WriteAll(int fd, const void* buf, size_t count);
39bool PWriteAll(int fd, const void* buf, size_t count, off_t offset);
40
41// Calls pread() repeatedly until count bytes are read, or EOF is reached.
42// Returns number of bytes read in *bytes_read. Returns true on success.
43bool PReadAll(int fd, void* buf, size_t count, off_t offset,
44 ssize_t* out_bytes_read);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070045
adlr@google.com3defe6a2009-12-04 20:57:17 +000046// Returns the entire contents of the file at path. Returns true on success.
47bool ReadFile(const std::string& path, std::vector<char>* out);
48bool ReadFileToString(const std::string& path, std::string* out);
49
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070050// Returns the size of the file at path. If the file doesn't exist or some
51// error occurrs, -1 is returned.
52off_t FileSize(const std::string& path);
53
adlr@google.com3defe6a2009-12-04 20:57:17 +000054std::string ErrnoNumberAsString(int err);
55
56// Strips duplicate slashes, and optionally removes all trailing slashes.
57// Does not compact /./ or /../.
58std::string NormalizePath(const std::string& path, bool strip_trailing_slash);
59
60// Returns true if the file exists for sure. Returns false if it doesn't exist,
61// or an error occurs.
62bool FileExists(const char* path);
63
Darin Petkov30291ed2010-11-12 10:23:06 -080064// Returns true if |path| exists and is a symbolic link.
65bool IsSymlink(const char* path);
66
adlr@google.com3defe6a2009-12-04 20:57:17 +000067// The last 6 chars of path must be XXXXXX. They will be randomly changed
68// and a non-existent path will be returned. Intentionally makes a copy
69// of the string passed in.
70// NEVER CALL THIS FUNCTION UNLESS YOU ARE SURE
71// THAT YOUR PROCESS WILL BE THE ONLY THING WRITING FILES IN THIS DIRECTORY.
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -080072std::string TempFilename(std::string path);
adlr@google.com3defe6a2009-12-04 20:57:17 +000073
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070074// Calls mkstemp() with the template passed. Returns the filename in the
75// out param filename. If fd is non-NULL, the file fd returned by mkstemp
76// is not close()d and is returned in the out param 'fd'. However, if
77// fd is NULL, the fd from mkstemp() will be closed.
78// The last six chars of the template must be XXXXXX.
79// Returns true on success.
80bool MakeTempFile(const std::string& filename_template,
81 std::string* filename,
82 int* fd);
83
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070084// Calls mkdtemp() with the tempate passed. Returns the generated dirname
85// in the dirname param. Returns TRUE on success. dirname must not be NULL.
86bool MakeTempDirectory(const std::string& dirname_template,
87 std::string* dirname);
88
adlr@google.com3defe6a2009-12-04 20:57:17 +000089// Deletes a directory and all its contents synchronously. Returns true
90// on success. This may be called with a regular file--it will just unlink it.
91// This WILL cross filesystem boundaries.
92bool RecursiveUnlinkDir(const std::string& path);
93
Andrew de los Reyesf9714432010-05-04 10:21:23 -070094// Returns the root device for a partition. For example,
Darin Petkovf74eb652010-08-04 12:08:38 -070095// RootDevice("/dev/sda3") returns "/dev/sda". Returns an empty string
96// if the input device is not of the "/dev/xyz" form.
Andrew de los Reyesf9714432010-05-04 10:21:23 -070097std::string RootDevice(const std::string& partition_device);
98
99// Returns the partition number, as a string, of partition_device. For example,
Darin Petkovf74eb652010-08-04 12:08:38 -0700100// PartitionNumber("/dev/sda3") returns "3".
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700101std::string PartitionNumber(const std::string& partition_device);
102
Darin Petkovf74eb652010-08-04 12:08:38 -0700103// Returns the sysfs block device for a root block device. For
104// example, SysfsBlockDevice("/dev/sda") returns
105// "/sys/block/sda". Returns an empty string if the input device is
106// not of the "/dev/xyz" form.
107std::string SysfsBlockDevice(const std::string& device);
108
109// Returns true if the root |device| (e.g., "/dev/sdb") is known to be
110// removable, false otherwise.
111bool IsRemovableDevice(const std::string& device);
112
adlr@google.com3defe6a2009-12-04 20:57:17 +0000113// Synchronously mount or unmount a filesystem. Return true on success.
114// Mounts as ext3 with default options.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700115bool MountFilesystem(const std::string& device, const std::string& mountpoint,
116 unsigned long flags);
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800117bool UnmountFilesystem(const std::string& mountpoint);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000118
Darin Petkovd3f8c892010-10-12 21:38:45 -0700119// Returns the block count and the block byte size of the ext3 file system on
120// |device| (which may be a real device or a path to a filesystem image) or on
121// an opened file descriptor |fd|. The actual file-system size is |block_count|
122// * |block_size| bytes. Returns true on success, false otherwise.
123bool GetFilesystemSize(const std::string& device,
124 int* out_block_count,
125 int* out_block_size);
126bool GetFilesystemSizeFromFD(int fd,
127 int* out_block_count,
128 int* out_block_size);
129
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700130enum BootLoader {
131 BootLoader_SYSLINUX = 0,
132 BootLoader_CHROME_FIRMWARE = 1
133};
134// Detects which bootloader this system uses and returns it via the out
135// param. Returns true on success.
136bool GetBootloader(BootLoader* out_bootloader);
137
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700138// Returns the error message, if any, from a GError pointer.
139const char* GetGErrorMessage(const GError* error);
140
Darin Petkov296889c2010-07-23 16:20:54 -0700141// Initiates a system reboot. Returns true on success, false otherwise.
142bool Reboot();
143
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800144// Schedules a Main Loop callback to trigger the crash reporter to perform an
145// upload as if this process had crashed.
146void ScheduleCrashReporterUpload();
147
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700148// Fuzzes an integer |value| randomly in the range:
149// [value - range / 2, value + range - range / 2]
150int FuzzInt(int value, unsigned int range);
151
adlr@google.com3defe6a2009-12-04 20:57:17 +0000152// Log a string in hex to LOG(INFO). Useful for debugging.
153void HexDumpArray(const unsigned char* const arr, const size_t length);
154inline void HexDumpString(const std::string& str) {
155 HexDumpArray(reinterpret_cast<const unsigned char*>(str.data()), str.size());
156}
157inline void HexDumpVector(const std::vector<char>& vect) {
158 HexDumpArray(reinterpret_cast<const unsigned char*>(&vect[0]), vect.size());
159}
160
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800161extern const char* const kStatefulPartition;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000162
163bool StringHasSuffix(const std::string& str, const std::string& suffix);
164bool StringHasPrefix(const std::string& str, const std::string& prefix);
165
166template<typename KeyType, typename ValueType>
167bool MapContainsKey(const std::map<KeyType, ValueType>& m, const KeyType& k) {
168 return m.find(k) != m.end();
169}
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800170template<typename KeyType>
171bool SetContainsKey(const std::set<KeyType>& s, const KeyType& k) {
172 return s.find(k) != s.end();
173}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000174
175template<typename ValueType>
176std::set<ValueType> SetWithValue(const ValueType& value) {
177 std::set<ValueType> ret;
178 ret.insert(value);
179 return ret;
180}
181
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800182template<typename T>
183bool VectorContainsValue(const std::vector<T>& vect, const T& value) {
Darin Petkovc1a8b422010-07-19 11:34:49 -0700184 return std::find(vect.begin(), vect.end(), value) != vect.end();
Andrew de los Reyes0ce161b2010-02-22 15:27:01 -0800185}
186
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700187template<typename T>
188bool VectorIndexOf(const std::vector<T>& vect, const T& value,
189 typename std::vector<T>::size_type* out_index) {
190 typename std::vector<T>::const_iterator it = std::find(vect.begin(),
191 vect.end(),
192 value);
193 if (it == vect.end()) {
194 return false;
195 } else {
196 *out_index = it - vect.begin();
197 return true;
198 }
199}
200
Andrew de los Reyescc92cd32010-10-05 16:56:14 -0700201template<typename ValueType>
202void ApplyMap(std::vector<ValueType>* collection,
203 const std::map<ValueType, ValueType>& the_map) {
204 for (typename std::vector<ValueType>::iterator it = collection->begin();
205 it != collection->end(); ++it) {
206 typename std::map<ValueType, ValueType>::const_iterator map_it =
207 the_map.find(*it);
208 if (map_it != the_map.end()) {
209 *it = map_it->second;
210 }
211 }
212}
213
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700214// Returns the currently booted device. "/dev/sda3", for example.
adlr@google.com3defe6a2009-12-04 20:57:17 +0000215// This will not interpret LABEL= or UUID=. You'll need to use findfs
216// or something with equivalent funcionality to interpret those.
217const std::string BootDevice();
218
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700219// Returns the currently booted kernel device, "dev/sda2", for example.
220// Client must pass in the boot device. The suggested calling convention
221// is: BootKernelDevice(BootDevice()).
222// This function works by doing string modification on boot_device.
223// Returns empty string on failure.
224const std::string BootKernelDevice(const std::string& boot_device);
225
Darin Petkovc6c135c2010-08-11 13:36:18 -0700226enum ProcessPriority {
227 kProcessPriorityHigh = -10,
228 kProcessPriorityNormal = 0,
229 kProcessPriorityLow = 10,
230};
231
232// Compares process priorities and returns an integer that is less
233// than, equal to or greater than 0 if |priority_lhs| is,
234// respectively, lower than, same as or higher than |priority_rhs|.
235int ComparePriorities(ProcessPriority priority_lhs,
236 ProcessPriority priority_rhs);
237
238// Sets the current process priority to |priority|. Returns true on
239// success, false otherwise.
240bool SetProcessPriority(ProcessPriority priority);
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700241
adlr@google.com3defe6a2009-12-04 20:57:17 +0000242} // namespace utils
243
244// Class to unmount FS when object goes out of scope
245class ScopedFilesystemUnmounter {
246 public:
247 explicit ScopedFilesystemUnmounter(const std::string& mountpoint)
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800248 : mountpoint_(mountpoint),
249 should_unmount_(true) {}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000250 ~ScopedFilesystemUnmounter() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800251 if (should_unmount_) {
252 utils::UnmountFilesystem(mountpoint_);
253 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000254 }
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800255 void set_should_unmount(bool unmount) { should_unmount_ = unmount; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000256 private:
257 const std::string mountpoint_;
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800258 bool should_unmount_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700259 DISALLOW_COPY_AND_ASSIGN(ScopedFilesystemUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000260};
261
262// Utility class to close a file descriptor
263class ScopedFdCloser {
264 public:
265 explicit ScopedFdCloser(int* fd) : fd_(fd), should_close_(true) {}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000266 ~ScopedFdCloser() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800267 if (should_close_ && fd_ && (*fd_ >= 0)) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000268 close(*fd_);
269 *fd_ = -1;
270 }
271 }
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800272 void set_should_close(bool should_close) { should_close_ = should_close; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000273 private:
274 int* fd_;
275 bool should_close_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700276 DISALLOW_COPY_AND_ASSIGN(ScopedFdCloser);
277};
278
Thieu Le5c7d9752010-12-15 16:09:28 -0800279// Utility class to close a file system
280class ScopedExt2fsCloser {
281 public:
282 explicit ScopedExt2fsCloser(ext2_filsys filsys) : filsys_(filsys) {}
283 ~ScopedExt2fsCloser() { ext2fs_close(filsys_); }
284
285 private:
286 ext2_filsys filsys_;
287 DISALLOW_COPY_AND_ASSIGN(ScopedExt2fsCloser);
288};
289
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700290// Utility class to delete a file when it goes out of scope.
291class ScopedPathUnlinker {
292 public:
293 explicit ScopedPathUnlinker(const std::string& path) : path_(path) {}
294 ~ScopedPathUnlinker() {
295 if (unlink(path_.c_str()) < 0) {
296 std::string err_message = strerror(errno);
297 LOG(ERROR) << "Unable to unlink path " << path_ << ": " << err_message;
298 }
299 }
300 private:
301 const std::string path_;
302 DISALLOW_COPY_AND_ASSIGN(ScopedPathUnlinker);
303};
304
305// Utility class to delete an empty directory when it goes out of scope.
306class ScopedDirRemover {
307 public:
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800308 explicit ScopedDirRemover(const std::string& path)
309 : path_(path),
310 should_remove_(true) {}
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700311 ~ScopedDirRemover() {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800312 if (should_remove_ && (rmdir(path_.c_str()) < 0)) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700313 PLOG(ERROR) << "Unable to remove dir " << path_;
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800314 }
315 }
316 void set_should_remove(bool should_remove) { should_remove_ = should_remove; }
317
318 protected:
319 const std::string path_;
320
321 private:
322 bool should_remove_;
323 DISALLOW_COPY_AND_ASSIGN(ScopedDirRemover);
324};
325
326// Utility class to unmount a filesystem mounted on a temporary directory and
327// delete the temporary directory when it goes out of scope.
328class ScopedTempUnmounter : public ScopedDirRemover {
329 public:
330 explicit ScopedTempUnmounter(const std::string& path) :
331 ScopedDirRemover(path) {}
332 ~ScopedTempUnmounter() {
333 utils::UnmountFilesystem(path_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700334 }
335 private:
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800336 DISALLOW_COPY_AND_ASSIGN(ScopedTempUnmounter);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000337};
338
339// A little object to call ActionComplete on the ActionProcessor when
340// it's destructed.
341class ScopedActionCompleter {
342 public:
343 explicit ScopedActionCompleter(ActionProcessor* processor,
344 AbstractAction* action)
345 : processor_(processor),
346 action_(action),
Darin Petkovc1a8b422010-07-19 11:34:49 -0700347 code_(kActionCodeError),
adlr@google.com3defe6a2009-12-04 20:57:17 +0000348 should_complete_(true) {}
349 ~ScopedActionCompleter() {
350 if (should_complete_)
Darin Petkovc1a8b422010-07-19 11:34:49 -0700351 processor_->ActionComplete(action_, code_);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000352 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700353 void set_code(ActionExitCode code) { code_ = code; }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000354 void set_should_complete(bool should_complete) {
355 should_complete_ = should_complete;
356 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700357
adlr@google.com3defe6a2009-12-04 20:57:17 +0000358 private:
359 ActionProcessor* processor_;
360 AbstractAction* action_;
Darin Petkovc1a8b422010-07-19 11:34:49 -0700361 ActionExitCode code_;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000362 bool should_complete_;
363 DISALLOW_COPY_AND_ASSIGN(ScopedActionCompleter);
364};
365
366} // namespace chromeos_update_engine
367
368#define TEST_AND_RETURN_FALSE_ERRNO(_x) \
369 do { \
370 bool _success = (_x); \
371 if (!_success) { \
372 std::string _msg = \
373 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
374 LOG(ERROR) << #_x " failed: " << _msg; \
375 return false; \
376 } \
377 } while (0)
378
379#define TEST_AND_RETURN_FALSE(_x) \
380 do { \
381 bool _success = (_x); \
382 if (!_success) { \
383 LOG(ERROR) << #_x " failed."; \
384 return false; \
385 } \
386 } while (0)
387
388#define TEST_AND_RETURN_ERRNO(_x) \
389 do { \
390 bool _success = (_x); \
391 if (!_success) { \
392 std::string _msg = \
393 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
394 LOG(ERROR) << #_x " failed: " << _msg; \
395 return; \
396 } \
397 } while (0)
398
399#define TEST_AND_RETURN(_x) \
400 do { \
401 bool _success = (_x); \
402 if (!_success) { \
403 LOG(ERROR) << #_x " failed."; \
404 return; \
405 } \
406 } while (0)
407
Thieu Le5c7d9752010-12-15 16:09:28 -0800408#define TEST_AND_RETURN_FALSE_ERRCODE(_x) \
409 do { \
410 errcode_t _error = (_x); \
411 if (_error) { \
412 errno = _error; \
413 LOG(ERROR) << #_x " failed: " << _error; \
414 return false; \
415 } \
416 } while (0)
417
adlr@google.com3defe6a2009-12-04 20:57:17 +0000418
419
420#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_UTILS_H__