blob: 3853b94b3984e73f5a08797bc23da7ecc15d2d7b [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";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070062const char* const kStatefulPartition = "/mnt/stateful_partition";
Darin Petkov2a0e6332010-09-24 14:43:41 -070063
Chris Sosa4f8ee272012-11-30 13:01:54 -080064// Cgroup container is created in update-engine's upstart script located at
65// /etc/init/update-engine.conf.
66static const char kCGroupDir[] = "/sys/fs/cgroup/cpu/update-engine";
67
Darin Petkov33d30642010-08-04 10:18:57 -070068bool IsOfficialBuild() {
Darin Petkova07586b2010-10-20 13:41:15 -070069 return !file_util::PathExists(FilePath(kDevImageMarker));
Darin Petkov33d30642010-08-04 10:18:57 -070070}
71
Darin Petkovc91dd6b2011-01-10 12:31:34 -080072bool IsNormalBootMode() {
Darin Petkov44d98d92011-03-21 16:08:11 -070073 // TODO(petkov): Convert to a library call once a crossystem library is
74 // available (crosbug.com/13291).
75 int exit_code = 0;
76 vector<string> cmd(1, "/usr/bin/crossystem");
77 cmd.push_back("devsw_boot?1");
78
79 // Assume dev mode if the dev switch is set to 1 and there was no error
80 // executing crossystem. Assume normal mode otherwise.
Darin Petkov85d02b72011-05-17 13:25:51 -070081 bool success = Subprocess::SynchronousExec(cmd, &exit_code, NULL);
Darin Petkov44d98d92011-03-21 16:08:11 -070082 bool dev_mode = success && exit_code == 0;
83 LOG_IF(INFO, dev_mode) << "Booted in dev mode.";
84 return !dev_mode;
Darin Petkovc91dd6b2011-01-10 12:31:34 -080085}
86
Darin Petkovf2065b42011-05-17 16:36:27 -070087string GetHardwareClass() {
88 // TODO(petkov): Convert to a library call once a crossystem library is
89 // available (crosbug.com/13291).
90 int exit_code = 0;
91 vector<string> cmd(1, "/usr/bin/crossystem");
92 cmd.push_back("hwid");
93
94 string hwid;
95 bool success = Subprocess::SynchronousExec(cmd, &exit_code, &hwid);
96 if (success && !exit_code) {
97 TrimWhitespaceASCII(hwid, TRIM_ALL, &hwid);
98 return hwid;
99 }
100 LOG(ERROR) << "Unable to read HWID (" << exit_code << ") " << hwid;
101 return "";
102}
103
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800104bool WriteFile(const char* path, const char* data, int data_len) {
105 DirectFileWriter writer;
106 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
107 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700108 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800109 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800110 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800111 return true;
112}
113
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700114bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700115 const char* c_buf = static_cast<const char*>(buf);
116 ssize_t bytes_written = 0;
117 while (bytes_written < static_cast<ssize_t>(count)) {
118 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
119 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
120 bytes_written += rc;
121 }
122 return true;
123}
124
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700125bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
126 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700127 size_t bytes_written = 0;
128 int num_attempts = 0;
129 while (bytes_written < count) {
130 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700131 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
132 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700133 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
134 if (rc < 0) {
135 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
136 << " bytes_written=" << bytes_written
137 << " count=" << count << " offset=" << offset;
138 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700139 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
140 bytes_written += rc;
141 }
142 return true;
143}
144
145bool PReadAll(int fd, void* buf, size_t count, off_t offset,
146 ssize_t* out_bytes_read) {
147 char* c_buf = static_cast<char*>(buf);
148 ssize_t bytes_read = 0;
149 while (bytes_read < static_cast<ssize_t>(count)) {
150 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
151 offset + bytes_read);
152 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
153 if (rc == 0) {
154 break;
155 }
156 bytes_read += rc;
157 }
158 *out_bytes_read = bytes_read;
159 return true;
Darin Petkov296889c2010-07-23 16:20:54 -0700160
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700161}
162
Gilad Arnold19a45f02012-07-19 12:36:10 -0700163// Append |nbytes| of content from |buf| to the vector pointed to by either
164// |vec_p| or |str_p|.
165static void AppendBytes(const char* buf, size_t nbytes,
166 std::vector<char>* vec_p) {
167 CHECK(buf);
168 CHECK(vec_p);
169 vec_p->insert(vec_p->end(), buf, buf + nbytes);
170}
171static void AppendBytes(const char* buf, size_t nbytes,
172 std::string* str_p) {
173 CHECK(buf);
174 CHECK(str_p);
175 str_p->append(buf, nbytes);
176}
177
178// Reads from an open file |fp|, appending the read content to the container
179// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200180// file's content, false otherwise. If |size| is not -1, reads up to |size|
181// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700182template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200183static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700184 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200185 CHECK(size == -1 || size >= 0);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700186 char buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200187 while (size == -1 || size > 0) {
188 off_t bytes_to_read = sizeof(buf);
189 if (size > 0 && bytes_to_read > size) {
190 bytes_to_read = size;
191 }
192 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
193 if (!nbytes) {
194 break;
195 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700196 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200197 if (size != -1) {
198 CHECK(size >= static_cast<off_t>(nbytes));
199 size -= nbytes;
200 }
201 }
202 if (ferror(fp)) {
203 return false;
204 }
205 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700206}
207
Darin Petkov8e447e02013-04-16 16:23:50 +0200208// Opens a file |path| for reading and appends its the contents to a container
209// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
210// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700211template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200212static bool ReadFileChunkAndAppend(const std::string& path,
213 off_t offset,
214 off_t size,
215 T* out_p) {
216 CHECK_GE(offset, 0);
217 CHECK(size == -1 || size >= 0);
218 file_util::ScopedFILE fp(fopen(path.c_str(), "r"));
219 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000220 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200221 if (offset) {
222 // Return success without appending any data if a chunk beyond the end of
223 // the file is requested.
224 if (offset >= FileSize(path)) {
225 return true;
226 }
227 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
228 }
229 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000230}
231
Gilad Arnold19a45f02012-07-19 12:36:10 -0700232// Invokes a pipe |cmd|, then uses |append_func| to append its stdout to a
233// container |out_p|.
234template <class T>
235static bool ReadPipeAndAppend(const std::string& cmd, T* out_p) {
236 FILE* fp = popen(cmd.c_str(), "r");
237 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000238 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200239 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700240 return (success && pclose(fp) >= 0);
241}
242
243
Darin Petkov8e447e02013-04-16 16:23:50 +0200244bool ReadFile(const string& path, vector<char>* out_p) {
245 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700246}
247
Darin Petkov8e447e02013-04-16 16:23:50 +0200248bool ReadFile(const string& path, string* out_p) {
249 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700250}
251
Darin Petkov8e447e02013-04-16 16:23:50 +0200252bool ReadFileChunk(const string& path, off_t offset, off_t size,
253 vector<char>* out_p) {
254 return ReadFileChunkAndAppend(path, offset, size, out_p);
255}
256
257bool ReadPipe(const string& cmd, vector<char>* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700258 return ReadPipeAndAppend(cmd, out_p);
259}
260
Darin Petkov8e447e02013-04-16 16:23:50 +0200261bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700262 return ReadPipeAndAppend(cmd, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000263}
264
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700265off_t FileSize(const string& path) {
266 struct stat stbuf;
267 int rc = stat(path.c_str(), &stbuf);
268 CHECK_EQ(rc, 0);
269 if (rc < 0)
270 return rc;
271 return stbuf.st_size;
272}
273
adlr@google.com3defe6a2009-12-04 20:57:17 +0000274void HexDumpArray(const unsigned char* const arr, const size_t length) {
275 const unsigned char* const char_arr =
276 reinterpret_cast<const unsigned char* const>(arr);
277 LOG(INFO) << "Logging array of length: " << length;
278 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700279 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000280 const unsigned int bytes_remaining = length - i;
281 const unsigned int bytes_per_this_line = min(bytes_per_line,
282 bytes_remaining);
283 char header[100];
284 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
285 TEST_AND_RETURN(r == 13);
286 string line = header;
287 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
288 char buf[20];
289 unsigned char c = char_arr[i + j];
290 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
291 TEST_AND_RETURN(r == 3);
292 line += buf;
293 }
294 LOG(INFO) << line;
295 }
296}
297
298namespace {
299class ScopedDirCloser {
300 public:
301 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
302 ~ScopedDirCloser() {
303 if (dir_ && *dir_) {
304 int r = closedir(*dir_);
305 TEST_AND_RETURN_ERRNO(r == 0);
306 *dir_ = NULL;
307 dir_ = NULL;
308 }
309 }
310 private:
311 DIR** dir_;
312};
313} // namespace {}
314
315bool RecursiveUnlinkDir(const std::string& path) {
316 struct stat stbuf;
317 int r = lstat(path.c_str(), &stbuf);
318 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
319 if ((r < 0) && (errno == ENOENT))
320 // path request is missing. that's fine.
321 return true;
322 if (!S_ISDIR(stbuf.st_mode)) {
323 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700324 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000325 // success or path disappeared before we could unlink.
326 return true;
327 }
328 {
329 // We have a dir, unlink all children, then delete dir
330 DIR *dir = opendir(path.c_str());
331 TEST_AND_RETURN_FALSE_ERRNO(dir);
332 ScopedDirCloser dir_closer(&dir);
333 struct dirent dir_entry;
334 struct dirent *dir_entry_p;
335 int err = 0;
336 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
337 if (dir_entry_p == NULL) {
338 // end of stream reached
339 break;
340 }
341 // Skip . and ..
342 if (!strcmp(dir_entry_p->d_name, ".") ||
343 !strcmp(dir_entry_p->d_name, ".."))
344 continue;
345 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700346 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000347 }
348 TEST_AND_RETURN_FALSE(err == 0);
349 }
350 // unlink dir
351 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
352 return true;
353}
354
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700355string RootDevice(const string& partition_device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700356 FilePath device_path(partition_device);
357 if (device_path.DirName().value() != "/dev") {
358 return "";
359 }
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700360 string::const_iterator it = --partition_device.end();
361 for (; it >= partition_device.begin(); --it) {
362 if (!isdigit(*it))
363 break;
364 }
365 // Some devices contain a p before the partitions. For example:
366 // /dev/mmc0p4 should be shortened to /dev/mmc0.
367 if (*it == 'p')
368 --it;
369 return string(partition_device.begin(), it + 1);
370}
371
372string PartitionNumber(const string& partition_device) {
373 CHECK(!partition_device.empty());
374 string::const_iterator it = --partition_device.end();
375 for (; it >= partition_device.begin(); --it) {
376 if (!isdigit(*it))
377 break;
378 }
379 return string(it + 1, partition_device.end());
380}
381
Darin Petkovf74eb652010-08-04 12:08:38 -0700382string SysfsBlockDevice(const string& device) {
383 FilePath device_path(device);
384 if (device_path.DirName().value() != "/dev") {
385 return "";
386 }
387 return FilePath("/sys/block").Append(device_path.BaseName()).value();
388}
389
390bool IsRemovableDevice(const std::string& device) {
391 string sysfs_block = SysfsBlockDevice(device);
392 string removable;
393 if (sysfs_block.empty() ||
394 !file_util::ReadFileToString(FilePath(sysfs_block).Append("removable"),
395 &removable)) {
396 return false;
397 }
398 TrimWhitespaceASCII(removable, TRIM_ALL, &removable);
399 return removable == "1";
400}
401
adlr@google.com3defe6a2009-12-04 20:57:17 +0000402std::string ErrnoNumberAsString(int err) {
403 char buf[100];
404 buf[0] = '\0';
405 return strerror_r(err, buf, sizeof(buf));
406}
407
408std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
409 string ret;
410 bool last_insert_was_slash = false;
411 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
412 if (*it == '/') {
413 if (last_insert_was_slash)
414 continue;
415 last_insert_was_slash = true;
416 } else {
417 last_insert_was_slash = false;
418 }
419 ret.push_back(*it);
420 }
421 if (strip_trailing_slash && last_insert_was_slash) {
422 string::size_type last_non_slash = ret.find_last_not_of('/');
423 if (last_non_slash != string::npos) {
424 ret.resize(last_non_slash + 1);
425 } else {
426 ret = "";
427 }
428 }
429 return ret;
430}
431
432bool FileExists(const char* path) {
433 struct stat stbuf;
434 return 0 == lstat(path, &stbuf);
435}
436
Darin Petkov30291ed2010-11-12 10:23:06 -0800437bool IsSymlink(const char* path) {
438 struct stat stbuf;
439 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
440}
441
adlr@google.com3defe6a2009-12-04 20:57:17 +0000442std::string TempFilename(string path) {
443 static const string suffix("XXXXXX");
444 CHECK(StringHasSuffix(path, suffix));
445 do {
446 string new_suffix;
447 for (unsigned int i = 0; i < suffix.size(); i++) {
448 int r = rand() % (26 * 2 + 10); // [a-zA-Z0-9]
449 if (r < 26)
450 new_suffix.append(1, 'a' + r);
451 else if (r < (26 * 2))
452 new_suffix.append(1, 'A' + r - 26);
453 else
454 new_suffix.append(1, '0' + r - (26 * 2));
455 }
456 CHECK_EQ(new_suffix.size(), suffix.size());
457 path.resize(path.size() - new_suffix.size());
458 path.append(new_suffix);
459 } while (FileExists(path.c_str()));
460 return path;
461}
462
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700463bool MakeTempFile(const std::string& filename_template,
464 std::string* filename,
465 int* fd) {
466 DCHECK(filename || fd);
467 vector<char> buf(filename_template.size() + 1);
468 memcpy(&buf[0], filename_template.data(), filename_template.size());
469 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700470
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700471 int mkstemp_fd = mkstemp(&buf[0]);
472 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
473 if (filename) {
474 *filename = &buf[0];
475 }
476 if (fd) {
477 *fd = mkstemp_fd;
478 } else {
479 close(mkstemp_fd);
480 }
481 return true;
482}
483
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700484bool MakeTempDirectory(const std::string& dirname_template,
485 std::string* dirname) {
486 DCHECK(dirname);
487 vector<char> buf(dirname_template.size() + 1);
488 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
489 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700490
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700491 char* return_code = mkdtemp(&buf[0]);
492 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
493 *dirname = &buf[0];
494 return true;
495}
496
adlr@google.com3defe6a2009-12-04 20:57:17 +0000497bool StringHasSuffix(const std::string& str, const std::string& suffix) {
498 if (suffix.size() > str.size())
499 return false;
500 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
501}
502
503bool StringHasPrefix(const std::string& str, const std::string& prefix) {
504 if (prefix.size() > str.size())
505 return false;
506 return 0 == str.compare(0, prefix.size(), prefix);
507}
508
Will Drewry8f71da82010-08-30 14:07:11 -0500509const std::string BootDevice() {
510 char boot_path[PATH_MAX];
511 // Resolve the boot device path fully, including dereferencing
512 // through dm-verity.
513 int ret = rootdev(boot_path, sizeof(boot_path), true, false);
514
515 if (ret < 0) {
516 LOG(ERROR) << "rootdev failed to find the root device";
adlr@google.com3defe6a2009-12-04 20:57:17 +0000517 return "";
518 }
Will Drewry8f71da82010-08-30 14:07:11 -0500519 LOG_IF(WARNING, ret > 0) << "rootdev found a device name with no device node";
520
521 // This local variable is used to construct the return string and is not
522 // passed around after use.
523 return boot_path;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000524}
525
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700526const string BootKernelDevice(const std::string& boot_device) {
527 // Currntly this assumes the last digit of the boot device is
528 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
529 // get the kernel device.
530 string ret = boot_device;
531 if (ret.empty())
532 return ret;
533 char last_char = ret[ret.size() - 1];
534 if (last_char == '3' || last_char == '5' || last_char == '7') {
535 ret[ret.size() - 1] = last_char - 1;
536 return ret;
537 }
538 return "";
539}
540
adlr@google.com3defe6a2009-12-04 20:57:17 +0000541bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700542 const string& mountpoint,
543 unsigned long mountflags) {
544 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000545 if (rc < 0) {
546 string msg = ErrnoNumberAsString(errno);
547 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
548 << device << " on " << mountpoint;
549 return false;
550 }
551 return true;
552}
553
554bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700555 for (int num_retries = 0; ; ++num_retries) {
556 if (umount(mountpoint.c_str()) == 0)
557 break;
558
559 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
560 num_retries < kUnmountMaxNumOfRetries);
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800561 g_usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700562 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000563 return true;
564}
565
Darin Petkovd3f8c892010-10-12 21:38:45 -0700566bool GetFilesystemSize(const std::string& device,
567 int* out_block_count,
568 int* out_block_size) {
569 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
570 TEST_AND_RETURN_FALSE(fd >= 0);
571 ScopedFdCloser fd_closer(&fd);
572 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
573}
574
575bool GetFilesystemSizeFromFD(int fd,
576 int* out_block_count,
577 int* out_block_size) {
578 TEST_AND_RETURN_FALSE(fd >= 0);
579
580 // Determine the ext3 filesystem size by directly reading the block count and
581 // block size information from the superblock. See include/linux/ext3_fs.h for
582 // more details on the structure.
583 ssize_t kBufferSize = 16 * sizeof(uint32_t);
584 char buffer[kBufferSize];
585 const int kSuperblockOffset = 1024;
586 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
587 kBufferSize) {
588 PLOG(ERROR) << "Unable to determine file system size:";
589 return false;
590 }
591 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
592 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
593 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
594 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
595 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
596 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
597 block_count = le32toh(block_count);
598 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
599 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
600 magic = le16toh(magic);
601
602 // Sanity check the parameters.
603 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
604 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
605 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
606 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
607 int block_size = 1 << log_block_size;
608 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
609 block_size <= kExt3MaxBlockSize);
610 TEST_AND_RETURN_FALSE(block_count > 0);
611
612 if (out_block_count) {
613 *out_block_count = block_count;
614 }
615 if (out_block_size) {
616 *out_block_size = block_size;
617 }
618 return true;
619}
620
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700621bool GetBootloader(BootLoader* out_bootloader) {
622 // For now, hardcode to syslinux.
623 *out_bootloader = BootLoader_SYSLINUX;
624 return true;
625}
626
Darin Petkova0b9e772011-10-06 05:05:56 -0700627string GetAndFreeGError(GError** error) {
628 if (!*error) {
629 return "Unknown GLib error.";
630 }
631 string message =
632 base::StringPrintf("GError(%d): %s",
633 (*error)->code,
634 (*error)->message ? (*error)->message : "(unknown)");
635 g_error_free(*error);
636 *error = NULL;
637 return message;
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700638}
639
Darin Petkov296889c2010-07-23 16:20:54 -0700640bool Reboot() {
641 vector<string> command;
642 command.push_back("/sbin/shutdown");
643 command.push_back("-r");
644 command.push_back("now");
645 int rc = 0;
Darin Petkov85d02b72011-05-17 13:25:51 -0700646 Subprocess::SynchronousExec(command, &rc, NULL);
Darin Petkov296889c2010-07-23 16:20:54 -0700647 TEST_AND_RETURN_FALSE(rc == 0);
648 return true;
649}
650
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800651namespace {
652// Do the actual trigger. We do it as a main-loop callback to (try to) get a
653// consistent stack trace.
654gboolean TriggerCrashReporterUpload(void* unused) {
655 pid_t pid = fork();
656 CHECK(pid >= 0) << "fork failed"; // fork() failed. Something is very wrong.
657 if (pid == 0) {
658 // We are the child. Crash.
659 abort(); // never returns
660 }
661 // We are the parent. Wait for child to terminate.
662 pid_t result = waitpid(pid, NULL, 0);
663 LOG_IF(ERROR, result < 0) << "waitpid() failed";
664 return FALSE; // Don't call this callback again
665}
666} // namespace {}
667
668void ScheduleCrashReporterUpload() {
669 g_idle_add(&TriggerCrashReporterUpload, NULL);
670}
671
Chris Sosa4f8ee272012-11-30 13:01:54 -0800672bool SetCpuShares(CpuShares shares) {
673 string string_shares = base::IntToString(static_cast<int>(shares));
674 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
675 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
676 if(utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
677 string_shares.size())){
678 return true;
679 } else {
680 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
681 << " using " << cpu_shares_file;
682 return false;
683 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700684}
685
Chris Sosa4f8ee272012-11-30 13:01:54 -0800686int CompareCpuShares(CpuShares shares_lhs,
687 CpuShares shares_rhs) {
688 return static_cast<int>(shares_lhs) - static_cast<int>(shares_rhs);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700689}
690
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700691int FuzzInt(int value, unsigned int range) {
692 int min = value - range / 2;
693 int max = value + range - range / 2;
694 return base::RandInt(min, max);
695}
696
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800697gboolean GlibRunClosure(gpointer data) {
698 google::protobuf::Closure* callback =
699 reinterpret_cast<google::protobuf::Closure*>(data);
700 callback->Run();
701 return FALSE;
702}
703
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700704string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800705 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700706}
707
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800708string FormatTimeDelta(TimeDelta delta) {
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700709 // Canonicalize into days, hours, minutes, seconds and microseconds.
710 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800711 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700712 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800713 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700714 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800715 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700716 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800717 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700718 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800719
720 // Construct and return string.
721 string str;
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700722 if (days)
723 base::StringAppendF(&str, "%ud", days);
724 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800725 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700726 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800727 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700728 base::StringAppendF(&str, "%u", secs);
729 if (usecs) {
730 int width = 6;
731 while ((usecs / 10) * 10 == usecs) {
732 usecs /= 10;
733 width--;
734 }
735 base::StringAppendF(&str, ".%0*u", width, usecs);
736 }
737 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800738 return str;
739}
740
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700741string ToString(const Time utc_time) {
742 Time::Exploded exp_time;
743 utc_time.UTCExplode(&exp_time);
744 return StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
745 exp_time.month,
746 exp_time.day_of_month,
747 exp_time.year,
748 exp_time.hour,
749 exp_time.minute,
750 exp_time.second);
751}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000752
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700753string ToString(bool b) {
754 return (b ? "true" : "false");
755}
756
Jay Srinivasan19409b72013-04-12 19:23:36 -0700757std::string ToString(DownloadSource source) {
758 switch (source) {
759 case kDownloadSourceHttpsServer: return "HttpsServer";
760 case kDownloadSourceHttpServer: return "HttpServer";
761 case kNumDownloadSources: return "Unknown";
762 // Don't add a default case to let the compiler warn about newly added
763 // download sources which should be added here.
764 }
765
766 return "Unknown";
767}
768
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800769ActionExitCode GetBaseErrorCode(ActionExitCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700770 // Ignore the higher order bits in the code by applying the mask as
771 // we want the enumerations to be in the small contiguous range
Jay Srinivasanedce2832012-10-24 18:57:47 -0700772 // with values less than kActionCodeUmaReportedMax.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800773 ActionExitCode base_code = static_cast<ActionExitCode>(code & ~kSpecialFlags);
Jay Srinivasanf0572052012-10-23 18:12:56 -0700774
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800775 // Make additional adjustments required for UMA and error classification.
776 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
777 // chromium-os:34369.
778 if (base_code >= kActionCodeOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700779 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800780 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800781 LOG(INFO) << "Converting error code " << base_code
782 << " to kActionCodeOmahaErrorInHTTPResponse";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800783 base_code = kActionCodeOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700784 }
785
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800786 return base_code;
787}
788
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800789// Returns a printable version of the various flags denoted in the higher order
790// bits of the given code. Returns an empty string if none of those bits are
791// set.
792string GetFlagNames(uint32_t code) {
793 uint32_t flags = code & kSpecialFlags;
794 string flag_names;
795 string separator = "";
796 for(size_t i = 0; i < sizeof(flags) * 8; i++) {
797 uint32_t flag = flags & (1 << i);
798 if (flag) {
799 flag_names += separator + CodeToString(static_cast<ActionExitCode>(flag));
800 separator = ", ";
801 }
802 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800803
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800804 return flag_names;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700805}
806
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800807void SendErrorCodeToUma(SystemState* system_state, ActionExitCode code) {
808 if (!system_state)
809 return;
810
811 ActionExitCode uma_error_code = GetBaseErrorCode(code);
812
813 // If the code doesn't have flags computed already, compute them now based on
814 // the state of the current update attempt.
815 uint32_t flags = code & kSpecialFlags;
816 if (!flags)
817 flags = system_state->update_attempter()->GetErrorCodeFlags();
818
819 // Determine the UMA bucket depending on the flags. But, ignore the resumed
820 // flag, as it's perfectly normal for production devices to resume their
821 // downloads and so we want to record those cases also in NormalErrorCodes
822 // bucket.
823 string metric = (flags & ~kActionCodeResumedFlag) ?
824 "Installer.DevModeErrorCodes" : "Installer.NormalErrorCodes";
825
826 LOG(INFO) << "Sending error code " << uma_error_code
827 << " (" << CodeToString(uma_error_code) << ")"
828 << " to UMA metric: " << metric
829 << ". Flags = " << (flags ? GetFlagNames(flags) : "None");
830
831 system_state->metrics_lib()->SendEnumToUMA(metric,
832 uma_error_code,
833 kActionCodeUmaReportedMax);
834}
835
836string CodeToString(ActionExitCode code) {
837 // If the given code has both parts (i.e. the error code part and the flags
838 // part) then strip off the flags part since the switch statement below
839 // has case statements only for the base error code or a single flag but
840 // doesn't support any combinations of those.
841 if ((code & kSpecialFlags) && (code & ~kSpecialFlags))
842 code = static_cast<ActionExitCode>(code & ~kSpecialFlags);
843 switch (code) {
844 case kActionCodeSuccess: return "kActionCodeSuccess";
845 case kActionCodeError: return "kActionCodeError";
846 case kActionCodeOmahaRequestError: return "kActionCodeOmahaRequestError";
847 case kActionCodeOmahaResponseHandlerError:
848 return "kActionCodeOmahaResponseHandlerError";
849 case kActionCodeFilesystemCopierError:
850 return "kActionCodeFilesystemCopierError";
851 case kActionCodePostinstallRunnerError:
852 return "kActionCodePostinstallRunnerError";
853 case kActionCodeSetBootableFlagError:
854 return "kActionCodeSetBootableFlagError";
855 case kActionCodeInstallDeviceOpenError:
856 return "kActionCodeInstallDeviceOpenError";
857 case kActionCodeKernelDeviceOpenError:
858 return "kActionCodeKernelDeviceOpenError";
859 case kActionCodeDownloadTransferError:
860 return "kActionCodeDownloadTransferError";
861 case kActionCodePayloadHashMismatchError:
862 return "kActionCodePayloadHashMismatchError";
863 case kActionCodePayloadSizeMismatchError:
864 return "kActionCodePayloadSizeMismatchError";
865 case kActionCodeDownloadPayloadVerificationError:
866 return "kActionCodeDownloadPayloadVerificationError";
867 case kActionCodeDownloadNewPartitionInfoError:
868 return "kActionCodeDownloadNewPartitionInfoError";
869 case kActionCodeDownloadWriteError:
870 return "kActionCodeDownloadWriteError";
871 case kActionCodeNewRootfsVerificationError:
872 return "kActionCodeNewRootfsVerificationError";
873 case kActionCodeNewKernelVerificationError:
874 return "kActionCodeNewKernelVerificationError";
875 case kActionCodeSignedDeltaPayloadExpectedError:
876 return "kActionCodeSignedDeltaPayloadExpectedError";
877 case kActionCodeDownloadPayloadPubKeyVerificationError:
878 return "kActionCodeDownloadPayloadPubKeyVerificationError";
879 case kActionCodePostinstallBootedFromFirmwareB:
880 return "kActionCodePostinstallBootedFromFirmwareB";
881 case kActionCodeDownloadStateInitializationError:
882 return "kActionCodeDownloadStateInitializationError";
883 case kActionCodeDownloadInvalidMetadataMagicString:
884 return "kActionCodeDownloadInvalidMetadataMagicString";
885 case kActionCodeDownloadSignatureMissingInManifest:
886 return "kActionCodeDownloadSignatureMissingInManifest";
887 case kActionCodeDownloadManifestParseError:
888 return "kActionCodeDownloadManifestParseError";
889 case kActionCodeDownloadMetadataSignatureError:
890 return "kActionCodeDownloadMetadataSignatureError";
891 case kActionCodeDownloadMetadataSignatureVerificationError:
892 return "kActionCodeDownloadMetadataSignatureVerificationError";
893 case kActionCodeDownloadMetadataSignatureMismatch:
894 return "kActionCodeDownloadMetadataSignatureMismatch";
895 case kActionCodeDownloadOperationHashVerificationError:
896 return "kActionCodeDownloadOperationHashVerificationError";
897 case kActionCodeDownloadOperationExecutionError:
898 return "kActionCodeDownloadOperationExecutionError";
899 case kActionCodeDownloadOperationHashMismatch:
900 return "kActionCodeDownloadOperationHashMismatch";
901 case kActionCodeOmahaRequestEmptyResponseError:
902 return "kActionCodeOmahaRequestEmptyResponseError";
903 case kActionCodeOmahaRequestXMLParseError:
904 return "kActionCodeOmahaRequestXMLParseError";
905 case kActionCodeDownloadInvalidMetadataSize:
906 return "kActionCodeDownloadInvalidMetadataSize";
907 case kActionCodeDownloadInvalidMetadataSignature:
908 return "kActionCodeDownloadInvalidMetadataSignature";
909 case kActionCodeOmahaResponseInvalid:
910 return "kActionCodeOmahaResponseInvalid";
911 case kActionCodeOmahaUpdateIgnoredPerPolicy:
912 return "kActionCodeOmahaUpdateIgnoredPerPolicy";
913 case kActionCodeOmahaUpdateDeferredPerPolicy:
914 return "kActionCodeOmahaUpdateDeferredPerPolicy";
915 case kActionCodeOmahaErrorInHTTPResponse:
916 return "kActionCodeOmahaErrorInHTTPResponse";
917 case kActionCodeDownloadOperationHashMissingError:
918 return "kActionCodeDownloadOperationHashMissingError";
919 case kActionCodeDownloadMetadataSignatureMissingError:
920 return "kActionCodeDownloadMetadataSignatureMissingError";
921 case kActionCodeOmahaUpdateDeferredForBackoff:
922 return "kActionCodeOmahaUpdateDeferredForBackoff";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700923 case kActionCodePostinstallPowerwashError:
924 return "kActionCodePostinstallPowerwashError";
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700925 case kActionCodeUpdateCanceledByChannelChange:
926 return "kActionCodeUpdateCanceledByChannelChange";
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800927 case kActionCodeUmaReportedMax:
928 return "kActionCodeUmaReportedMax";
929 case kActionCodeOmahaRequestHTTPResponseBase:
930 return "kActionCodeOmahaRequestHTTPResponseBase";
931 case kActionCodeResumedFlag:
932 return "Resumed";
933 case kActionCodeDevModeFlag:
934 return "DevMode";
935 case kActionCodeTestImageFlag:
936 return "TestImage";
937 case kActionCodeTestOmahaUrlFlag:
938 return "TestOmahaUrl";
939 case kSpecialFlags:
940 return "kSpecialFlags";
941 // Don't add a default case to let the compiler warn about newly added
942 // error codes which should be added here.
943 }
944
945 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
946}
Jay Srinivasanf0572052012-10-23 18:12:56 -0700947
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700948bool CreatePowerwashMarkerFile() {
949 bool result = utils::WriteFile(kPowerwashMarkerFile,
950 kPowerwashCommand,
951 strlen(kPowerwashCommand));
952 if (result)
953 LOG(INFO) << "Created " << kPowerwashMarkerFile
954 << " to powerwash on next reboot";
955 else
956 PLOG(ERROR) << "Error in creating powerwash marker file: "
957 << kPowerwashMarkerFile;
958
959 return result;
960}
961
962bool DeletePowerwashMarkerFile() {
963 const FilePath kPowerwashMarkerPath(kPowerwashMarkerFile);
964 bool result = file_util::Delete(kPowerwashMarkerPath, false);
965
966 if (result)
967 LOG(INFO) << "Successfully deleted the powerwash marker file : "
968 << kPowerwashMarkerFile;
969 else
970 PLOG(ERROR) << "Could not delete the powerwash marker file : "
971 << kPowerwashMarkerFile;
972
973 return result;
974}
975
David Zeuthen9a017f22013-04-11 16:10:26 -0700976
977Time GetMonotonicTime() {
978 struct timespec now_ts;
979 if (clock_gettime(CLOCK_MONOTONIC_RAW, &now_ts) != 0) {
980 // Avoid logging this as an error as call-sites may call this very
981 // often and we don't want to fill up the disk...
982 return Time();
983 }
984 struct timeval now_tv;
985 now_tv.tv_sec = now_ts.tv_sec;
986 now_tv.tv_usec = now_ts.tv_nsec/Time::kNanosecondsPerMicrosecond;
987 return Time::FromTimeVal(now_tv);
988}
989
adlr@google.com3defe6a2009-12-04 20:57:17 +0000990} // namespace utils
991
992} // namespace chromeos_update_engine