blob: 2bcc311d424382042720874d7df2f9584e5a9aaa [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>
Chris Sosac1972482013-04-30 22:31:10 -070021#include <vector>
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>
Chris Sosac1972482013-04-30 22:31:10 -070029#include <base/string_split.h>
Will Drewry8f71da82010-08-30 14:07:11 -050030#include <base/string_util.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040031#include <base/stringprintf.h>
Gilad Arnold8e3f1262013-01-08 14:59:54 -080032#include <glib.h>
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -080033#include <google/protobuf/stubs/common.h>
Will Drewry8f71da82010-08-30 14:07:11 -050034#include <rootdev/rootdev.h>
35
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070036#include "update_engine/constants.h"
Andrew de los Reyes970bb282009-12-09 16:34:04 -080037#include "update_engine/file_writer.h"
Darin Petkov33d30642010-08-04 10:18:57 -070038#include "update_engine/omaha_request_params.h"
Darin Petkov296889c2010-07-23 16:20:54 -070039#include "update_engine/subprocess.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080040#include "update_engine/system_state.h"
41#include "update_engine/update_attempter.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000042
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070043using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080044using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000045using std::min;
Chris Sosac1972482013-04-30 22:31:10 -070046using std::pair;
adlr@google.com3defe6a2009-12-04 20:57:17 +000047using std::string;
48using std::vector;
49
50namespace chromeos_update_engine {
51
Ben Chan77a1eba2012-10-07 22:54:55 -070052namespace {
53
54// The following constants control how UnmountFilesystem should retry if
55// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
56// one second.
57const int kUnmountMaxNumOfRetries = 5;
58const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Ben Chan77a1eba2012-10-07 22:54:55 -070059} // namespace
60
adlr@google.com3defe6a2009-12-04 20:57:17 +000061namespace utils {
62
Darin Petkova07586b2010-10-20 13:41:15 -070063static const char kDevImageMarker[] = "/root/.dev_mode";
Darin Petkov2a0e6332010-09-24 14:43:41 -070064
Chris Sosa4f8ee272012-11-30 13:01:54 -080065// Cgroup container is created in update-engine's upstart script located at
66// /etc/init/update-engine.conf.
67static const char kCGroupDir[] = "/sys/fs/cgroup/cpu/update-engine";
68
Darin Petkov33d30642010-08-04 10:18:57 -070069bool IsOfficialBuild() {
Darin Petkova07586b2010-10-20 13:41:15 -070070 return !file_util::PathExists(FilePath(kDevImageMarker));
Darin Petkov33d30642010-08-04 10:18:57 -070071}
72
Darin Petkovc91dd6b2011-01-10 12:31:34 -080073bool IsNormalBootMode() {
Darin Petkov44d98d92011-03-21 16:08:11 -070074 // TODO(petkov): Convert to a library call once a crossystem library is
75 // available (crosbug.com/13291).
76 int exit_code = 0;
77 vector<string> cmd(1, "/usr/bin/crossystem");
78 cmd.push_back("devsw_boot?1");
79
80 // Assume dev mode if the dev switch is set to 1 and there was no error
81 // executing crossystem. Assume normal mode otherwise.
Darin Petkov85d02b72011-05-17 13:25:51 -070082 bool success = Subprocess::SynchronousExec(cmd, &exit_code, NULL);
Darin Petkov44d98d92011-03-21 16:08:11 -070083 bool dev_mode = success && exit_code == 0;
84 LOG_IF(INFO, dev_mode) << "Booted in dev mode.";
85 return !dev_mode;
Darin Petkovc91dd6b2011-01-10 12:31:34 -080086}
87
Chris Sosac1972482013-04-30 22:31:10 -070088string ReadValueFromCrosSystem(const string& key){
Darin Petkovf2065b42011-05-17 16:36:27 -070089 int exit_code = 0;
90 vector<string> cmd(1, "/usr/bin/crossystem");
Chris Sosac1972482013-04-30 22:31:10 -070091 cmd.push_back(key);
Darin Petkovf2065b42011-05-17 16:36:27 -070092
Chris Sosac1972482013-04-30 22:31:10 -070093 string return_value;
94 bool success = Subprocess::SynchronousExec(cmd, &exit_code, &return_value);
Darin Petkovf2065b42011-05-17 16:36:27 -070095 if (success && !exit_code) {
Chris Sosac1972482013-04-30 22:31:10 -070096 TrimWhitespaceASCII(return_value, TRIM_ALL, &return_value);
97 return return_value;
Darin Petkovf2065b42011-05-17 16:36:27 -070098 }
Chris Sosac1972482013-04-30 22:31:10 -070099 LOG(ERROR) << "Unable to read " << key << " (" << exit_code << ") "
100 << return_value;
Darin Petkovf2065b42011-05-17 16:36:27 -0700101 return "";
102}
103
Chris Sosac1972482013-04-30 22:31:10 -0700104string GetHardwareClass() {
105 return ReadValueFromCrosSystem("hwid");
106}
107
108string GetFirmwareVersion() {
109 return ReadValueFromCrosSystem("fwid");
110}
111
112string GetECVersion(const char* input_line) {
113 string line;
114 if(input_line == NULL) {
115 int exit_code = 0;
116 vector<string> cmd(1, "/usr/sbin/mosys");
117 cmd.push_back("-k");
118 cmd.push_back("ec");
119 cmd.push_back("info");
120
121 bool success = Subprocess::SynchronousExec(cmd, &exit_code, &line);
122 if (!success || exit_code) {
123 LOG(ERROR) << "Unable to read ec info from mosys (" << exit_code << ")";
124 return "";
125 }
126 } else {
127 line = input_line;
128 }
129
130 TrimWhitespaceASCII(line, TRIM_ALL, &line);
131
132 // At this point we want to conver the format key=value pair from mosys to
133 // a vector of key value pairs.
134 vector<pair<string, string> > kv_pairs;
135 if (base::SplitStringIntoKeyValuePairs(line, '=', ' ', &kv_pairs)) {
136 for (vector<pair<string, string> >::iterator it = kv_pairs.begin();
137 it != kv_pairs.end(); ++it) {
138 // Finally match against the fw_verion which may have quotes.
139 if (it->first == "fw_version") {
140 string output;
141 // Trim any quotes.
142 TrimString(it->second, "\"", &output);
143 return output;
144 }
145 }
146 }
147 LOG(ERROR) << "Unable to parse fwid from ec info.";
148 return "";
149}
150
151
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800152bool WriteFile(const char* path, const char* data, int data_len) {
153 DirectFileWriter writer;
154 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
155 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700156 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800157 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800158 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800159 return true;
160}
161
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700162bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700163 const char* c_buf = static_cast<const char*>(buf);
164 ssize_t bytes_written = 0;
165 while (bytes_written < static_cast<ssize_t>(count)) {
166 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
167 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
168 bytes_written += rc;
169 }
170 return true;
171}
172
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700173bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
174 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700175 size_t bytes_written = 0;
176 int num_attempts = 0;
177 while (bytes_written < count) {
178 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700179 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
180 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700181 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
182 if (rc < 0) {
183 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
184 << " bytes_written=" << bytes_written
185 << " count=" << count << " offset=" << offset;
186 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700187 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
188 bytes_written += rc;
189 }
190 return true;
191}
192
193bool PReadAll(int fd, void* buf, size_t count, off_t offset,
194 ssize_t* out_bytes_read) {
195 char* c_buf = static_cast<char*>(buf);
196 ssize_t bytes_read = 0;
197 while (bytes_read < static_cast<ssize_t>(count)) {
198 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
199 offset + bytes_read);
200 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
201 if (rc == 0) {
202 break;
203 }
204 bytes_read += rc;
205 }
206 *out_bytes_read = bytes_read;
207 return true;
Darin Petkov296889c2010-07-23 16:20:54 -0700208
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700209}
210
Gilad Arnold19a45f02012-07-19 12:36:10 -0700211// Append |nbytes| of content from |buf| to the vector pointed to by either
212// |vec_p| or |str_p|.
213static void AppendBytes(const char* buf, size_t nbytes,
214 std::vector<char>* vec_p) {
215 CHECK(buf);
216 CHECK(vec_p);
217 vec_p->insert(vec_p->end(), buf, buf + nbytes);
218}
219static void AppendBytes(const char* buf, size_t nbytes,
220 std::string* str_p) {
221 CHECK(buf);
222 CHECK(str_p);
223 str_p->append(buf, nbytes);
224}
225
226// Reads from an open file |fp|, appending the read content to the container
227// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200228// file's content, false otherwise. If |size| is not -1, reads up to |size|
229// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700230template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200231static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700232 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200233 CHECK(size == -1 || size >= 0);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700234 char buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200235 while (size == -1 || size > 0) {
236 off_t bytes_to_read = sizeof(buf);
237 if (size > 0 && bytes_to_read > size) {
238 bytes_to_read = size;
239 }
240 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
241 if (!nbytes) {
242 break;
243 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700244 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200245 if (size != -1) {
246 CHECK(size >= static_cast<off_t>(nbytes));
247 size -= nbytes;
248 }
249 }
250 if (ferror(fp)) {
251 return false;
252 }
253 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700254}
255
Darin Petkov8e447e02013-04-16 16:23:50 +0200256// Opens a file |path| for reading and appends its the contents to a container
257// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
258// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700259template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200260static bool ReadFileChunkAndAppend(const std::string& path,
261 off_t offset,
262 off_t size,
263 T* out_p) {
264 CHECK_GE(offset, 0);
265 CHECK(size == -1 || size >= 0);
266 file_util::ScopedFILE fp(fopen(path.c_str(), "r"));
267 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000268 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200269 if (offset) {
270 // Return success without appending any data if a chunk beyond the end of
271 // the file is requested.
272 if (offset >= FileSize(path)) {
273 return true;
274 }
275 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
276 }
277 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000278}
279
Gilad Arnold19a45f02012-07-19 12:36:10 -0700280// Invokes a pipe |cmd|, then uses |append_func| to append its stdout to a
281// container |out_p|.
282template <class T>
283static bool ReadPipeAndAppend(const std::string& cmd, T* out_p) {
284 FILE* fp = popen(cmd.c_str(), "r");
285 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000286 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200287 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700288 return (success && pclose(fp) >= 0);
289}
290
291
Darin Petkov8e447e02013-04-16 16:23:50 +0200292bool ReadFile(const string& path, vector<char>* out_p) {
293 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700294}
295
Darin Petkov8e447e02013-04-16 16:23:50 +0200296bool ReadFile(const string& path, string* out_p) {
297 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700298}
299
Darin Petkov8e447e02013-04-16 16:23:50 +0200300bool ReadFileChunk(const string& path, off_t offset, off_t size,
301 vector<char>* out_p) {
302 return ReadFileChunkAndAppend(path, offset, size, out_p);
303}
304
305bool ReadPipe(const string& cmd, vector<char>* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700306 return ReadPipeAndAppend(cmd, out_p);
307}
308
Darin Petkov8e447e02013-04-16 16:23:50 +0200309bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700310 return ReadPipeAndAppend(cmd, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000311}
312
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700313off_t FileSize(const string& path) {
314 struct stat stbuf;
315 int rc = stat(path.c_str(), &stbuf);
316 CHECK_EQ(rc, 0);
317 if (rc < 0)
318 return rc;
319 return stbuf.st_size;
320}
321
adlr@google.com3defe6a2009-12-04 20:57:17 +0000322void HexDumpArray(const unsigned char* const arr, const size_t length) {
323 const unsigned char* const char_arr =
324 reinterpret_cast<const unsigned char* const>(arr);
325 LOG(INFO) << "Logging array of length: " << length;
326 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700327 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000328 const unsigned int bytes_remaining = length - i;
329 const unsigned int bytes_per_this_line = min(bytes_per_line,
330 bytes_remaining);
331 char header[100];
332 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
333 TEST_AND_RETURN(r == 13);
334 string line = header;
335 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
336 char buf[20];
337 unsigned char c = char_arr[i + j];
338 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
339 TEST_AND_RETURN(r == 3);
340 line += buf;
341 }
342 LOG(INFO) << line;
343 }
344}
345
346namespace {
347class ScopedDirCloser {
348 public:
349 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
350 ~ScopedDirCloser() {
351 if (dir_ && *dir_) {
352 int r = closedir(*dir_);
353 TEST_AND_RETURN_ERRNO(r == 0);
354 *dir_ = NULL;
355 dir_ = NULL;
356 }
357 }
358 private:
359 DIR** dir_;
360};
361} // namespace {}
362
363bool RecursiveUnlinkDir(const std::string& path) {
364 struct stat stbuf;
365 int r = lstat(path.c_str(), &stbuf);
366 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
367 if ((r < 0) && (errno == ENOENT))
368 // path request is missing. that's fine.
369 return true;
370 if (!S_ISDIR(stbuf.st_mode)) {
371 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700372 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000373 // success or path disappeared before we could unlink.
374 return true;
375 }
376 {
377 // We have a dir, unlink all children, then delete dir
378 DIR *dir = opendir(path.c_str());
379 TEST_AND_RETURN_FALSE_ERRNO(dir);
380 ScopedDirCloser dir_closer(&dir);
381 struct dirent dir_entry;
382 struct dirent *dir_entry_p;
383 int err = 0;
384 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
385 if (dir_entry_p == NULL) {
386 // end of stream reached
387 break;
388 }
389 // Skip . and ..
390 if (!strcmp(dir_entry_p->d_name, ".") ||
391 !strcmp(dir_entry_p->d_name, ".."))
392 continue;
393 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700394 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000395 }
396 TEST_AND_RETURN_FALSE(err == 0);
397 }
398 // unlink dir
399 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
400 return true;
401}
402
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700403string RootDevice(const string& partition_device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700404 FilePath device_path(partition_device);
405 if (device_path.DirName().value() != "/dev") {
406 return "";
407 }
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700408 string::const_iterator it = --partition_device.end();
409 for (; it >= partition_device.begin(); --it) {
410 if (!isdigit(*it))
411 break;
412 }
413 // Some devices contain a p before the partitions. For example:
414 // /dev/mmc0p4 should be shortened to /dev/mmc0.
415 if (*it == 'p')
416 --it;
417 return string(partition_device.begin(), it + 1);
418}
419
420string PartitionNumber(const string& partition_device) {
421 CHECK(!partition_device.empty());
422 string::const_iterator it = --partition_device.end();
423 for (; it >= partition_device.begin(); --it) {
424 if (!isdigit(*it))
425 break;
426 }
427 return string(it + 1, partition_device.end());
428}
429
Darin Petkovf74eb652010-08-04 12:08:38 -0700430string SysfsBlockDevice(const string& device) {
431 FilePath device_path(device);
432 if (device_path.DirName().value() != "/dev") {
433 return "";
434 }
435 return FilePath("/sys/block").Append(device_path.BaseName()).value();
436}
437
438bool IsRemovableDevice(const std::string& device) {
439 string sysfs_block = SysfsBlockDevice(device);
440 string removable;
441 if (sysfs_block.empty() ||
442 !file_util::ReadFileToString(FilePath(sysfs_block).Append("removable"),
443 &removable)) {
444 return false;
445 }
446 TrimWhitespaceASCII(removable, TRIM_ALL, &removable);
447 return removable == "1";
448}
449
adlr@google.com3defe6a2009-12-04 20:57:17 +0000450std::string ErrnoNumberAsString(int err) {
451 char buf[100];
452 buf[0] = '\0';
453 return strerror_r(err, buf, sizeof(buf));
454}
455
456std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
457 string ret;
458 bool last_insert_was_slash = false;
459 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
460 if (*it == '/') {
461 if (last_insert_was_slash)
462 continue;
463 last_insert_was_slash = true;
464 } else {
465 last_insert_was_slash = false;
466 }
467 ret.push_back(*it);
468 }
469 if (strip_trailing_slash && last_insert_was_slash) {
470 string::size_type last_non_slash = ret.find_last_not_of('/');
471 if (last_non_slash != string::npos) {
472 ret.resize(last_non_slash + 1);
473 } else {
474 ret = "";
475 }
476 }
477 return ret;
478}
479
480bool FileExists(const char* path) {
481 struct stat stbuf;
482 return 0 == lstat(path, &stbuf);
483}
484
Darin Petkov30291ed2010-11-12 10:23:06 -0800485bool IsSymlink(const char* path) {
486 struct stat stbuf;
487 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
488}
489
adlr@google.com3defe6a2009-12-04 20:57:17 +0000490std::string TempFilename(string path) {
491 static const string suffix("XXXXXX");
492 CHECK(StringHasSuffix(path, suffix));
493 do {
494 string new_suffix;
495 for (unsigned int i = 0; i < suffix.size(); i++) {
496 int r = rand() % (26 * 2 + 10); // [a-zA-Z0-9]
497 if (r < 26)
498 new_suffix.append(1, 'a' + r);
499 else if (r < (26 * 2))
500 new_suffix.append(1, 'A' + r - 26);
501 else
502 new_suffix.append(1, '0' + r - (26 * 2));
503 }
504 CHECK_EQ(new_suffix.size(), suffix.size());
505 path.resize(path.size() - new_suffix.size());
506 path.append(new_suffix);
507 } while (FileExists(path.c_str()));
508 return path;
509}
510
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700511bool MakeTempFile(const std::string& filename_template,
512 std::string* filename,
513 int* fd) {
514 DCHECK(filename || fd);
515 vector<char> buf(filename_template.size() + 1);
516 memcpy(&buf[0], filename_template.data(), filename_template.size());
517 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700518
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700519 int mkstemp_fd = mkstemp(&buf[0]);
520 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
521 if (filename) {
522 *filename = &buf[0];
523 }
524 if (fd) {
525 *fd = mkstemp_fd;
526 } else {
527 close(mkstemp_fd);
528 }
529 return true;
530}
531
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700532bool MakeTempDirectory(const std::string& dirname_template,
533 std::string* dirname) {
534 DCHECK(dirname);
535 vector<char> buf(dirname_template.size() + 1);
536 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
537 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700538
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700539 char* return_code = mkdtemp(&buf[0]);
540 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
541 *dirname = &buf[0];
542 return true;
543}
544
adlr@google.com3defe6a2009-12-04 20:57:17 +0000545bool StringHasSuffix(const std::string& str, const std::string& suffix) {
546 if (suffix.size() > str.size())
547 return false;
548 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
549}
550
551bool StringHasPrefix(const std::string& str, const std::string& prefix) {
552 if (prefix.size() > str.size())
553 return false;
554 return 0 == str.compare(0, prefix.size(), prefix);
555}
556
Will Drewry8f71da82010-08-30 14:07:11 -0500557const std::string BootDevice() {
558 char boot_path[PATH_MAX];
559 // Resolve the boot device path fully, including dereferencing
560 // through dm-verity.
561 int ret = rootdev(boot_path, sizeof(boot_path), true, false);
562
563 if (ret < 0) {
564 LOG(ERROR) << "rootdev failed to find the root device";
adlr@google.com3defe6a2009-12-04 20:57:17 +0000565 return "";
566 }
Will Drewry8f71da82010-08-30 14:07:11 -0500567 LOG_IF(WARNING, ret > 0) << "rootdev found a device name with no device node";
568
569 // This local variable is used to construct the return string and is not
570 // passed around after use.
571 return boot_path;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000572}
573
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700574const string BootKernelDevice(const std::string& boot_device) {
575 // Currntly this assumes the last digit of the boot device is
576 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
577 // get the kernel device.
578 string ret = boot_device;
579 if (ret.empty())
580 return ret;
581 char last_char = ret[ret.size() - 1];
582 if (last_char == '3' || last_char == '5' || last_char == '7') {
583 ret[ret.size() - 1] = last_char - 1;
584 return ret;
585 }
586 return "";
587}
588
adlr@google.com3defe6a2009-12-04 20:57:17 +0000589bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700590 const string& mountpoint,
591 unsigned long mountflags) {
592 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000593 if (rc < 0) {
594 string msg = ErrnoNumberAsString(errno);
595 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
596 << device << " on " << mountpoint;
597 return false;
598 }
599 return true;
600}
601
602bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700603 for (int num_retries = 0; ; ++num_retries) {
604 if (umount(mountpoint.c_str()) == 0)
605 break;
606
607 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
608 num_retries < kUnmountMaxNumOfRetries);
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800609 g_usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700610 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000611 return true;
612}
613
Darin Petkovd3f8c892010-10-12 21:38:45 -0700614bool GetFilesystemSize(const std::string& device,
615 int* out_block_count,
616 int* out_block_size) {
617 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
618 TEST_AND_RETURN_FALSE(fd >= 0);
619 ScopedFdCloser fd_closer(&fd);
620 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
621}
622
623bool GetFilesystemSizeFromFD(int fd,
624 int* out_block_count,
625 int* out_block_size) {
626 TEST_AND_RETURN_FALSE(fd >= 0);
627
628 // Determine the ext3 filesystem size by directly reading the block count and
629 // block size information from the superblock. See include/linux/ext3_fs.h for
630 // more details on the structure.
631 ssize_t kBufferSize = 16 * sizeof(uint32_t);
632 char buffer[kBufferSize];
633 const int kSuperblockOffset = 1024;
634 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
635 kBufferSize) {
636 PLOG(ERROR) << "Unable to determine file system size:";
637 return false;
638 }
639 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
640 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
641 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
642 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
643 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
644 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
645 block_count = le32toh(block_count);
646 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
647 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
648 magic = le16toh(magic);
649
650 // Sanity check the parameters.
651 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
652 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
653 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
654 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
655 int block_size = 1 << log_block_size;
656 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
657 block_size <= kExt3MaxBlockSize);
658 TEST_AND_RETURN_FALSE(block_count > 0);
659
660 if (out_block_count) {
661 *out_block_count = block_count;
662 }
663 if (out_block_size) {
664 *out_block_size = block_size;
665 }
666 return true;
667}
668
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700669bool GetBootloader(BootLoader* out_bootloader) {
670 // For now, hardcode to syslinux.
671 *out_bootloader = BootLoader_SYSLINUX;
672 return true;
673}
674
Darin Petkova0b9e772011-10-06 05:05:56 -0700675string GetAndFreeGError(GError** error) {
676 if (!*error) {
677 return "Unknown GLib error.";
678 }
679 string message =
680 base::StringPrintf("GError(%d): %s",
681 (*error)->code,
682 (*error)->message ? (*error)->message : "(unknown)");
683 g_error_free(*error);
684 *error = NULL;
685 return message;
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700686}
687
Darin Petkov296889c2010-07-23 16:20:54 -0700688bool Reboot() {
689 vector<string> command;
690 command.push_back("/sbin/shutdown");
691 command.push_back("-r");
692 command.push_back("now");
693 int rc = 0;
Darin Petkov85d02b72011-05-17 13:25:51 -0700694 Subprocess::SynchronousExec(command, &rc, NULL);
Darin Petkov296889c2010-07-23 16:20:54 -0700695 TEST_AND_RETURN_FALSE(rc == 0);
696 return true;
697}
698
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800699namespace {
700// Do the actual trigger. We do it as a main-loop callback to (try to) get a
701// consistent stack trace.
702gboolean TriggerCrashReporterUpload(void* unused) {
703 pid_t pid = fork();
704 CHECK(pid >= 0) << "fork failed"; // fork() failed. Something is very wrong.
705 if (pid == 0) {
706 // We are the child. Crash.
707 abort(); // never returns
708 }
709 // We are the parent. Wait for child to terminate.
710 pid_t result = waitpid(pid, NULL, 0);
711 LOG_IF(ERROR, result < 0) << "waitpid() failed";
712 return FALSE; // Don't call this callback again
713}
714} // namespace {}
715
716void ScheduleCrashReporterUpload() {
717 g_idle_add(&TriggerCrashReporterUpload, NULL);
718}
719
Chris Sosa4f8ee272012-11-30 13:01:54 -0800720bool SetCpuShares(CpuShares shares) {
721 string string_shares = base::IntToString(static_cast<int>(shares));
722 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
723 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
724 if(utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
725 string_shares.size())){
726 return true;
727 } else {
728 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
729 << " using " << cpu_shares_file;
730 return false;
731 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700732}
733
Chris Sosa4f8ee272012-11-30 13:01:54 -0800734int CompareCpuShares(CpuShares shares_lhs,
735 CpuShares shares_rhs) {
736 return static_cast<int>(shares_lhs) - static_cast<int>(shares_rhs);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700737}
738
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700739int FuzzInt(int value, unsigned int range) {
740 int min = value - range / 2;
741 int max = value + range - range / 2;
742 return base::RandInt(min, max);
743}
744
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800745gboolean GlibRunClosure(gpointer data) {
746 google::protobuf::Closure* callback =
747 reinterpret_cast<google::protobuf::Closure*>(data);
748 callback->Run();
749 return FALSE;
750}
751
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700752string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800753 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700754}
755
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800756string FormatTimeDelta(TimeDelta delta) {
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700757 // Canonicalize into days, hours, minutes, seconds and microseconds.
758 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800759 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700760 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800761 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700762 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800763 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700764 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800765 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700766 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800767
768 // Construct and return string.
769 string str;
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700770 if (days)
771 base::StringAppendF(&str, "%ud", days);
772 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800773 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700774 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800775 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700776 base::StringAppendF(&str, "%u", secs);
777 if (usecs) {
778 int width = 6;
779 while ((usecs / 10) * 10 == usecs) {
780 usecs /= 10;
781 width--;
782 }
783 base::StringAppendF(&str, ".%0*u", width, usecs);
784 }
785 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800786 return str;
787}
788
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700789string ToString(const Time utc_time) {
790 Time::Exploded exp_time;
791 utc_time.UTCExplode(&exp_time);
792 return StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
793 exp_time.month,
794 exp_time.day_of_month,
795 exp_time.year,
796 exp_time.hour,
797 exp_time.minute,
798 exp_time.second);
799}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000800
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700801string ToString(bool b) {
802 return (b ? "true" : "false");
803}
804
Alex Deymo1c656c42013-06-28 11:02:14 -0700805string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700806 switch (source) {
807 case kDownloadSourceHttpsServer: return "HttpsServer";
808 case kDownloadSourceHttpServer: return "HttpServer";
809 case kNumDownloadSources: return "Unknown";
810 // Don't add a default case to let the compiler warn about newly added
811 // download sources which should be added here.
812 }
813
814 return "Unknown";
815}
816
Alex Deymo1c656c42013-06-28 11:02:14 -0700817string ToString(PayloadType payload_type) {
818 switch (payload_type) {
819 case kPayloadTypeDelta: return "Delta";
820 case kPayloadTypeFull: return "Full";
821 case kPayloadTypeForcedFull: return "ForcedFull";
822 case kNumPayloadTypes: return "Unknown";
823 // Don't add a default case to let the compiler warn about newly added
824 // payload types which should be added here.
825 }
826
827 return "Unknown";
828}
829
David Zeuthena99981f2013-04-29 13:42:47 -0700830ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700831 // Ignore the higher order bits in the code by applying the mask as
832 // we want the enumerations to be in the small contiguous range
David Zeuthena99981f2013-04-29 13:42:47 -0700833 // with values less than kErrorCodeUmaReportedMax.
834 ErrorCode base_code = static_cast<ErrorCode>(code & ~kErrorCodeSpecialFlags);
Jay Srinivasanf0572052012-10-23 18:12:56 -0700835
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800836 // Make additional adjustments required for UMA and error classification.
837 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
838 // chromium-os:34369.
David Zeuthena99981f2013-04-29 13:42:47 -0700839 if (base_code >= kErrorCodeOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700840 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800841 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800842 LOG(INFO) << "Converting error code " << base_code
David Zeuthena99981f2013-04-29 13:42:47 -0700843 << " to kErrorCodeOmahaErrorInHTTPResponse";
844 base_code = kErrorCodeOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700845 }
846
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800847 return base_code;
848}
849
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800850// Returns a printable version of the various flags denoted in the higher order
851// bits of the given code. Returns an empty string if none of those bits are
852// set.
853string GetFlagNames(uint32_t code) {
David Zeuthena99981f2013-04-29 13:42:47 -0700854 uint32_t flags = code & kErrorCodeSpecialFlags;
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800855 string flag_names;
856 string separator = "";
857 for(size_t i = 0; i < sizeof(flags) * 8; i++) {
858 uint32_t flag = flags & (1 << i);
859 if (flag) {
David Zeuthena99981f2013-04-29 13:42:47 -0700860 flag_names += separator + CodeToString(static_cast<ErrorCode>(flag));
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800861 separator = ", ";
862 }
863 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800864
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800865 return flag_names;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700866}
867
David Zeuthena99981f2013-04-29 13:42:47 -0700868void SendErrorCodeToUma(SystemState* system_state, ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800869 if (!system_state)
870 return;
871
David Zeuthena99981f2013-04-29 13:42:47 -0700872 ErrorCode uma_error_code = GetBaseErrorCode(code);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800873
874 // If the code doesn't have flags computed already, compute them now based on
875 // the state of the current update attempt.
David Zeuthena99981f2013-04-29 13:42:47 -0700876 uint32_t flags = code & kErrorCodeSpecialFlags;
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800877 if (!flags)
878 flags = system_state->update_attempter()->GetErrorCodeFlags();
879
880 // Determine the UMA bucket depending on the flags. But, ignore the resumed
881 // flag, as it's perfectly normal for production devices to resume their
882 // downloads and so we want to record those cases also in NormalErrorCodes
883 // bucket.
David Zeuthena99981f2013-04-29 13:42:47 -0700884 string metric = (flags & ~kErrorCodeResumedFlag) ?
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800885 "Installer.DevModeErrorCodes" : "Installer.NormalErrorCodes";
886
887 LOG(INFO) << "Sending error code " << uma_error_code
888 << " (" << CodeToString(uma_error_code) << ")"
889 << " to UMA metric: " << metric
890 << ". Flags = " << (flags ? GetFlagNames(flags) : "None");
891
892 system_state->metrics_lib()->SendEnumToUMA(metric,
893 uma_error_code,
David Zeuthena99981f2013-04-29 13:42:47 -0700894 kErrorCodeUmaReportedMax);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800895}
896
David Zeuthena99981f2013-04-29 13:42:47 -0700897string CodeToString(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800898 // If the given code has both parts (i.e. the error code part and the flags
899 // part) then strip off the flags part since the switch statement below
900 // has case statements only for the base error code or a single flag but
901 // doesn't support any combinations of those.
David Zeuthena99981f2013-04-29 13:42:47 -0700902 if ((code & kErrorCodeSpecialFlags) && (code & ~kErrorCodeSpecialFlags))
903 code = static_cast<ErrorCode>(code & ~kErrorCodeSpecialFlags);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800904 switch (code) {
David Zeuthena99981f2013-04-29 13:42:47 -0700905 case kErrorCodeSuccess: return "kErrorCodeSuccess";
906 case kErrorCodeError: return "kErrorCodeError";
907 case kErrorCodeOmahaRequestError: return "kErrorCodeOmahaRequestError";
908 case kErrorCodeOmahaResponseHandlerError:
909 return "kErrorCodeOmahaResponseHandlerError";
910 case kErrorCodeFilesystemCopierError:
911 return "kErrorCodeFilesystemCopierError";
912 case kErrorCodePostinstallRunnerError:
913 return "kErrorCodePostinstallRunnerError";
Gilad Arnold21504f02013-05-24 08:51:22 -0700914 case kErrorCodePayloadMismatchedType:
915 return "kErrorCodePayloadMismatchedType";
David Zeuthena99981f2013-04-29 13:42:47 -0700916 case kErrorCodeInstallDeviceOpenError:
917 return "kErrorCodeInstallDeviceOpenError";
918 case kErrorCodeKernelDeviceOpenError:
919 return "kErrorCodeKernelDeviceOpenError";
920 case kErrorCodeDownloadTransferError:
921 return "kErrorCodeDownloadTransferError";
922 case kErrorCodePayloadHashMismatchError:
923 return "kErrorCodePayloadHashMismatchError";
924 case kErrorCodePayloadSizeMismatchError:
925 return "kErrorCodePayloadSizeMismatchError";
926 case kErrorCodeDownloadPayloadVerificationError:
927 return "kErrorCodeDownloadPayloadVerificationError";
928 case kErrorCodeDownloadNewPartitionInfoError:
929 return "kErrorCodeDownloadNewPartitionInfoError";
930 case kErrorCodeDownloadWriteError:
931 return "kErrorCodeDownloadWriteError";
932 case kErrorCodeNewRootfsVerificationError:
933 return "kErrorCodeNewRootfsVerificationError";
934 case kErrorCodeNewKernelVerificationError:
935 return "kErrorCodeNewKernelVerificationError";
936 case kErrorCodeSignedDeltaPayloadExpectedError:
937 return "kErrorCodeSignedDeltaPayloadExpectedError";
938 case kErrorCodeDownloadPayloadPubKeyVerificationError:
939 return "kErrorCodeDownloadPayloadPubKeyVerificationError";
940 case kErrorCodePostinstallBootedFromFirmwareB:
941 return "kErrorCodePostinstallBootedFromFirmwareB";
942 case kErrorCodeDownloadStateInitializationError:
943 return "kErrorCodeDownloadStateInitializationError";
944 case kErrorCodeDownloadInvalidMetadataMagicString:
945 return "kErrorCodeDownloadInvalidMetadataMagicString";
946 case kErrorCodeDownloadSignatureMissingInManifest:
947 return "kErrorCodeDownloadSignatureMissingInManifest";
948 case kErrorCodeDownloadManifestParseError:
949 return "kErrorCodeDownloadManifestParseError";
950 case kErrorCodeDownloadMetadataSignatureError:
951 return "kErrorCodeDownloadMetadataSignatureError";
952 case kErrorCodeDownloadMetadataSignatureVerificationError:
953 return "kErrorCodeDownloadMetadataSignatureVerificationError";
954 case kErrorCodeDownloadMetadataSignatureMismatch:
955 return "kErrorCodeDownloadMetadataSignatureMismatch";
956 case kErrorCodeDownloadOperationHashVerificationError:
957 return "kErrorCodeDownloadOperationHashVerificationError";
958 case kErrorCodeDownloadOperationExecutionError:
959 return "kErrorCodeDownloadOperationExecutionError";
960 case kErrorCodeDownloadOperationHashMismatch:
961 return "kErrorCodeDownloadOperationHashMismatch";
962 case kErrorCodeOmahaRequestEmptyResponseError:
963 return "kErrorCodeOmahaRequestEmptyResponseError";
964 case kErrorCodeOmahaRequestXMLParseError:
965 return "kErrorCodeOmahaRequestXMLParseError";
966 case kErrorCodeDownloadInvalidMetadataSize:
967 return "kErrorCodeDownloadInvalidMetadataSize";
968 case kErrorCodeDownloadInvalidMetadataSignature:
969 return "kErrorCodeDownloadInvalidMetadataSignature";
970 case kErrorCodeOmahaResponseInvalid:
971 return "kErrorCodeOmahaResponseInvalid";
972 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
973 return "kErrorCodeOmahaUpdateIgnoredPerPolicy";
974 case kErrorCodeOmahaUpdateDeferredPerPolicy:
975 return "kErrorCodeOmahaUpdateDeferredPerPolicy";
976 case kErrorCodeOmahaErrorInHTTPResponse:
977 return "kErrorCodeOmahaErrorInHTTPResponse";
978 case kErrorCodeDownloadOperationHashMissingError:
979 return "kErrorCodeDownloadOperationHashMissingError";
980 case kErrorCodeDownloadMetadataSignatureMissingError:
981 return "kErrorCodeDownloadMetadataSignatureMissingError";
982 case kErrorCodeOmahaUpdateDeferredForBackoff:
983 return "kErrorCodeOmahaUpdateDeferredForBackoff";
984 case kErrorCodePostinstallPowerwashError:
985 return "kErrorCodePostinstallPowerwashError";
986 case kErrorCodeUpdateCanceledByChannelChange:
987 return "kErrorCodeUpdateCanceledByChannelChange";
988 case kErrorCodeUmaReportedMax:
989 return "kErrorCodeUmaReportedMax";
990 case kErrorCodeOmahaRequestHTTPResponseBase:
991 return "kErrorCodeOmahaRequestHTTPResponseBase";
992 case kErrorCodeResumedFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800993 return "Resumed";
David Zeuthena99981f2013-04-29 13:42:47 -0700994 case kErrorCodeDevModeFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800995 return "DevMode";
David Zeuthena99981f2013-04-29 13:42:47 -0700996 case kErrorCodeTestImageFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800997 return "TestImage";
David Zeuthena99981f2013-04-29 13:42:47 -0700998 case kErrorCodeTestOmahaUrlFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800999 return "TestOmahaUrl";
David Zeuthena99981f2013-04-29 13:42:47 -07001000 case kErrorCodeSpecialFlags:
1001 return "kErrorCodeSpecialFlags";
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001002 // Don't add a default case to let the compiler warn about newly added
1003 // error codes which should be added here.
1004 }
1005
1006 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
1007}
Jay Srinivasanf0572052012-10-23 18:12:56 -07001008
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001009bool CreatePowerwashMarkerFile() {
1010 bool result = utils::WriteFile(kPowerwashMarkerFile,
1011 kPowerwashCommand,
1012 strlen(kPowerwashCommand));
1013 if (result)
1014 LOG(INFO) << "Created " << kPowerwashMarkerFile
1015 << " to powerwash on next reboot";
1016 else
1017 PLOG(ERROR) << "Error in creating powerwash marker file: "
1018 << kPowerwashMarkerFile;
1019
1020 return result;
1021}
1022
1023bool DeletePowerwashMarkerFile() {
1024 const FilePath kPowerwashMarkerPath(kPowerwashMarkerFile);
1025 bool result = file_util::Delete(kPowerwashMarkerPath, false);
1026
1027 if (result)
1028 LOG(INFO) << "Successfully deleted the powerwash marker file : "
1029 << kPowerwashMarkerFile;
1030 else
1031 PLOG(ERROR) << "Could not delete the powerwash marker file : "
1032 << kPowerwashMarkerFile;
1033
1034 return result;
1035}
1036
Chris Sosad317e402013-06-12 13:47:09 -07001037bool GetInstallDev(const std::string& boot_dev, std::string* install_dev) {
1038 TEST_AND_RETURN_FALSE(StringHasPrefix(boot_dev, "/dev/"));
1039 string ret(boot_dev);
1040 string::reverse_iterator it = ret.rbegin(); // last character in string
1041 // Right now, we just switch '3' and '5' partition numbers.
1042 TEST_AND_RETURN_FALSE((*it == '3') || (*it == '5'));
1043 *it = (*it == '3') ? '5' : '3';
1044 *install_dev = ret;
1045 return true;
1046}
1047
adlr@google.com3defe6a2009-12-04 20:57:17 +00001048} // namespace utils
1049
1050} // namespace chromeos_update_engine