blob: f0cea0d8df3fa38637d95ad9261ff21b3455d481 [file] [log] [blame]
Mike Frysinger8155d082012-04-06 15:23:18 -04001// Copyright (c) 2012 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#include "update_engine/utils.h"
Darin Petkovf74eb652010-08-04 12:08:38 -07006
adlr@google.com3defe6a2009-12-04 20:57:17 +00007#include <sys/mount.h>
Darin Petkovc6c135c2010-08-11 13:36:18 -07008#include <sys/resource.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +00009#include <sys/stat.h>
10#include <sys/types.h>
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -080011#include <sys/wait.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000012#include <dirent.h>
13#include <errno.h>
Andrew de los Reyes970bb282009-12-09 16:34:04 -080014#include <fcntl.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000015#include <stdio.h>
16#include <stdlib.h>
17#include <string.h>
David Zeuthen9a017f22013-04-11 16:10:26 -070018#include <time.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000019#include <unistd.h>
Darin Petkovf74eb652010-08-04 12:08:38 -070020
adlr@google.com3defe6a2009-12-04 20:57:17 +000021#include <algorithm>
Darin Petkovf74eb652010-08-04 12:08:38 -070022
Will Drewry8f71da82010-08-30 14:07:11 -050023#include <base/file_path.h>
24#include <base/file_util.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040025#include <base/logging.h>
Chris Sosafc661a12013-02-26 14:43:21 -080026#include <base/posix/eintr_wrapper.h>
Will Drewry8f71da82010-08-30 14:07:11 -050027#include <base/rand_util.h>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070028#include <base/string_number_conversions.h>
Will Drewry8f71da82010-08-30 14:07:11 -050029#include <base/string_util.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040030#include <base/stringprintf.h>
Gilad Arnold8e3f1262013-01-08 14:59:54 -080031#include <glib.h>
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -080032#include <google/protobuf/stubs/common.h>
Will Drewry8f71da82010-08-30 14:07:11 -050033#include <rootdev/rootdev.h>
34
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070035#include "update_engine/constants.h"
Andrew de los Reyes970bb282009-12-09 16:34:04 -080036#include "update_engine/file_writer.h"
Darin Petkov33d30642010-08-04 10:18:57 -070037#include "update_engine/omaha_request_params.h"
Darin Petkov296889c2010-07-23 16:20:54 -070038#include "update_engine/subprocess.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080039#include "update_engine/system_state.h"
40#include "update_engine/update_attempter.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000041
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070042using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080043using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000044using std::min;
45using std::string;
46using std::vector;
47
48namespace chromeos_update_engine {
49
Ben Chan77a1eba2012-10-07 22:54:55 -070050namespace {
51
52// The following constants control how UnmountFilesystem should retry if
53// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
54// one second.
55const int kUnmountMaxNumOfRetries = 5;
56const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Ben Chan77a1eba2012-10-07 22:54:55 -070057} // namespace
58
adlr@google.com3defe6a2009-12-04 20:57:17 +000059namespace utils {
60
Darin Petkova07586b2010-10-20 13:41:15 -070061static const char kDevImageMarker[] = "/root/.dev_mode";
Darin Petkov2a0e6332010-09-24 14:43:41 -070062
Chris Sosa4f8ee272012-11-30 13:01:54 -080063// Cgroup container is created in update-engine's upstart script located at
64// /etc/init/update-engine.conf.
65static const char kCGroupDir[] = "/sys/fs/cgroup/cpu/update-engine";
66
Darin Petkov33d30642010-08-04 10:18:57 -070067bool IsOfficialBuild() {
Darin Petkova07586b2010-10-20 13:41:15 -070068 return !file_util::PathExists(FilePath(kDevImageMarker));
Darin Petkov33d30642010-08-04 10:18:57 -070069}
70
Darin Petkovc91dd6b2011-01-10 12:31:34 -080071bool IsNormalBootMode() {
Darin Petkov44d98d92011-03-21 16:08:11 -070072 // TODO(petkov): Convert to a library call once a crossystem library is
73 // available (crosbug.com/13291).
74 int exit_code = 0;
75 vector<string> cmd(1, "/usr/bin/crossystem");
76 cmd.push_back("devsw_boot?1");
77
78 // Assume dev mode if the dev switch is set to 1 and there was no error
79 // executing crossystem. Assume normal mode otherwise.
Darin Petkov85d02b72011-05-17 13:25:51 -070080 bool success = Subprocess::SynchronousExec(cmd, &exit_code, NULL);
Darin Petkov44d98d92011-03-21 16:08:11 -070081 bool dev_mode = success && exit_code == 0;
82 LOG_IF(INFO, dev_mode) << "Booted in dev mode.";
83 return !dev_mode;
Darin Petkovc91dd6b2011-01-10 12:31:34 -080084}
85
Darin Petkovf2065b42011-05-17 16:36:27 -070086string GetHardwareClass() {
87 // TODO(petkov): Convert to a library call once a crossystem library is
88 // available (crosbug.com/13291).
89 int exit_code = 0;
90 vector<string> cmd(1, "/usr/bin/crossystem");
91 cmd.push_back("hwid");
92
93 string hwid;
94 bool success = Subprocess::SynchronousExec(cmd, &exit_code, &hwid);
95 if (success && !exit_code) {
96 TrimWhitespaceASCII(hwid, TRIM_ALL, &hwid);
97 return hwid;
98 }
99 LOG(ERROR) << "Unable to read HWID (" << exit_code << ") " << hwid;
100 return "";
101}
102
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800103bool WriteFile(const char* path, const char* data, int data_len) {
104 DirectFileWriter writer;
105 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
106 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700107 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800108 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800109 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800110 return true;
111}
112
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700113bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700114 const char* c_buf = static_cast<const char*>(buf);
115 ssize_t bytes_written = 0;
116 while (bytes_written < static_cast<ssize_t>(count)) {
117 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
118 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
119 bytes_written += rc;
120 }
121 return true;
122}
123
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700124bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
125 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700126 size_t bytes_written = 0;
127 int num_attempts = 0;
128 while (bytes_written < count) {
129 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700130 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
131 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700132 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
133 if (rc < 0) {
134 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
135 << " bytes_written=" << bytes_written
136 << " count=" << count << " offset=" << offset;
137 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700138 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
139 bytes_written += rc;
140 }
141 return true;
142}
143
144bool PReadAll(int fd, void* buf, size_t count, off_t offset,
145 ssize_t* out_bytes_read) {
146 char* c_buf = static_cast<char*>(buf);
147 ssize_t bytes_read = 0;
148 while (bytes_read < static_cast<ssize_t>(count)) {
149 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
150 offset + bytes_read);
151 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
152 if (rc == 0) {
153 break;
154 }
155 bytes_read += rc;
156 }
157 *out_bytes_read = bytes_read;
158 return true;
Darin Petkov296889c2010-07-23 16:20:54 -0700159
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700160}
161
Gilad Arnold19a45f02012-07-19 12:36:10 -0700162// Append |nbytes| of content from |buf| to the vector pointed to by either
163// |vec_p| or |str_p|.
164static void AppendBytes(const char* buf, size_t nbytes,
165 std::vector<char>* vec_p) {
166 CHECK(buf);
167 CHECK(vec_p);
168 vec_p->insert(vec_p->end(), buf, buf + nbytes);
169}
170static void AppendBytes(const char* buf, size_t nbytes,
171 std::string* str_p) {
172 CHECK(buf);
173 CHECK(str_p);
174 str_p->append(buf, nbytes);
175}
176
177// Reads from an open file |fp|, appending the read content to the container
178// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200179// file's content, false otherwise. If |size| is not -1, reads up to |size|
180// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700181template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200182static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700183 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200184 CHECK(size == -1 || size >= 0);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700185 char buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200186 while (size == -1 || size > 0) {
187 off_t bytes_to_read = sizeof(buf);
188 if (size > 0 && bytes_to_read > size) {
189 bytes_to_read = size;
190 }
191 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
192 if (!nbytes) {
193 break;
194 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700195 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200196 if (size != -1) {
197 CHECK(size >= static_cast<off_t>(nbytes));
198 size -= nbytes;
199 }
200 }
201 if (ferror(fp)) {
202 return false;
203 }
204 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700205}
206
Darin Petkov8e447e02013-04-16 16:23:50 +0200207// Opens a file |path| for reading and appends its the contents to a container
208// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
209// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700210template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200211static bool ReadFileChunkAndAppend(const std::string& path,
212 off_t offset,
213 off_t size,
214 T* out_p) {
215 CHECK_GE(offset, 0);
216 CHECK(size == -1 || size >= 0);
217 file_util::ScopedFILE fp(fopen(path.c_str(), "r"));
218 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000219 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200220 if (offset) {
221 // Return success without appending any data if a chunk beyond the end of
222 // the file is requested.
223 if (offset >= FileSize(path)) {
224 return true;
225 }
226 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
227 }
228 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000229}
230
Gilad Arnold19a45f02012-07-19 12:36:10 -0700231// Invokes a pipe |cmd|, then uses |append_func| to append its stdout to a
232// container |out_p|.
233template <class T>
234static bool ReadPipeAndAppend(const std::string& cmd, T* out_p) {
235 FILE* fp = popen(cmd.c_str(), "r");
236 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000237 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200238 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700239 return (success && pclose(fp) >= 0);
240}
241
242
Darin Petkov8e447e02013-04-16 16:23:50 +0200243bool ReadFile(const string& path, vector<char>* out_p) {
244 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700245}
246
Darin Petkov8e447e02013-04-16 16:23:50 +0200247bool ReadFile(const string& path, string* out_p) {
248 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700249}
250
Darin Petkov8e447e02013-04-16 16:23:50 +0200251bool ReadFileChunk(const string& path, off_t offset, off_t size,
252 vector<char>* out_p) {
253 return ReadFileChunkAndAppend(path, offset, size, out_p);
254}
255
256bool ReadPipe(const string& cmd, vector<char>* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700257 return ReadPipeAndAppend(cmd, out_p);
258}
259
Darin Petkov8e447e02013-04-16 16:23:50 +0200260bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700261 return ReadPipeAndAppend(cmd, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000262}
263
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700264off_t FileSize(const string& path) {
265 struct stat stbuf;
266 int rc = stat(path.c_str(), &stbuf);
267 CHECK_EQ(rc, 0);
268 if (rc < 0)
269 return rc;
270 return stbuf.st_size;
271}
272
adlr@google.com3defe6a2009-12-04 20:57:17 +0000273void HexDumpArray(const unsigned char* const arr, const size_t length) {
274 const unsigned char* const char_arr =
275 reinterpret_cast<const unsigned char* const>(arr);
276 LOG(INFO) << "Logging array of length: " << length;
277 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700278 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000279 const unsigned int bytes_remaining = length - i;
280 const unsigned int bytes_per_this_line = min(bytes_per_line,
281 bytes_remaining);
282 char header[100];
283 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
284 TEST_AND_RETURN(r == 13);
285 string line = header;
286 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
287 char buf[20];
288 unsigned char c = char_arr[i + j];
289 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
290 TEST_AND_RETURN(r == 3);
291 line += buf;
292 }
293 LOG(INFO) << line;
294 }
295}
296
297namespace {
298class ScopedDirCloser {
299 public:
300 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
301 ~ScopedDirCloser() {
302 if (dir_ && *dir_) {
303 int r = closedir(*dir_);
304 TEST_AND_RETURN_ERRNO(r == 0);
305 *dir_ = NULL;
306 dir_ = NULL;
307 }
308 }
309 private:
310 DIR** dir_;
311};
312} // namespace {}
313
314bool RecursiveUnlinkDir(const std::string& path) {
315 struct stat stbuf;
316 int r = lstat(path.c_str(), &stbuf);
317 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
318 if ((r < 0) && (errno == ENOENT))
319 // path request is missing. that's fine.
320 return true;
321 if (!S_ISDIR(stbuf.st_mode)) {
322 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700323 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000324 // success or path disappeared before we could unlink.
325 return true;
326 }
327 {
328 // We have a dir, unlink all children, then delete dir
329 DIR *dir = opendir(path.c_str());
330 TEST_AND_RETURN_FALSE_ERRNO(dir);
331 ScopedDirCloser dir_closer(&dir);
332 struct dirent dir_entry;
333 struct dirent *dir_entry_p;
334 int err = 0;
335 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
336 if (dir_entry_p == NULL) {
337 // end of stream reached
338 break;
339 }
340 // Skip . and ..
341 if (!strcmp(dir_entry_p->d_name, ".") ||
342 !strcmp(dir_entry_p->d_name, ".."))
343 continue;
344 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700345 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000346 }
347 TEST_AND_RETURN_FALSE(err == 0);
348 }
349 // unlink dir
350 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
351 return true;
352}
353
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700354string RootDevice(const string& partition_device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700355 FilePath device_path(partition_device);
356 if (device_path.DirName().value() != "/dev") {
357 return "";
358 }
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700359 string::const_iterator it = --partition_device.end();
360 for (; it >= partition_device.begin(); --it) {
361 if (!isdigit(*it))
362 break;
363 }
364 // Some devices contain a p before the partitions. For example:
365 // /dev/mmc0p4 should be shortened to /dev/mmc0.
366 if (*it == 'p')
367 --it;
368 return string(partition_device.begin(), it + 1);
369}
370
371string PartitionNumber(const string& partition_device) {
372 CHECK(!partition_device.empty());
373 string::const_iterator it = --partition_device.end();
374 for (; it >= partition_device.begin(); --it) {
375 if (!isdigit(*it))
376 break;
377 }
378 return string(it + 1, partition_device.end());
379}
380
Darin Petkovf74eb652010-08-04 12:08:38 -0700381string SysfsBlockDevice(const string& device) {
382 FilePath device_path(device);
383 if (device_path.DirName().value() != "/dev") {
384 return "";
385 }
386 return FilePath("/sys/block").Append(device_path.BaseName()).value();
387}
388
389bool IsRemovableDevice(const std::string& device) {
390 string sysfs_block = SysfsBlockDevice(device);
391 string removable;
392 if (sysfs_block.empty() ||
393 !file_util::ReadFileToString(FilePath(sysfs_block).Append("removable"),
394 &removable)) {
395 return false;
396 }
397 TrimWhitespaceASCII(removable, TRIM_ALL, &removable);
398 return removable == "1";
399}
400
adlr@google.com3defe6a2009-12-04 20:57:17 +0000401std::string ErrnoNumberAsString(int err) {
402 char buf[100];
403 buf[0] = '\0';
404 return strerror_r(err, buf, sizeof(buf));
405}
406
407std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
408 string ret;
409 bool last_insert_was_slash = false;
410 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
411 if (*it == '/') {
412 if (last_insert_was_slash)
413 continue;
414 last_insert_was_slash = true;
415 } else {
416 last_insert_was_slash = false;
417 }
418 ret.push_back(*it);
419 }
420 if (strip_trailing_slash && last_insert_was_slash) {
421 string::size_type last_non_slash = ret.find_last_not_of('/');
422 if (last_non_slash != string::npos) {
423 ret.resize(last_non_slash + 1);
424 } else {
425 ret = "";
426 }
427 }
428 return ret;
429}
430
431bool FileExists(const char* path) {
432 struct stat stbuf;
433 return 0 == lstat(path, &stbuf);
434}
435
Darin Petkov30291ed2010-11-12 10:23:06 -0800436bool IsSymlink(const char* path) {
437 struct stat stbuf;
438 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
439}
440
adlr@google.com3defe6a2009-12-04 20:57:17 +0000441std::string TempFilename(string path) {
442 static const string suffix("XXXXXX");
443 CHECK(StringHasSuffix(path, suffix));
444 do {
445 string new_suffix;
446 for (unsigned int i = 0; i < suffix.size(); i++) {
447 int r = rand() % (26 * 2 + 10); // [a-zA-Z0-9]
448 if (r < 26)
449 new_suffix.append(1, 'a' + r);
450 else if (r < (26 * 2))
451 new_suffix.append(1, 'A' + r - 26);
452 else
453 new_suffix.append(1, '0' + r - (26 * 2));
454 }
455 CHECK_EQ(new_suffix.size(), suffix.size());
456 path.resize(path.size() - new_suffix.size());
457 path.append(new_suffix);
458 } while (FileExists(path.c_str()));
459 return path;
460}
461
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700462bool MakeTempFile(const std::string& filename_template,
463 std::string* filename,
464 int* fd) {
465 DCHECK(filename || fd);
466 vector<char> buf(filename_template.size() + 1);
467 memcpy(&buf[0], filename_template.data(), filename_template.size());
468 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700469
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700470 int mkstemp_fd = mkstemp(&buf[0]);
471 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
472 if (filename) {
473 *filename = &buf[0];
474 }
475 if (fd) {
476 *fd = mkstemp_fd;
477 } else {
478 close(mkstemp_fd);
479 }
480 return true;
481}
482
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700483bool MakeTempDirectory(const std::string& dirname_template,
484 std::string* dirname) {
485 DCHECK(dirname);
486 vector<char> buf(dirname_template.size() + 1);
487 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
488 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700489
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700490 char* return_code = mkdtemp(&buf[0]);
491 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
492 *dirname = &buf[0];
493 return true;
494}
495
adlr@google.com3defe6a2009-12-04 20:57:17 +0000496bool StringHasSuffix(const std::string& str, const std::string& suffix) {
497 if (suffix.size() > str.size())
498 return false;
499 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
500}
501
502bool StringHasPrefix(const std::string& str, const std::string& prefix) {
503 if (prefix.size() > str.size())
504 return false;
505 return 0 == str.compare(0, prefix.size(), prefix);
506}
507
Will Drewry8f71da82010-08-30 14:07:11 -0500508const std::string BootDevice() {
509 char boot_path[PATH_MAX];
510 // Resolve the boot device path fully, including dereferencing
511 // through dm-verity.
512 int ret = rootdev(boot_path, sizeof(boot_path), true, false);
513
514 if (ret < 0) {
515 LOG(ERROR) << "rootdev failed to find the root device";
adlr@google.com3defe6a2009-12-04 20:57:17 +0000516 return "";
517 }
Will Drewry8f71da82010-08-30 14:07:11 -0500518 LOG_IF(WARNING, ret > 0) << "rootdev found a device name with no device node";
519
520 // This local variable is used to construct the return string and is not
521 // passed around after use.
522 return boot_path;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000523}
524
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700525const string BootKernelDevice(const std::string& boot_device) {
526 // Currntly this assumes the last digit of the boot device is
527 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
528 // get the kernel device.
529 string ret = boot_device;
530 if (ret.empty())
531 return ret;
532 char last_char = ret[ret.size() - 1];
533 if (last_char == '3' || last_char == '5' || last_char == '7') {
534 ret[ret.size() - 1] = last_char - 1;
535 return ret;
536 }
537 return "";
538}
539
adlr@google.com3defe6a2009-12-04 20:57:17 +0000540bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700541 const string& mountpoint,
542 unsigned long mountflags) {
543 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000544 if (rc < 0) {
545 string msg = ErrnoNumberAsString(errno);
546 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
547 << device << " on " << mountpoint;
548 return false;
549 }
550 return true;
551}
552
553bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700554 for (int num_retries = 0; ; ++num_retries) {
555 if (umount(mountpoint.c_str()) == 0)
556 break;
557
558 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
559 num_retries < kUnmountMaxNumOfRetries);
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800560 g_usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700561 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000562 return true;
563}
564
Darin Petkovd3f8c892010-10-12 21:38:45 -0700565bool GetFilesystemSize(const std::string& device,
566 int* out_block_count,
567 int* out_block_size) {
568 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
569 TEST_AND_RETURN_FALSE(fd >= 0);
570 ScopedFdCloser fd_closer(&fd);
571 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
572}
573
574bool GetFilesystemSizeFromFD(int fd,
575 int* out_block_count,
576 int* out_block_size) {
577 TEST_AND_RETURN_FALSE(fd >= 0);
578
579 // Determine the ext3 filesystem size by directly reading the block count and
580 // block size information from the superblock. See include/linux/ext3_fs.h for
581 // more details on the structure.
582 ssize_t kBufferSize = 16 * sizeof(uint32_t);
583 char buffer[kBufferSize];
584 const int kSuperblockOffset = 1024;
585 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
586 kBufferSize) {
587 PLOG(ERROR) << "Unable to determine file system size:";
588 return false;
589 }
590 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
591 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
592 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
593 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
594 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
595 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
596 block_count = le32toh(block_count);
597 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
598 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
599 magic = le16toh(magic);
600
601 // Sanity check the parameters.
602 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
603 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
604 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
605 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
606 int block_size = 1 << log_block_size;
607 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
608 block_size <= kExt3MaxBlockSize);
609 TEST_AND_RETURN_FALSE(block_count > 0);
610
611 if (out_block_count) {
612 *out_block_count = block_count;
613 }
614 if (out_block_size) {
615 *out_block_size = block_size;
616 }
617 return true;
618}
619
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700620bool GetBootloader(BootLoader* out_bootloader) {
621 // For now, hardcode to syslinux.
622 *out_bootloader = BootLoader_SYSLINUX;
623 return true;
624}
625
Darin Petkova0b9e772011-10-06 05:05:56 -0700626string GetAndFreeGError(GError** error) {
627 if (!*error) {
628 return "Unknown GLib error.";
629 }
630 string message =
631 base::StringPrintf("GError(%d): %s",
632 (*error)->code,
633 (*error)->message ? (*error)->message : "(unknown)");
634 g_error_free(*error);
635 *error = NULL;
636 return message;
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700637}
638
Darin Petkov296889c2010-07-23 16:20:54 -0700639bool Reboot() {
640 vector<string> command;
641 command.push_back("/sbin/shutdown");
642 command.push_back("-r");
643 command.push_back("now");
644 int rc = 0;
Darin Petkov85d02b72011-05-17 13:25:51 -0700645 Subprocess::SynchronousExec(command, &rc, NULL);
Darin Petkov296889c2010-07-23 16:20:54 -0700646 TEST_AND_RETURN_FALSE(rc == 0);
647 return true;
648}
649
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800650namespace {
651// Do the actual trigger. We do it as a main-loop callback to (try to) get a
652// consistent stack trace.
653gboolean TriggerCrashReporterUpload(void* unused) {
654 pid_t pid = fork();
655 CHECK(pid >= 0) << "fork failed"; // fork() failed. Something is very wrong.
656 if (pid == 0) {
657 // We are the child. Crash.
658 abort(); // never returns
659 }
660 // We are the parent. Wait for child to terminate.
661 pid_t result = waitpid(pid, NULL, 0);
662 LOG_IF(ERROR, result < 0) << "waitpid() failed";
663 return FALSE; // Don't call this callback again
664}
665} // namespace {}
666
667void ScheduleCrashReporterUpload() {
668 g_idle_add(&TriggerCrashReporterUpload, NULL);
669}
670
Chris Sosa4f8ee272012-11-30 13:01:54 -0800671bool SetCpuShares(CpuShares shares) {
672 string string_shares = base::IntToString(static_cast<int>(shares));
673 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
674 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
675 if(utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
676 string_shares.size())){
677 return true;
678 } else {
679 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
680 << " using " << cpu_shares_file;
681 return false;
682 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700683}
684
Chris Sosa4f8ee272012-11-30 13:01:54 -0800685int CompareCpuShares(CpuShares shares_lhs,
686 CpuShares shares_rhs) {
687 return static_cast<int>(shares_lhs) - static_cast<int>(shares_rhs);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700688}
689
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700690int FuzzInt(int value, unsigned int range) {
691 int min = value - range / 2;
692 int max = value + range - range / 2;
693 return base::RandInt(min, max);
694}
695
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800696gboolean GlibRunClosure(gpointer data) {
697 google::protobuf::Closure* callback =
698 reinterpret_cast<google::protobuf::Closure*>(data);
699 callback->Run();
700 return FALSE;
701}
702
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700703string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800704 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700705}
706
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800707string FormatTimeDelta(TimeDelta delta) {
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700708 // Canonicalize into days, hours, minutes, seconds and microseconds.
709 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800710 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700711 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800712 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700713 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800714 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700715 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800716 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700717 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800718
719 // Construct and return string.
720 string str;
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700721 if (days)
722 base::StringAppendF(&str, "%ud", days);
723 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800724 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700725 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800726 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700727 base::StringAppendF(&str, "%u", secs);
728 if (usecs) {
729 int width = 6;
730 while ((usecs / 10) * 10 == usecs) {
731 usecs /= 10;
732 width--;
733 }
734 base::StringAppendF(&str, ".%0*u", width, usecs);
735 }
736 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800737 return str;
738}
739
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700740string ToString(const Time utc_time) {
741 Time::Exploded exp_time;
742 utc_time.UTCExplode(&exp_time);
743 return StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
744 exp_time.month,
745 exp_time.day_of_month,
746 exp_time.year,
747 exp_time.hour,
748 exp_time.minute,
749 exp_time.second);
750}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000751
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700752string ToString(bool b) {
753 return (b ? "true" : "false");
754}
755
Jay Srinivasan19409b72013-04-12 19:23:36 -0700756std::string ToString(DownloadSource source) {
757 switch (source) {
758 case kDownloadSourceHttpsServer: return "HttpsServer";
759 case kDownloadSourceHttpServer: return "HttpServer";
760 case kNumDownloadSources: return "Unknown";
761 // Don't add a default case to let the compiler warn about newly added
762 // download sources which should be added here.
763 }
764
765 return "Unknown";
766}
767
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800768ActionExitCode GetBaseErrorCode(ActionExitCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700769 // Ignore the higher order bits in the code by applying the mask as
770 // we want the enumerations to be in the small contiguous range
Jay Srinivasanedce2832012-10-24 18:57:47 -0700771 // with values less than kActionCodeUmaReportedMax.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800772 ActionExitCode base_code = static_cast<ActionExitCode>(code & ~kSpecialFlags);
Jay Srinivasanf0572052012-10-23 18:12:56 -0700773
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800774 // Make additional adjustments required for UMA and error classification.
775 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
776 // chromium-os:34369.
777 if (base_code >= kActionCodeOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700778 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800779 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800780 LOG(INFO) << "Converting error code " << base_code
781 << " to kActionCodeOmahaErrorInHTTPResponse";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800782 base_code = kActionCodeOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700783 }
784
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800785 return base_code;
786}
787
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800788// Returns a printable version of the various flags denoted in the higher order
789// bits of the given code. Returns an empty string if none of those bits are
790// set.
791string GetFlagNames(uint32_t code) {
792 uint32_t flags = code & kSpecialFlags;
793 string flag_names;
794 string separator = "";
795 for(size_t i = 0; i < sizeof(flags) * 8; i++) {
796 uint32_t flag = flags & (1 << i);
797 if (flag) {
798 flag_names += separator + CodeToString(static_cast<ActionExitCode>(flag));
799 separator = ", ";
800 }
801 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800802
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800803 return flag_names;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700804}
805
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800806void SendErrorCodeToUma(SystemState* system_state, ActionExitCode code) {
807 if (!system_state)
808 return;
809
810 ActionExitCode uma_error_code = GetBaseErrorCode(code);
811
812 // If the code doesn't have flags computed already, compute them now based on
813 // the state of the current update attempt.
814 uint32_t flags = code & kSpecialFlags;
815 if (!flags)
816 flags = system_state->update_attempter()->GetErrorCodeFlags();
817
818 // Determine the UMA bucket depending on the flags. But, ignore the resumed
819 // flag, as it's perfectly normal for production devices to resume their
820 // downloads and so we want to record those cases also in NormalErrorCodes
821 // bucket.
822 string metric = (flags & ~kActionCodeResumedFlag) ?
823 "Installer.DevModeErrorCodes" : "Installer.NormalErrorCodes";
824
825 LOG(INFO) << "Sending error code " << uma_error_code
826 << " (" << CodeToString(uma_error_code) << ")"
827 << " to UMA metric: " << metric
828 << ". Flags = " << (flags ? GetFlagNames(flags) : "None");
829
830 system_state->metrics_lib()->SendEnumToUMA(metric,
831 uma_error_code,
832 kActionCodeUmaReportedMax);
833}
834
835string CodeToString(ActionExitCode code) {
836 // If the given code has both parts (i.e. the error code part and the flags
837 // part) then strip off the flags part since the switch statement below
838 // has case statements only for the base error code or a single flag but
839 // doesn't support any combinations of those.
840 if ((code & kSpecialFlags) && (code & ~kSpecialFlags))
841 code = static_cast<ActionExitCode>(code & ~kSpecialFlags);
842 switch (code) {
843 case kActionCodeSuccess: return "kActionCodeSuccess";
844 case kActionCodeError: return "kActionCodeError";
845 case kActionCodeOmahaRequestError: return "kActionCodeOmahaRequestError";
846 case kActionCodeOmahaResponseHandlerError:
847 return "kActionCodeOmahaResponseHandlerError";
848 case kActionCodeFilesystemCopierError:
849 return "kActionCodeFilesystemCopierError";
850 case kActionCodePostinstallRunnerError:
851 return "kActionCodePostinstallRunnerError";
852 case kActionCodeSetBootableFlagError:
853 return "kActionCodeSetBootableFlagError";
854 case kActionCodeInstallDeviceOpenError:
855 return "kActionCodeInstallDeviceOpenError";
856 case kActionCodeKernelDeviceOpenError:
857 return "kActionCodeKernelDeviceOpenError";
858 case kActionCodeDownloadTransferError:
859 return "kActionCodeDownloadTransferError";
860 case kActionCodePayloadHashMismatchError:
861 return "kActionCodePayloadHashMismatchError";
862 case kActionCodePayloadSizeMismatchError:
863 return "kActionCodePayloadSizeMismatchError";
864 case kActionCodeDownloadPayloadVerificationError:
865 return "kActionCodeDownloadPayloadVerificationError";
866 case kActionCodeDownloadNewPartitionInfoError:
867 return "kActionCodeDownloadNewPartitionInfoError";
868 case kActionCodeDownloadWriteError:
869 return "kActionCodeDownloadWriteError";
870 case kActionCodeNewRootfsVerificationError:
871 return "kActionCodeNewRootfsVerificationError";
872 case kActionCodeNewKernelVerificationError:
873 return "kActionCodeNewKernelVerificationError";
874 case kActionCodeSignedDeltaPayloadExpectedError:
875 return "kActionCodeSignedDeltaPayloadExpectedError";
876 case kActionCodeDownloadPayloadPubKeyVerificationError:
877 return "kActionCodeDownloadPayloadPubKeyVerificationError";
878 case kActionCodePostinstallBootedFromFirmwareB:
879 return "kActionCodePostinstallBootedFromFirmwareB";
880 case kActionCodeDownloadStateInitializationError:
881 return "kActionCodeDownloadStateInitializationError";
882 case kActionCodeDownloadInvalidMetadataMagicString:
883 return "kActionCodeDownloadInvalidMetadataMagicString";
884 case kActionCodeDownloadSignatureMissingInManifest:
885 return "kActionCodeDownloadSignatureMissingInManifest";
886 case kActionCodeDownloadManifestParseError:
887 return "kActionCodeDownloadManifestParseError";
888 case kActionCodeDownloadMetadataSignatureError:
889 return "kActionCodeDownloadMetadataSignatureError";
890 case kActionCodeDownloadMetadataSignatureVerificationError:
891 return "kActionCodeDownloadMetadataSignatureVerificationError";
892 case kActionCodeDownloadMetadataSignatureMismatch:
893 return "kActionCodeDownloadMetadataSignatureMismatch";
894 case kActionCodeDownloadOperationHashVerificationError:
895 return "kActionCodeDownloadOperationHashVerificationError";
896 case kActionCodeDownloadOperationExecutionError:
897 return "kActionCodeDownloadOperationExecutionError";
898 case kActionCodeDownloadOperationHashMismatch:
899 return "kActionCodeDownloadOperationHashMismatch";
900 case kActionCodeOmahaRequestEmptyResponseError:
901 return "kActionCodeOmahaRequestEmptyResponseError";
902 case kActionCodeOmahaRequestXMLParseError:
903 return "kActionCodeOmahaRequestXMLParseError";
904 case kActionCodeDownloadInvalidMetadataSize:
905 return "kActionCodeDownloadInvalidMetadataSize";
906 case kActionCodeDownloadInvalidMetadataSignature:
907 return "kActionCodeDownloadInvalidMetadataSignature";
908 case kActionCodeOmahaResponseInvalid:
909 return "kActionCodeOmahaResponseInvalid";
910 case kActionCodeOmahaUpdateIgnoredPerPolicy:
911 return "kActionCodeOmahaUpdateIgnoredPerPolicy";
912 case kActionCodeOmahaUpdateDeferredPerPolicy:
913 return "kActionCodeOmahaUpdateDeferredPerPolicy";
914 case kActionCodeOmahaErrorInHTTPResponse:
915 return "kActionCodeOmahaErrorInHTTPResponse";
916 case kActionCodeDownloadOperationHashMissingError:
917 return "kActionCodeDownloadOperationHashMissingError";
918 case kActionCodeDownloadMetadataSignatureMissingError:
919 return "kActionCodeDownloadMetadataSignatureMissingError";
920 case kActionCodeOmahaUpdateDeferredForBackoff:
921 return "kActionCodeOmahaUpdateDeferredForBackoff";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700922 case kActionCodePostinstallPowerwashError:
923 return "kActionCodePostinstallPowerwashError";
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700924 case kActionCodeUpdateCanceledByChannelChange:
925 return "kActionCodeUpdateCanceledByChannelChange";
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800926 case kActionCodeUmaReportedMax:
927 return "kActionCodeUmaReportedMax";
928 case kActionCodeOmahaRequestHTTPResponseBase:
929 return "kActionCodeOmahaRequestHTTPResponseBase";
930 case kActionCodeResumedFlag:
931 return "Resumed";
932 case kActionCodeDevModeFlag:
933 return "DevMode";
934 case kActionCodeTestImageFlag:
935 return "TestImage";
936 case kActionCodeTestOmahaUrlFlag:
937 return "TestOmahaUrl";
938 case kSpecialFlags:
939 return "kSpecialFlags";
940 // Don't add a default case to let the compiler warn about newly added
941 // error codes which should be added here.
942 }
943
944 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
945}
Jay Srinivasanf0572052012-10-23 18:12:56 -0700946
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700947bool CreatePowerwashMarkerFile() {
948 bool result = utils::WriteFile(kPowerwashMarkerFile,
949 kPowerwashCommand,
950 strlen(kPowerwashCommand));
951 if (result)
952 LOG(INFO) << "Created " << kPowerwashMarkerFile
953 << " to powerwash on next reboot";
954 else
955 PLOG(ERROR) << "Error in creating powerwash marker file: "
956 << kPowerwashMarkerFile;
957
958 return result;
959}
960
961bool DeletePowerwashMarkerFile() {
962 const FilePath kPowerwashMarkerPath(kPowerwashMarkerFile);
963 bool result = file_util::Delete(kPowerwashMarkerPath, false);
964
965 if (result)
966 LOG(INFO) << "Successfully deleted the powerwash marker file : "
967 << kPowerwashMarkerFile;
968 else
969 PLOG(ERROR) << "Could not delete the powerwash marker file : "
970 << kPowerwashMarkerFile;
971
972 return result;
973}
974
David Zeuthen9a017f22013-04-11 16:10:26 -0700975
976Time GetMonotonicTime() {
977 struct timespec now_ts;
978 if (clock_gettime(CLOCK_MONOTONIC_RAW, &now_ts) != 0) {
979 // Avoid logging this as an error as call-sites may call this very
980 // often and we don't want to fill up the disk...
981 return Time();
982 }
983 struct timeval now_tv;
984 now_tv.tv_sec = now_ts.tv_sec;
985 now_tv.tv_usec = now_ts.tv_nsec/Time::kNanosecondsPerMicrosecond;
986 return Time::FromTimeVal(now_tv);
987}
988
adlr@google.com3defe6a2009-12-04 20:57:17 +0000989} // namespace utils
990
991} // namespace chromeos_update_engine