blob: be98a71478831e58909a845f301f3704ff0ab72c [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>
18#include <unistd.h>
Darin Petkovf74eb652010-08-04 12:08:38 -070019
adlr@google.com3defe6a2009-12-04 20:57:17 +000020#include <algorithm>
Darin Petkovf74eb652010-08-04 12:08:38 -070021
Will Drewry8f71da82010-08-30 14:07:11 -050022#include <base/file_path.h>
23#include <base/file_util.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040024#include <base/logging.h>
Chris Sosafc661a12013-02-26 14:43:21 -080025#include <base/posix/eintr_wrapper.h>
Will Drewry8f71da82010-08-30 14:07:11 -050026#include <base/rand_util.h>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070027#include <base/string_number_conversions.h>
Will Drewry8f71da82010-08-30 14:07:11 -050028#include <base/string_util.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040029#include <base/stringprintf.h>
Gilad Arnold8e3f1262013-01-08 14:59:54 -080030#include <glib.h>
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -080031#include <google/protobuf/stubs/common.h>
Will Drewry8f71da82010-08-30 14:07:11 -050032#include <rootdev/rootdev.h>
33
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070034#include "update_engine/constants.h"
Andrew de los Reyes970bb282009-12-09 16:34:04 -080035#include "update_engine/file_writer.h"
Darin Petkov33d30642010-08-04 10:18:57 -070036#include "update_engine/omaha_request_params.h"
Darin Petkov296889c2010-07-23 16:20:54 -070037#include "update_engine/subprocess.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080038#include "update_engine/system_state.h"
39#include "update_engine/update_attempter.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000040
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070041using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080042using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000043using std::min;
44using std::string;
45using std::vector;
46
47namespace chromeos_update_engine {
48
Ben Chan77a1eba2012-10-07 22:54:55 -070049namespace {
50
51// The following constants control how UnmountFilesystem should retry if
52// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
53// one second.
54const int kUnmountMaxNumOfRetries = 5;
55const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Ben Chan77a1eba2012-10-07 22:54:55 -070056} // namespace
57
adlr@google.com3defe6a2009-12-04 20:57:17 +000058namespace utils {
59
Darin Petkova07586b2010-10-20 13:41:15 -070060static const char kDevImageMarker[] = "/root/.dev_mode";
Darin Petkov2a0e6332010-09-24 14:43:41 -070061
Chris Sosa4f8ee272012-11-30 13:01:54 -080062// Cgroup container is created in update-engine's upstart script located at
63// /etc/init/update-engine.conf.
64static const char kCGroupDir[] = "/sys/fs/cgroup/cpu/update-engine";
65
Darin Petkov33d30642010-08-04 10:18:57 -070066bool IsOfficialBuild() {
Darin Petkova07586b2010-10-20 13:41:15 -070067 return !file_util::PathExists(FilePath(kDevImageMarker));
Darin Petkov33d30642010-08-04 10:18:57 -070068}
69
Darin Petkovc91dd6b2011-01-10 12:31:34 -080070bool IsNormalBootMode() {
Darin Petkov44d98d92011-03-21 16:08:11 -070071 // TODO(petkov): Convert to a library call once a crossystem library is
72 // available (crosbug.com/13291).
73 int exit_code = 0;
74 vector<string> cmd(1, "/usr/bin/crossystem");
75 cmd.push_back("devsw_boot?1");
76
77 // Assume dev mode if the dev switch is set to 1 and there was no error
78 // executing crossystem. Assume normal mode otherwise.
Darin Petkov85d02b72011-05-17 13:25:51 -070079 bool success = Subprocess::SynchronousExec(cmd, &exit_code, NULL);
Darin Petkov44d98d92011-03-21 16:08:11 -070080 bool dev_mode = success && exit_code == 0;
81 LOG_IF(INFO, dev_mode) << "Booted in dev mode.";
82 return !dev_mode;
Darin Petkovc91dd6b2011-01-10 12:31:34 -080083}
84
Darin Petkovf2065b42011-05-17 16:36:27 -070085string GetHardwareClass() {
86 // TODO(petkov): Convert to a library call once a crossystem library is
87 // available (crosbug.com/13291).
88 int exit_code = 0;
89 vector<string> cmd(1, "/usr/bin/crossystem");
90 cmd.push_back("hwid");
91
92 string hwid;
93 bool success = Subprocess::SynchronousExec(cmd, &exit_code, &hwid);
94 if (success && !exit_code) {
95 TrimWhitespaceASCII(hwid, TRIM_ALL, &hwid);
96 return hwid;
97 }
98 LOG(ERROR) << "Unable to read HWID (" << exit_code << ") " << hwid;
99 return "";
100}
101
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800102bool WriteFile(const char* path, const char* data, int data_len) {
103 DirectFileWriter writer;
104 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
105 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700106 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800107 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800108 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800109 return true;
110}
111
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700112bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700113 const char* c_buf = static_cast<const char*>(buf);
114 ssize_t bytes_written = 0;
115 while (bytes_written < static_cast<ssize_t>(count)) {
116 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
117 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
118 bytes_written += rc;
119 }
120 return true;
121}
122
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700123bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
124 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700125 size_t bytes_written = 0;
126 int num_attempts = 0;
127 while (bytes_written < count) {
128 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700129 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
130 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700131 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
132 if (rc < 0) {
133 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
134 << " bytes_written=" << bytes_written
135 << " count=" << count << " offset=" << offset;
136 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700137 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
138 bytes_written += rc;
139 }
140 return true;
141}
142
143bool PReadAll(int fd, void* buf, size_t count, off_t offset,
144 ssize_t* out_bytes_read) {
145 char* c_buf = static_cast<char*>(buf);
146 ssize_t bytes_read = 0;
147 while (bytes_read < static_cast<ssize_t>(count)) {
148 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
149 offset + bytes_read);
150 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
151 if (rc == 0) {
152 break;
153 }
154 bytes_read += rc;
155 }
156 *out_bytes_read = bytes_read;
157 return true;
Darin Petkov296889c2010-07-23 16:20:54 -0700158
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700159}
160
Gilad Arnold19a45f02012-07-19 12:36:10 -0700161// Append |nbytes| of content from |buf| to the vector pointed to by either
162// |vec_p| or |str_p|.
163static void AppendBytes(const char* buf, size_t nbytes,
164 std::vector<char>* vec_p) {
165 CHECK(buf);
166 CHECK(vec_p);
167 vec_p->insert(vec_p->end(), buf, buf + nbytes);
168}
169static void AppendBytes(const char* buf, size_t nbytes,
170 std::string* str_p) {
171 CHECK(buf);
172 CHECK(str_p);
173 str_p->append(buf, nbytes);
174}
175
176// Reads from an open file |fp|, appending the read content to the container
177// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200178// file's content, false otherwise. If |size| is not -1, reads up to |size|
179// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700180template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200181static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700182 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200183 CHECK(size == -1 || size >= 0);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700184 char buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200185 while (size == -1 || size > 0) {
186 off_t bytes_to_read = sizeof(buf);
187 if (size > 0 && bytes_to_read > size) {
188 bytes_to_read = size;
189 }
190 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
191 if (!nbytes) {
192 break;
193 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700194 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200195 if (size != -1) {
196 CHECK(size >= static_cast<off_t>(nbytes));
197 size -= nbytes;
198 }
199 }
200 if (ferror(fp)) {
201 return false;
202 }
203 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700204}
205
Darin Petkov8e447e02013-04-16 16:23:50 +0200206// Opens a file |path| for reading and appends its the contents to a container
207// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
208// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700209template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200210static bool ReadFileChunkAndAppend(const std::string& path,
211 off_t offset,
212 off_t size,
213 T* out_p) {
214 CHECK_GE(offset, 0);
215 CHECK(size == -1 || size >= 0);
216 file_util::ScopedFILE fp(fopen(path.c_str(), "r"));
217 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000218 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200219 if (offset) {
220 // Return success without appending any data if a chunk beyond the end of
221 // the file is requested.
222 if (offset >= FileSize(path)) {
223 return true;
224 }
225 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
226 }
227 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000228}
229
Gilad Arnold19a45f02012-07-19 12:36:10 -0700230// Invokes a pipe |cmd|, then uses |append_func| to append its stdout to a
231// container |out_p|.
232template <class T>
233static bool ReadPipeAndAppend(const std::string& cmd, T* out_p) {
234 FILE* fp = popen(cmd.c_str(), "r");
235 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000236 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200237 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700238 return (success && pclose(fp) >= 0);
239}
240
241
Darin Petkov8e447e02013-04-16 16:23:50 +0200242bool ReadFile(const string& path, vector<char>* out_p) {
243 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700244}
245
Darin Petkov8e447e02013-04-16 16:23:50 +0200246bool ReadFile(const string& path, string* out_p) {
247 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700248}
249
Darin Petkov8e447e02013-04-16 16:23:50 +0200250bool ReadFileChunk(const string& path, off_t offset, off_t size,
251 vector<char>* out_p) {
252 return ReadFileChunkAndAppend(path, offset, size, out_p);
253}
254
255bool ReadPipe(const string& cmd, vector<char>* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700256 return ReadPipeAndAppend(cmd, out_p);
257}
258
Darin Petkov8e447e02013-04-16 16:23:50 +0200259bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700260 return ReadPipeAndAppend(cmd, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000261}
262
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700263off_t FileSize(const string& path) {
264 struct stat stbuf;
265 int rc = stat(path.c_str(), &stbuf);
266 CHECK_EQ(rc, 0);
267 if (rc < 0)
268 return rc;
269 return stbuf.st_size;
270}
271
adlr@google.com3defe6a2009-12-04 20:57:17 +0000272void HexDumpArray(const unsigned char* const arr, const size_t length) {
273 const unsigned char* const char_arr =
274 reinterpret_cast<const unsigned char* const>(arr);
275 LOG(INFO) << "Logging array of length: " << length;
276 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700277 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000278 const unsigned int bytes_remaining = length - i;
279 const unsigned int bytes_per_this_line = min(bytes_per_line,
280 bytes_remaining);
281 char header[100];
282 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
283 TEST_AND_RETURN(r == 13);
284 string line = header;
285 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
286 char buf[20];
287 unsigned char c = char_arr[i + j];
288 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
289 TEST_AND_RETURN(r == 3);
290 line += buf;
291 }
292 LOG(INFO) << line;
293 }
294}
295
296namespace {
297class ScopedDirCloser {
298 public:
299 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
300 ~ScopedDirCloser() {
301 if (dir_ && *dir_) {
302 int r = closedir(*dir_);
303 TEST_AND_RETURN_ERRNO(r == 0);
304 *dir_ = NULL;
305 dir_ = NULL;
306 }
307 }
308 private:
309 DIR** dir_;
310};
311} // namespace {}
312
313bool RecursiveUnlinkDir(const std::string& path) {
314 struct stat stbuf;
315 int r = lstat(path.c_str(), &stbuf);
316 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
317 if ((r < 0) && (errno == ENOENT))
318 // path request is missing. that's fine.
319 return true;
320 if (!S_ISDIR(stbuf.st_mode)) {
321 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700322 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000323 // success or path disappeared before we could unlink.
324 return true;
325 }
326 {
327 // We have a dir, unlink all children, then delete dir
328 DIR *dir = opendir(path.c_str());
329 TEST_AND_RETURN_FALSE_ERRNO(dir);
330 ScopedDirCloser dir_closer(&dir);
331 struct dirent dir_entry;
332 struct dirent *dir_entry_p;
333 int err = 0;
334 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
335 if (dir_entry_p == NULL) {
336 // end of stream reached
337 break;
338 }
339 // Skip . and ..
340 if (!strcmp(dir_entry_p->d_name, ".") ||
341 !strcmp(dir_entry_p->d_name, ".."))
342 continue;
343 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700344 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000345 }
346 TEST_AND_RETURN_FALSE(err == 0);
347 }
348 // unlink dir
349 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
350 return true;
351}
352
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700353string RootDevice(const string& partition_device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700354 FilePath device_path(partition_device);
355 if (device_path.DirName().value() != "/dev") {
356 return "";
357 }
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700358 string::const_iterator it = --partition_device.end();
359 for (; it >= partition_device.begin(); --it) {
360 if (!isdigit(*it))
361 break;
362 }
363 // Some devices contain a p before the partitions. For example:
364 // /dev/mmc0p4 should be shortened to /dev/mmc0.
365 if (*it == 'p')
366 --it;
367 return string(partition_device.begin(), it + 1);
368}
369
370string PartitionNumber(const string& partition_device) {
371 CHECK(!partition_device.empty());
372 string::const_iterator it = --partition_device.end();
373 for (; it >= partition_device.begin(); --it) {
374 if (!isdigit(*it))
375 break;
376 }
377 return string(it + 1, partition_device.end());
378}
379
Darin Petkovf74eb652010-08-04 12:08:38 -0700380string SysfsBlockDevice(const string& device) {
381 FilePath device_path(device);
382 if (device_path.DirName().value() != "/dev") {
383 return "";
384 }
385 return FilePath("/sys/block").Append(device_path.BaseName()).value();
386}
387
388bool IsRemovableDevice(const std::string& device) {
389 string sysfs_block = SysfsBlockDevice(device);
390 string removable;
391 if (sysfs_block.empty() ||
392 !file_util::ReadFileToString(FilePath(sysfs_block).Append("removable"),
393 &removable)) {
394 return false;
395 }
396 TrimWhitespaceASCII(removable, TRIM_ALL, &removable);
397 return removable == "1";
398}
399
adlr@google.com3defe6a2009-12-04 20:57:17 +0000400std::string ErrnoNumberAsString(int err) {
401 char buf[100];
402 buf[0] = '\0';
403 return strerror_r(err, buf, sizeof(buf));
404}
405
406std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
407 string ret;
408 bool last_insert_was_slash = false;
409 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
410 if (*it == '/') {
411 if (last_insert_was_slash)
412 continue;
413 last_insert_was_slash = true;
414 } else {
415 last_insert_was_slash = false;
416 }
417 ret.push_back(*it);
418 }
419 if (strip_trailing_slash && last_insert_was_slash) {
420 string::size_type last_non_slash = ret.find_last_not_of('/');
421 if (last_non_slash != string::npos) {
422 ret.resize(last_non_slash + 1);
423 } else {
424 ret = "";
425 }
426 }
427 return ret;
428}
429
430bool FileExists(const char* path) {
431 struct stat stbuf;
432 return 0 == lstat(path, &stbuf);
433}
434
Darin Petkov30291ed2010-11-12 10:23:06 -0800435bool IsSymlink(const char* path) {
436 struct stat stbuf;
437 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
438}
439
adlr@google.com3defe6a2009-12-04 20:57:17 +0000440std::string TempFilename(string path) {
441 static const string suffix("XXXXXX");
442 CHECK(StringHasSuffix(path, suffix));
443 do {
444 string new_suffix;
445 for (unsigned int i = 0; i < suffix.size(); i++) {
446 int r = rand() % (26 * 2 + 10); // [a-zA-Z0-9]
447 if (r < 26)
448 new_suffix.append(1, 'a' + r);
449 else if (r < (26 * 2))
450 new_suffix.append(1, 'A' + r - 26);
451 else
452 new_suffix.append(1, '0' + r - (26 * 2));
453 }
454 CHECK_EQ(new_suffix.size(), suffix.size());
455 path.resize(path.size() - new_suffix.size());
456 path.append(new_suffix);
457 } while (FileExists(path.c_str()));
458 return path;
459}
460
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700461bool MakeTempFile(const std::string& filename_template,
462 std::string* filename,
463 int* fd) {
464 DCHECK(filename || fd);
465 vector<char> buf(filename_template.size() + 1);
466 memcpy(&buf[0], filename_template.data(), filename_template.size());
467 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700468
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700469 int mkstemp_fd = mkstemp(&buf[0]);
470 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
471 if (filename) {
472 *filename = &buf[0];
473 }
474 if (fd) {
475 *fd = mkstemp_fd;
476 } else {
477 close(mkstemp_fd);
478 }
479 return true;
480}
481
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700482bool MakeTempDirectory(const std::string& dirname_template,
483 std::string* dirname) {
484 DCHECK(dirname);
485 vector<char> buf(dirname_template.size() + 1);
486 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
487 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700488
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700489 char* return_code = mkdtemp(&buf[0]);
490 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
491 *dirname = &buf[0];
492 return true;
493}
494
adlr@google.com3defe6a2009-12-04 20:57:17 +0000495bool StringHasSuffix(const std::string& str, const std::string& suffix) {
496 if (suffix.size() > str.size())
497 return false;
498 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
499}
500
501bool StringHasPrefix(const std::string& str, const std::string& prefix) {
502 if (prefix.size() > str.size())
503 return false;
504 return 0 == str.compare(0, prefix.size(), prefix);
505}
506
Will Drewry8f71da82010-08-30 14:07:11 -0500507const std::string BootDevice() {
508 char boot_path[PATH_MAX];
509 // Resolve the boot device path fully, including dereferencing
510 // through dm-verity.
511 int ret = rootdev(boot_path, sizeof(boot_path), true, false);
512
513 if (ret < 0) {
514 LOG(ERROR) << "rootdev failed to find the root device";
adlr@google.com3defe6a2009-12-04 20:57:17 +0000515 return "";
516 }
Will Drewry8f71da82010-08-30 14:07:11 -0500517 LOG_IF(WARNING, ret > 0) << "rootdev found a device name with no device node";
518
519 // This local variable is used to construct the return string and is not
520 // passed around after use.
521 return boot_path;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000522}
523
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700524const string BootKernelDevice(const std::string& boot_device) {
525 // Currntly this assumes the last digit of the boot device is
526 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
527 // get the kernel device.
528 string ret = boot_device;
529 if (ret.empty())
530 return ret;
531 char last_char = ret[ret.size() - 1];
532 if (last_char == '3' || last_char == '5' || last_char == '7') {
533 ret[ret.size() - 1] = last_char - 1;
534 return ret;
535 }
536 return "";
537}
538
adlr@google.com3defe6a2009-12-04 20:57:17 +0000539bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700540 const string& mountpoint,
541 unsigned long mountflags) {
542 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000543 if (rc < 0) {
544 string msg = ErrnoNumberAsString(errno);
545 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
546 << device << " on " << mountpoint;
547 return false;
548 }
549 return true;
550}
551
552bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700553 for (int num_retries = 0; ; ++num_retries) {
554 if (umount(mountpoint.c_str()) == 0)
555 break;
556
557 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
558 num_retries < kUnmountMaxNumOfRetries);
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800559 g_usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700560 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000561 return true;
562}
563
Darin Petkovd3f8c892010-10-12 21:38:45 -0700564bool GetFilesystemSize(const std::string& device,
565 int* out_block_count,
566 int* out_block_size) {
567 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
568 TEST_AND_RETURN_FALSE(fd >= 0);
569 ScopedFdCloser fd_closer(&fd);
570 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
571}
572
573bool GetFilesystemSizeFromFD(int fd,
574 int* out_block_count,
575 int* out_block_size) {
576 TEST_AND_RETURN_FALSE(fd >= 0);
577
578 // Determine the ext3 filesystem size by directly reading the block count and
579 // block size information from the superblock. See include/linux/ext3_fs.h for
580 // more details on the structure.
581 ssize_t kBufferSize = 16 * sizeof(uint32_t);
582 char buffer[kBufferSize];
583 const int kSuperblockOffset = 1024;
584 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
585 kBufferSize) {
586 PLOG(ERROR) << "Unable to determine file system size:";
587 return false;
588 }
589 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
590 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
591 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
592 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
593 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
594 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
595 block_count = le32toh(block_count);
596 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
597 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
598 magic = le16toh(magic);
599
600 // Sanity check the parameters.
601 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
602 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
603 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
604 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
605 int block_size = 1 << log_block_size;
606 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
607 block_size <= kExt3MaxBlockSize);
608 TEST_AND_RETURN_FALSE(block_count > 0);
609
610 if (out_block_count) {
611 *out_block_count = block_count;
612 }
613 if (out_block_size) {
614 *out_block_size = block_size;
615 }
616 return true;
617}
618
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700619bool GetBootloader(BootLoader* out_bootloader) {
620 // For now, hardcode to syslinux.
621 *out_bootloader = BootLoader_SYSLINUX;
622 return true;
623}
624
Darin Petkova0b9e772011-10-06 05:05:56 -0700625string GetAndFreeGError(GError** error) {
626 if (!*error) {
627 return "Unknown GLib error.";
628 }
629 string message =
630 base::StringPrintf("GError(%d): %s",
631 (*error)->code,
632 (*error)->message ? (*error)->message : "(unknown)");
633 g_error_free(*error);
634 *error = NULL;
635 return message;
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700636}
637
Darin Petkov296889c2010-07-23 16:20:54 -0700638bool Reboot() {
639 vector<string> command;
640 command.push_back("/sbin/shutdown");
641 command.push_back("-r");
642 command.push_back("now");
643 int rc = 0;
Darin Petkov85d02b72011-05-17 13:25:51 -0700644 Subprocess::SynchronousExec(command, &rc, NULL);
Darin Petkov296889c2010-07-23 16:20:54 -0700645 TEST_AND_RETURN_FALSE(rc == 0);
646 return true;
647}
648
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800649namespace {
650// Do the actual trigger. We do it as a main-loop callback to (try to) get a
651// consistent stack trace.
652gboolean TriggerCrashReporterUpload(void* unused) {
653 pid_t pid = fork();
654 CHECK(pid >= 0) << "fork failed"; // fork() failed. Something is very wrong.
655 if (pid == 0) {
656 // We are the child. Crash.
657 abort(); // never returns
658 }
659 // We are the parent. Wait for child to terminate.
660 pid_t result = waitpid(pid, NULL, 0);
661 LOG_IF(ERROR, result < 0) << "waitpid() failed";
662 return FALSE; // Don't call this callback again
663}
664} // namespace {}
665
666void ScheduleCrashReporterUpload() {
667 g_idle_add(&TriggerCrashReporterUpload, NULL);
668}
669
Chris Sosa4f8ee272012-11-30 13:01:54 -0800670bool SetCpuShares(CpuShares shares) {
671 string string_shares = base::IntToString(static_cast<int>(shares));
672 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
673 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
674 if(utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
675 string_shares.size())){
676 return true;
677 } else {
678 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
679 << " using " << cpu_shares_file;
680 return false;
681 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700682}
683
Chris Sosa4f8ee272012-11-30 13:01:54 -0800684int CompareCpuShares(CpuShares shares_lhs,
685 CpuShares shares_rhs) {
686 return static_cast<int>(shares_lhs) - static_cast<int>(shares_rhs);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700687}
688
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700689int FuzzInt(int value, unsigned int range) {
690 int min = value - range / 2;
691 int max = value + range - range / 2;
692 return base::RandInt(min, max);
693}
694
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800695gboolean GlibRunClosure(gpointer data) {
696 google::protobuf::Closure* callback =
697 reinterpret_cast<google::protobuf::Closure*>(data);
698 callback->Run();
699 return FALSE;
700}
701
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700702string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800703 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700704}
705
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800706string FormatTimeDelta(TimeDelta delta) {
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700707 // Canonicalize into days, hours, minutes, seconds and microseconds.
708 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800709 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700710 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800711 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700712 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800713 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700714 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800715 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700716 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800717
718 // Construct and return string.
719 string str;
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700720 if (days)
721 base::StringAppendF(&str, "%ud", days);
722 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800723 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700724 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800725 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700726 base::StringAppendF(&str, "%u", secs);
727 if (usecs) {
728 int width = 6;
729 while ((usecs / 10) * 10 == usecs) {
730 usecs /= 10;
731 width--;
732 }
733 base::StringAppendF(&str, ".%0*u", width, usecs);
734 }
735 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800736 return str;
737}
738
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700739string ToString(const Time utc_time) {
740 Time::Exploded exp_time;
741 utc_time.UTCExplode(&exp_time);
742 return StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
743 exp_time.month,
744 exp_time.day_of_month,
745 exp_time.year,
746 exp_time.hour,
747 exp_time.minute,
748 exp_time.second);
749}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000750
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700751string ToString(bool b) {
752 return (b ? "true" : "false");
753}
754
Jay Srinivasan19409b72013-04-12 19:23:36 -0700755std::string ToString(DownloadSource source) {
756 switch (source) {
757 case kDownloadSourceHttpsServer: return "HttpsServer";
758 case kDownloadSourceHttpServer: return "HttpServer";
759 case kNumDownloadSources: return "Unknown";
760 // Don't add a default case to let the compiler warn about newly added
761 // download sources which should be added here.
762 }
763
764 return "Unknown";
765}
766
David Zeuthena99981f2013-04-29 13:42:47 -0700767ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700768 // Ignore the higher order bits in the code by applying the mask as
769 // we want the enumerations to be in the small contiguous range
David Zeuthena99981f2013-04-29 13:42:47 -0700770 // with values less than kErrorCodeUmaReportedMax.
771 ErrorCode base_code = static_cast<ErrorCode>(code & ~kErrorCodeSpecialFlags);
Jay Srinivasanf0572052012-10-23 18:12:56 -0700772
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800773 // Make additional adjustments required for UMA and error classification.
774 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
775 // chromium-os:34369.
David Zeuthena99981f2013-04-29 13:42:47 -0700776 if (base_code >= kErrorCodeOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700777 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800778 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800779 LOG(INFO) << "Converting error code " << base_code
David Zeuthena99981f2013-04-29 13:42:47 -0700780 << " to kErrorCodeOmahaErrorInHTTPResponse";
781 base_code = kErrorCodeOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700782 }
783
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800784 return base_code;
785}
786
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800787// Returns a printable version of the various flags denoted in the higher order
788// bits of the given code. Returns an empty string if none of those bits are
789// set.
790string GetFlagNames(uint32_t code) {
David Zeuthena99981f2013-04-29 13:42:47 -0700791 uint32_t flags = code & kErrorCodeSpecialFlags;
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800792 string flag_names;
793 string separator = "";
794 for(size_t i = 0; i < sizeof(flags) * 8; i++) {
795 uint32_t flag = flags & (1 << i);
796 if (flag) {
David Zeuthena99981f2013-04-29 13:42:47 -0700797 flag_names += separator + CodeToString(static_cast<ErrorCode>(flag));
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800798 separator = ", ";
799 }
800 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800801
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800802 return flag_names;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700803}
804
David Zeuthena99981f2013-04-29 13:42:47 -0700805void SendErrorCodeToUma(SystemState* system_state, ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800806 if (!system_state)
807 return;
808
David Zeuthena99981f2013-04-29 13:42:47 -0700809 ErrorCode uma_error_code = GetBaseErrorCode(code);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800810
811 // If the code doesn't have flags computed already, compute them now based on
812 // the state of the current update attempt.
David Zeuthena99981f2013-04-29 13:42:47 -0700813 uint32_t flags = code & kErrorCodeSpecialFlags;
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800814 if (!flags)
815 flags = system_state->update_attempter()->GetErrorCodeFlags();
816
817 // Determine the UMA bucket depending on the flags. But, ignore the resumed
818 // flag, as it's perfectly normal for production devices to resume their
819 // downloads and so we want to record those cases also in NormalErrorCodes
820 // bucket.
David Zeuthena99981f2013-04-29 13:42:47 -0700821 string metric = (flags & ~kErrorCodeResumedFlag) ?
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800822 "Installer.DevModeErrorCodes" : "Installer.NormalErrorCodes";
823
824 LOG(INFO) << "Sending error code " << uma_error_code
825 << " (" << CodeToString(uma_error_code) << ")"
826 << " to UMA metric: " << metric
827 << ". Flags = " << (flags ? GetFlagNames(flags) : "None");
828
829 system_state->metrics_lib()->SendEnumToUMA(metric,
830 uma_error_code,
David Zeuthena99981f2013-04-29 13:42:47 -0700831 kErrorCodeUmaReportedMax);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800832}
833
David Zeuthena99981f2013-04-29 13:42:47 -0700834string CodeToString(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800835 // If the given code has both parts (i.e. the error code part and the flags
836 // part) then strip off the flags part since the switch statement below
837 // has case statements only for the base error code or a single flag but
838 // doesn't support any combinations of those.
David Zeuthena99981f2013-04-29 13:42:47 -0700839 if ((code & kErrorCodeSpecialFlags) && (code & ~kErrorCodeSpecialFlags))
840 code = static_cast<ErrorCode>(code & ~kErrorCodeSpecialFlags);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800841 switch (code) {
David Zeuthena99981f2013-04-29 13:42:47 -0700842 case kErrorCodeSuccess: return "kErrorCodeSuccess";
843 case kErrorCodeError: return "kErrorCodeError";
844 case kErrorCodeOmahaRequestError: return "kErrorCodeOmahaRequestError";
845 case kErrorCodeOmahaResponseHandlerError:
846 return "kErrorCodeOmahaResponseHandlerError";
847 case kErrorCodeFilesystemCopierError:
848 return "kErrorCodeFilesystemCopierError";
849 case kErrorCodePostinstallRunnerError:
850 return "kErrorCodePostinstallRunnerError";
851 case kErrorCodeSetBootableFlagError:
852 return "kErrorCodeSetBootableFlagError";
853 case kErrorCodeInstallDeviceOpenError:
854 return "kErrorCodeInstallDeviceOpenError";
855 case kErrorCodeKernelDeviceOpenError:
856 return "kErrorCodeKernelDeviceOpenError";
857 case kErrorCodeDownloadTransferError:
858 return "kErrorCodeDownloadTransferError";
859 case kErrorCodePayloadHashMismatchError:
860 return "kErrorCodePayloadHashMismatchError";
861 case kErrorCodePayloadSizeMismatchError:
862 return "kErrorCodePayloadSizeMismatchError";
863 case kErrorCodeDownloadPayloadVerificationError:
864 return "kErrorCodeDownloadPayloadVerificationError";
865 case kErrorCodeDownloadNewPartitionInfoError:
866 return "kErrorCodeDownloadNewPartitionInfoError";
867 case kErrorCodeDownloadWriteError:
868 return "kErrorCodeDownloadWriteError";
869 case kErrorCodeNewRootfsVerificationError:
870 return "kErrorCodeNewRootfsVerificationError";
871 case kErrorCodeNewKernelVerificationError:
872 return "kErrorCodeNewKernelVerificationError";
873 case kErrorCodeSignedDeltaPayloadExpectedError:
874 return "kErrorCodeSignedDeltaPayloadExpectedError";
875 case kErrorCodeDownloadPayloadPubKeyVerificationError:
876 return "kErrorCodeDownloadPayloadPubKeyVerificationError";
877 case kErrorCodePostinstallBootedFromFirmwareB:
878 return "kErrorCodePostinstallBootedFromFirmwareB";
879 case kErrorCodeDownloadStateInitializationError:
880 return "kErrorCodeDownloadStateInitializationError";
881 case kErrorCodeDownloadInvalidMetadataMagicString:
882 return "kErrorCodeDownloadInvalidMetadataMagicString";
883 case kErrorCodeDownloadSignatureMissingInManifest:
884 return "kErrorCodeDownloadSignatureMissingInManifest";
885 case kErrorCodeDownloadManifestParseError:
886 return "kErrorCodeDownloadManifestParseError";
887 case kErrorCodeDownloadMetadataSignatureError:
888 return "kErrorCodeDownloadMetadataSignatureError";
889 case kErrorCodeDownloadMetadataSignatureVerificationError:
890 return "kErrorCodeDownloadMetadataSignatureVerificationError";
891 case kErrorCodeDownloadMetadataSignatureMismatch:
892 return "kErrorCodeDownloadMetadataSignatureMismatch";
893 case kErrorCodeDownloadOperationHashVerificationError:
894 return "kErrorCodeDownloadOperationHashVerificationError";
895 case kErrorCodeDownloadOperationExecutionError:
896 return "kErrorCodeDownloadOperationExecutionError";
897 case kErrorCodeDownloadOperationHashMismatch:
898 return "kErrorCodeDownloadOperationHashMismatch";
899 case kErrorCodeOmahaRequestEmptyResponseError:
900 return "kErrorCodeOmahaRequestEmptyResponseError";
901 case kErrorCodeOmahaRequestXMLParseError:
902 return "kErrorCodeOmahaRequestXMLParseError";
903 case kErrorCodeDownloadInvalidMetadataSize:
904 return "kErrorCodeDownloadInvalidMetadataSize";
905 case kErrorCodeDownloadInvalidMetadataSignature:
906 return "kErrorCodeDownloadInvalidMetadataSignature";
907 case kErrorCodeOmahaResponseInvalid:
908 return "kErrorCodeOmahaResponseInvalid";
909 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
910 return "kErrorCodeOmahaUpdateIgnoredPerPolicy";
911 case kErrorCodeOmahaUpdateDeferredPerPolicy:
912 return "kErrorCodeOmahaUpdateDeferredPerPolicy";
913 case kErrorCodeOmahaErrorInHTTPResponse:
914 return "kErrorCodeOmahaErrorInHTTPResponse";
915 case kErrorCodeDownloadOperationHashMissingError:
916 return "kErrorCodeDownloadOperationHashMissingError";
917 case kErrorCodeDownloadMetadataSignatureMissingError:
918 return "kErrorCodeDownloadMetadataSignatureMissingError";
919 case kErrorCodeOmahaUpdateDeferredForBackoff:
920 return "kErrorCodeOmahaUpdateDeferredForBackoff";
921 case kErrorCodePostinstallPowerwashError:
922 return "kErrorCodePostinstallPowerwashError";
923 case kErrorCodeUpdateCanceledByChannelChange:
924 return "kErrorCodeUpdateCanceledByChannelChange";
925 case kErrorCodeUmaReportedMax:
926 return "kErrorCodeUmaReportedMax";
927 case kErrorCodeOmahaRequestHTTPResponseBase:
928 return "kErrorCodeOmahaRequestHTTPResponseBase";
929 case kErrorCodeResumedFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800930 return "Resumed";
David Zeuthena99981f2013-04-29 13:42:47 -0700931 case kErrorCodeDevModeFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800932 return "DevMode";
David Zeuthena99981f2013-04-29 13:42:47 -0700933 case kErrorCodeTestImageFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800934 return "TestImage";
David Zeuthena99981f2013-04-29 13:42:47 -0700935 case kErrorCodeTestOmahaUrlFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800936 return "TestOmahaUrl";
David Zeuthena99981f2013-04-29 13:42:47 -0700937 case kErrorCodeSpecialFlags:
938 return "kErrorCodeSpecialFlags";
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800939 // Don't add a default case to let the compiler warn about newly added
940 // error codes which should be added here.
941 }
942
943 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
944}
Jay Srinivasanf0572052012-10-23 18:12:56 -0700945
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700946bool CreatePowerwashMarkerFile() {
947 bool result = utils::WriteFile(kPowerwashMarkerFile,
948 kPowerwashCommand,
949 strlen(kPowerwashCommand));
950 if (result)
951 LOG(INFO) << "Created " << kPowerwashMarkerFile
952 << " to powerwash on next reboot";
953 else
954 PLOG(ERROR) << "Error in creating powerwash marker file: "
955 << kPowerwashMarkerFile;
956
957 return result;
958}
959
960bool DeletePowerwashMarkerFile() {
961 const FilePath kPowerwashMarkerPath(kPowerwashMarkerFile);
962 bool result = file_util::Delete(kPowerwashMarkerPath, false);
963
964 if (result)
965 LOG(INFO) << "Successfully deleted the powerwash marker file : "
966 << kPowerwashMarkerFile;
967 else
968 PLOG(ERROR) << "Could not delete the powerwash marker file : "
969 << kPowerwashMarkerFile;
970
971 return result;
972}
973
adlr@google.com3defe6a2009-12-04 20:57:17 +0000974} // namespace utils
975
976} // namespace chromeos_update_engine