blob: 7a304eeda204938048c8467a44d20164d6eb00ea [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
David Zeuthen910ec5b2013-09-26 12:10:58 -07007#include <attr/xattr.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +00008#include <sys/mount.h>
Darin Petkovc6c135c2010-08-11 13:36:18 -07009#include <sys/resource.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000010#include <sys/stat.h>
11#include <sys/types.h>
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -080012#include <sys/wait.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000013#include <dirent.h>
14#include <errno.h>
Andrew de los Reyes970bb282009-12-09 16:34:04 -080015#include <fcntl.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000016#include <stdio.h>
17#include <stdlib.h>
18#include <string.h>
19#include <unistd.h>
Darin Petkovf74eb652010-08-04 12:08:38 -070020
adlr@google.com3defe6a2009-12-04 20:57:17 +000021#include <algorithm>
Chris Sosac1972482013-04-30 22:31:10 -070022#include <vector>
Darin Petkovf74eb652010-08-04 12:08:38 -070023
Will Drewry8f71da82010-08-30 14:07:11 -050024#include <base/file_path.h>
25#include <base/file_util.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040026#include <base/logging.h>
Chris Sosafc661a12013-02-26 14:43:21 -080027#include <base/posix/eintr_wrapper.h>
Will Drewry8f71da82010-08-30 14:07:11 -050028#include <base/rand_util.h>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070029#include <base/string_number_conversions.h>
Chris Sosac1972482013-04-30 22:31:10 -070030#include <base/string_split.h>
Will Drewry8f71da82010-08-30 14:07:11 -050031#include <base/string_util.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040032#include <base/stringprintf.h>
Gilad Arnold8e3f1262013-01-08 14:59:54 -080033#include <glib.h>
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -080034#include <google/protobuf/stubs/common.h>
Will Drewry8f71da82010-08-30 14:07:11 -050035
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
J. Richard Barnette63137e52013-10-28 10:57:29 -0700112string GetECVersion() {
113 int exit_code = 0;
114 vector<string> cmd(1, "/usr/sbin/mosys");
115 cmd.push_back("-k");
116 cmd.push_back("ec");
117 cmd.push_back("info");
Chris Sosac1972482013-04-30 22:31:10 -0700118
J. Richard Barnette63137e52013-10-28 10:57:29 -0700119 string input_line;
120 bool success = Subprocess::SynchronousExec(cmd, &exit_code, &input_line);
121 if (!success || exit_code) {
122 LOG(ERROR) << "Unable to read ec info from mosys (" << exit_code << ")";
123 return "";
Chris Sosac1972482013-04-30 22:31:10 -0700124 }
125
J. Richard Barnette63137e52013-10-28 10:57:29 -0700126 return ParseECVersion(input_line);
127}
128
129string ParseECVersion(string input_line) {
130 TrimWhitespaceASCII(input_line, TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -0700131
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;
J. Richard Barnette63137e52013-10-28 10:57:29 -0700135 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Chris Sosac1972482013-04-30 22:31:10 -0700136 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
adlr@google.com3defe6a2009-12-04 20:57:17 +0000557bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700558 const string& mountpoint,
559 unsigned long mountflags) {
560 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000561 if (rc < 0) {
562 string msg = ErrnoNumberAsString(errno);
563 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
564 << device << " on " << mountpoint;
565 return false;
566 }
567 return true;
568}
569
570bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700571 for (int num_retries = 0; ; ++num_retries) {
572 if (umount(mountpoint.c_str()) == 0)
573 break;
574
575 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
576 num_retries < kUnmountMaxNumOfRetries);
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800577 g_usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700578 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000579 return true;
580}
581
Darin Petkovd3f8c892010-10-12 21:38:45 -0700582bool GetFilesystemSize(const std::string& device,
583 int* out_block_count,
584 int* out_block_size) {
585 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
586 TEST_AND_RETURN_FALSE(fd >= 0);
587 ScopedFdCloser fd_closer(&fd);
588 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
589}
590
591bool GetFilesystemSizeFromFD(int fd,
592 int* out_block_count,
593 int* out_block_size) {
594 TEST_AND_RETURN_FALSE(fd >= 0);
595
596 // Determine the ext3 filesystem size by directly reading the block count and
597 // block size information from the superblock. See include/linux/ext3_fs.h for
598 // more details on the structure.
599 ssize_t kBufferSize = 16 * sizeof(uint32_t);
600 char buffer[kBufferSize];
601 const int kSuperblockOffset = 1024;
602 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
603 kBufferSize) {
604 PLOG(ERROR) << "Unable to determine file system size:";
605 return false;
606 }
607 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
608 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
609 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
610 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
611 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
612 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
613 block_count = le32toh(block_count);
614 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
615 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
616 magic = le16toh(magic);
617
618 // Sanity check the parameters.
619 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
620 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
621 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
622 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
623 int block_size = 1 << log_block_size;
624 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
625 block_size <= kExt3MaxBlockSize);
626 TEST_AND_RETURN_FALSE(block_count > 0);
627
628 if (out_block_count) {
629 *out_block_count = block_count;
630 }
631 if (out_block_size) {
632 *out_block_size = block_size;
633 }
634 return true;
635}
636
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700637bool GetBootloader(BootLoader* out_bootloader) {
638 // For now, hardcode to syslinux.
639 *out_bootloader = BootLoader_SYSLINUX;
640 return true;
641}
642
Darin Petkova0b9e772011-10-06 05:05:56 -0700643string GetAndFreeGError(GError** error) {
644 if (!*error) {
645 return "Unknown GLib error.";
646 }
647 string message =
648 base::StringPrintf("GError(%d): %s",
649 (*error)->code,
650 (*error)->message ? (*error)->message : "(unknown)");
651 g_error_free(*error);
652 *error = NULL;
653 return message;
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700654}
655
Darin Petkov296889c2010-07-23 16:20:54 -0700656bool Reboot() {
657 vector<string> command;
658 command.push_back("/sbin/shutdown");
659 command.push_back("-r");
660 command.push_back("now");
661 int rc = 0;
Darin Petkov85d02b72011-05-17 13:25:51 -0700662 Subprocess::SynchronousExec(command, &rc, NULL);
Darin Petkov296889c2010-07-23 16:20:54 -0700663 TEST_AND_RETURN_FALSE(rc == 0);
664 return true;
665}
666
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800667namespace {
668// Do the actual trigger. We do it as a main-loop callback to (try to) get a
669// consistent stack trace.
670gboolean TriggerCrashReporterUpload(void* unused) {
671 pid_t pid = fork();
672 CHECK(pid >= 0) << "fork failed"; // fork() failed. Something is very wrong.
673 if (pid == 0) {
674 // We are the child. Crash.
675 abort(); // never returns
676 }
677 // We are the parent. Wait for child to terminate.
678 pid_t result = waitpid(pid, NULL, 0);
679 LOG_IF(ERROR, result < 0) << "waitpid() failed";
680 return FALSE; // Don't call this callback again
681}
682} // namespace {}
683
684void ScheduleCrashReporterUpload() {
685 g_idle_add(&TriggerCrashReporterUpload, NULL);
686}
687
Chris Sosa4f8ee272012-11-30 13:01:54 -0800688bool SetCpuShares(CpuShares shares) {
689 string string_shares = base::IntToString(static_cast<int>(shares));
690 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
691 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
692 if(utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
693 string_shares.size())){
694 return true;
695 } else {
696 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
697 << " using " << cpu_shares_file;
698 return false;
699 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700700}
701
Chris Sosa4f8ee272012-11-30 13:01:54 -0800702int CompareCpuShares(CpuShares shares_lhs,
703 CpuShares shares_rhs) {
704 return static_cast<int>(shares_lhs) - static_cast<int>(shares_rhs);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700705}
706
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700707int FuzzInt(int value, unsigned int range) {
708 int min = value - range / 2;
709 int max = value + range - range / 2;
710 return base::RandInt(min, max);
711}
712
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800713gboolean GlibRunClosure(gpointer data) {
714 google::protobuf::Closure* callback =
715 reinterpret_cast<google::protobuf::Closure*>(data);
716 callback->Run();
717 return FALSE;
718}
719
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700720string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800721 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700722}
723
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800724string FormatTimeDelta(TimeDelta delta) {
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700725 // Canonicalize into days, hours, minutes, seconds and microseconds.
726 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800727 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700728 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800729 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700730 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800731 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700732 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800733 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700734 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800735
736 // Construct and return string.
737 string str;
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700738 if (days)
739 base::StringAppendF(&str, "%ud", days);
740 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800741 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700742 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800743 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700744 base::StringAppendF(&str, "%u", secs);
745 if (usecs) {
746 int width = 6;
747 while ((usecs / 10) * 10 == usecs) {
748 usecs /= 10;
749 width--;
750 }
751 base::StringAppendF(&str, ".%0*u", width, usecs);
752 }
753 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800754 return str;
755}
756
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700757string ToString(const Time utc_time) {
758 Time::Exploded exp_time;
759 utc_time.UTCExplode(&exp_time);
760 return StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
761 exp_time.month,
762 exp_time.day_of_month,
763 exp_time.year,
764 exp_time.hour,
765 exp_time.minute,
766 exp_time.second);
767}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000768
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700769string ToString(bool b) {
770 return (b ? "true" : "false");
771}
772
Alex Deymo1c656c42013-06-28 11:02:14 -0700773string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700774 switch (source) {
775 case kDownloadSourceHttpsServer: return "HttpsServer";
776 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700777 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -0700778 case kNumDownloadSources: return "Unknown";
779 // Don't add a default case to let the compiler warn about newly added
780 // download sources which should be added here.
781 }
782
783 return "Unknown";
784}
785
Alex Deymo1c656c42013-06-28 11:02:14 -0700786string ToString(PayloadType payload_type) {
787 switch (payload_type) {
788 case kPayloadTypeDelta: return "Delta";
789 case kPayloadTypeFull: return "Full";
790 case kPayloadTypeForcedFull: return "ForcedFull";
791 case kNumPayloadTypes: return "Unknown";
792 // Don't add a default case to let the compiler warn about newly added
793 // payload types which should be added here.
794 }
795
796 return "Unknown";
797}
798
David Zeuthena99981f2013-04-29 13:42:47 -0700799ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700800 // Ignore the higher order bits in the code by applying the mask as
801 // we want the enumerations to be in the small contiguous range
David Zeuthena99981f2013-04-29 13:42:47 -0700802 // with values less than kErrorCodeUmaReportedMax.
803 ErrorCode base_code = static_cast<ErrorCode>(code & ~kErrorCodeSpecialFlags);
Jay Srinivasanf0572052012-10-23 18:12:56 -0700804
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800805 // Make additional adjustments required for UMA and error classification.
806 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
807 // chromium-os:34369.
David Zeuthena99981f2013-04-29 13:42:47 -0700808 if (base_code >= kErrorCodeOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700809 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800810 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800811 LOG(INFO) << "Converting error code " << base_code
David Zeuthena99981f2013-04-29 13:42:47 -0700812 << " to kErrorCodeOmahaErrorInHTTPResponse";
813 base_code = kErrorCodeOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700814 }
815
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800816 return base_code;
817}
818
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800819// Returns a printable version of the various flags denoted in the higher order
820// bits of the given code. Returns an empty string if none of those bits are
821// set.
822string GetFlagNames(uint32_t code) {
David Zeuthena99981f2013-04-29 13:42:47 -0700823 uint32_t flags = code & kErrorCodeSpecialFlags;
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800824 string flag_names;
825 string separator = "";
826 for(size_t i = 0; i < sizeof(flags) * 8; i++) {
827 uint32_t flag = flags & (1 << i);
828 if (flag) {
David Zeuthena99981f2013-04-29 13:42:47 -0700829 flag_names += separator + CodeToString(static_cast<ErrorCode>(flag));
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800830 separator = ", ";
831 }
832 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800833
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800834 return flag_names;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700835}
836
David Zeuthena99981f2013-04-29 13:42:47 -0700837void SendErrorCodeToUma(SystemState* system_state, ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800838 if (!system_state)
839 return;
840
David Zeuthena99981f2013-04-29 13:42:47 -0700841 ErrorCode uma_error_code = GetBaseErrorCode(code);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800842
843 // If the code doesn't have flags computed already, compute them now based on
844 // the state of the current update attempt.
David Zeuthena99981f2013-04-29 13:42:47 -0700845 uint32_t flags = code & kErrorCodeSpecialFlags;
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800846 if (!flags)
847 flags = system_state->update_attempter()->GetErrorCodeFlags();
848
849 // Determine the UMA bucket depending on the flags. But, ignore the resumed
850 // flag, as it's perfectly normal for production devices to resume their
851 // downloads and so we want to record those cases also in NormalErrorCodes
852 // bucket.
David Zeuthena99981f2013-04-29 13:42:47 -0700853 string metric = (flags & ~kErrorCodeResumedFlag) ?
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800854 "Installer.DevModeErrorCodes" : "Installer.NormalErrorCodes";
855
856 LOG(INFO) << "Sending error code " << uma_error_code
857 << " (" << CodeToString(uma_error_code) << ")"
858 << " to UMA metric: " << metric
859 << ". Flags = " << (flags ? GetFlagNames(flags) : "None");
860
861 system_state->metrics_lib()->SendEnumToUMA(metric,
862 uma_error_code,
David Zeuthena99981f2013-04-29 13:42:47 -0700863 kErrorCodeUmaReportedMax);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800864}
865
David Zeuthena99981f2013-04-29 13:42:47 -0700866string CodeToString(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800867 // If the given code has both parts (i.e. the error code part and the flags
868 // part) then strip off the flags part since the switch statement below
869 // has case statements only for the base error code or a single flag but
870 // doesn't support any combinations of those.
David Zeuthena99981f2013-04-29 13:42:47 -0700871 if ((code & kErrorCodeSpecialFlags) && (code & ~kErrorCodeSpecialFlags))
872 code = static_cast<ErrorCode>(code & ~kErrorCodeSpecialFlags);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800873 switch (code) {
David Zeuthena99981f2013-04-29 13:42:47 -0700874 case kErrorCodeSuccess: return "kErrorCodeSuccess";
875 case kErrorCodeError: return "kErrorCodeError";
876 case kErrorCodeOmahaRequestError: return "kErrorCodeOmahaRequestError";
877 case kErrorCodeOmahaResponseHandlerError:
878 return "kErrorCodeOmahaResponseHandlerError";
879 case kErrorCodeFilesystemCopierError:
880 return "kErrorCodeFilesystemCopierError";
881 case kErrorCodePostinstallRunnerError:
882 return "kErrorCodePostinstallRunnerError";
Gilad Arnold21504f02013-05-24 08:51:22 -0700883 case kErrorCodePayloadMismatchedType:
884 return "kErrorCodePayloadMismatchedType";
David Zeuthena99981f2013-04-29 13:42:47 -0700885 case kErrorCodeInstallDeviceOpenError:
886 return "kErrorCodeInstallDeviceOpenError";
887 case kErrorCodeKernelDeviceOpenError:
888 return "kErrorCodeKernelDeviceOpenError";
889 case kErrorCodeDownloadTransferError:
890 return "kErrorCodeDownloadTransferError";
891 case kErrorCodePayloadHashMismatchError:
892 return "kErrorCodePayloadHashMismatchError";
893 case kErrorCodePayloadSizeMismatchError:
894 return "kErrorCodePayloadSizeMismatchError";
895 case kErrorCodeDownloadPayloadVerificationError:
896 return "kErrorCodeDownloadPayloadVerificationError";
897 case kErrorCodeDownloadNewPartitionInfoError:
898 return "kErrorCodeDownloadNewPartitionInfoError";
899 case kErrorCodeDownloadWriteError:
900 return "kErrorCodeDownloadWriteError";
901 case kErrorCodeNewRootfsVerificationError:
902 return "kErrorCodeNewRootfsVerificationError";
903 case kErrorCodeNewKernelVerificationError:
904 return "kErrorCodeNewKernelVerificationError";
905 case kErrorCodeSignedDeltaPayloadExpectedError:
906 return "kErrorCodeSignedDeltaPayloadExpectedError";
907 case kErrorCodeDownloadPayloadPubKeyVerificationError:
908 return "kErrorCodeDownloadPayloadPubKeyVerificationError";
909 case kErrorCodePostinstallBootedFromFirmwareB:
910 return "kErrorCodePostinstallBootedFromFirmwareB";
911 case kErrorCodeDownloadStateInitializationError:
912 return "kErrorCodeDownloadStateInitializationError";
913 case kErrorCodeDownloadInvalidMetadataMagicString:
914 return "kErrorCodeDownloadInvalidMetadataMagicString";
915 case kErrorCodeDownloadSignatureMissingInManifest:
916 return "kErrorCodeDownloadSignatureMissingInManifest";
917 case kErrorCodeDownloadManifestParseError:
918 return "kErrorCodeDownloadManifestParseError";
919 case kErrorCodeDownloadMetadataSignatureError:
920 return "kErrorCodeDownloadMetadataSignatureError";
921 case kErrorCodeDownloadMetadataSignatureVerificationError:
922 return "kErrorCodeDownloadMetadataSignatureVerificationError";
923 case kErrorCodeDownloadMetadataSignatureMismatch:
924 return "kErrorCodeDownloadMetadataSignatureMismatch";
925 case kErrorCodeDownloadOperationHashVerificationError:
926 return "kErrorCodeDownloadOperationHashVerificationError";
927 case kErrorCodeDownloadOperationExecutionError:
928 return "kErrorCodeDownloadOperationExecutionError";
929 case kErrorCodeDownloadOperationHashMismatch:
930 return "kErrorCodeDownloadOperationHashMismatch";
931 case kErrorCodeOmahaRequestEmptyResponseError:
932 return "kErrorCodeOmahaRequestEmptyResponseError";
933 case kErrorCodeOmahaRequestXMLParseError:
934 return "kErrorCodeOmahaRequestXMLParseError";
935 case kErrorCodeDownloadInvalidMetadataSize:
936 return "kErrorCodeDownloadInvalidMetadataSize";
937 case kErrorCodeDownloadInvalidMetadataSignature:
938 return "kErrorCodeDownloadInvalidMetadataSignature";
939 case kErrorCodeOmahaResponseInvalid:
940 return "kErrorCodeOmahaResponseInvalid";
941 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
942 return "kErrorCodeOmahaUpdateIgnoredPerPolicy";
943 case kErrorCodeOmahaUpdateDeferredPerPolicy:
944 return "kErrorCodeOmahaUpdateDeferredPerPolicy";
945 case kErrorCodeOmahaErrorInHTTPResponse:
946 return "kErrorCodeOmahaErrorInHTTPResponse";
947 case kErrorCodeDownloadOperationHashMissingError:
948 return "kErrorCodeDownloadOperationHashMissingError";
949 case kErrorCodeDownloadMetadataSignatureMissingError:
950 return "kErrorCodeDownloadMetadataSignatureMissingError";
951 case kErrorCodeOmahaUpdateDeferredForBackoff:
952 return "kErrorCodeOmahaUpdateDeferredForBackoff";
953 case kErrorCodePostinstallPowerwashError:
954 return "kErrorCodePostinstallPowerwashError";
955 case kErrorCodeUpdateCanceledByChannelChange:
956 return "kErrorCodeUpdateCanceledByChannelChange";
957 case kErrorCodeUmaReportedMax:
958 return "kErrorCodeUmaReportedMax";
959 case kErrorCodeOmahaRequestHTTPResponseBase:
960 return "kErrorCodeOmahaRequestHTTPResponseBase";
961 case kErrorCodeResumedFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800962 return "Resumed";
David Zeuthena99981f2013-04-29 13:42:47 -0700963 case kErrorCodeDevModeFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800964 return "DevMode";
David Zeuthena99981f2013-04-29 13:42:47 -0700965 case kErrorCodeTestImageFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800966 return "TestImage";
David Zeuthena99981f2013-04-29 13:42:47 -0700967 case kErrorCodeTestOmahaUrlFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800968 return "TestOmahaUrl";
David Zeuthena99981f2013-04-29 13:42:47 -0700969 case kErrorCodeSpecialFlags:
970 return "kErrorCodeSpecialFlags";
Don Garrett81018e02013-07-30 18:46:31 -0700971 case kErrorCodePostinstallFirmwareRONotUpdatable:
972 return "kErrorCodePostinstallFirmwareRONotUpdatable";
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800973 // Don't add a default case to let the compiler warn about newly added
974 // error codes which should be added here.
975 }
976
977 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
978}
Jay Srinivasanf0572052012-10-23 18:12:56 -0700979
Gilad Arnold30dedd82013-07-03 06:19:09 -0700980bool CreatePowerwashMarkerFile(const char* file_path) {
981 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
982 bool result = utils::WriteFile(marker_file,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700983 kPowerwashCommand,
984 strlen(kPowerwashCommand));
Gilad Arnold30dedd82013-07-03 06:19:09 -0700985 if (result) {
986 LOG(INFO) << "Created " << marker_file << " to powerwash on next reboot";
987 } else {
988 PLOG(ERROR) << "Error in creating powerwash marker file: " << marker_file;
989 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700990
991 return result;
992}
993
Gilad Arnold30dedd82013-07-03 06:19:09 -0700994bool DeletePowerwashMarkerFile(const char* file_path) {
995 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
996 const FilePath kPowerwashMarkerPath(marker_file);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700997 bool result = file_util::Delete(kPowerwashMarkerPath, false);
998
999 if (result)
1000 LOG(INFO) << "Successfully deleted the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001001 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001002 else
1003 PLOG(ERROR) << "Could not delete the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001004 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001005
1006 return result;
1007}
1008
Chris Sosad317e402013-06-12 13:47:09 -07001009bool GetInstallDev(const std::string& boot_dev, std::string* install_dev) {
1010 TEST_AND_RETURN_FALSE(StringHasPrefix(boot_dev, "/dev/"));
Liam McLoughlin049d1652013-07-31 18:47:46 -07001011 string::iterator it;
1012 string ubiblock_prefix("/dev/ubiblock");
1013
1014 install_dev->assign(boot_dev);
1015
1016 if(StringHasPrefix(boot_dev, ubiblock_prefix)) {
1017 // UBI-based device
1018 it = install_dev->begin() + ubiblock_prefix.length();
1019 } else {
1020 // non-UBI device
1021 it = install_dev->end() - 1; // last character in string
1022 }
1023
Chris Sosad317e402013-06-12 13:47:09 -07001024 // Right now, we just switch '3' and '5' partition numbers.
Liam McLoughlin049d1652013-07-31 18:47:46 -07001025 TEST_AND_RETURN_FALSE(*it == '3' || *it == '5');
1026 *it = (*it == '3' ? '5' : '3');
1027
Chris Sosad317e402013-06-12 13:47:09 -07001028 return true;
1029}
1030
David Zeuthen27a48bc2013-08-06 12:06:29 -07001031Time TimeFromStructTimespec(struct timespec *ts) {
1032 int64 us = static_cast<int64>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
1033 static_cast<int64>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
1034 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
1035}
1036
1037gchar** StringVectorToGStrv(const vector<string> &vector) {
1038 GPtrArray *p = g_ptr_array_new();
1039 for (std::vector<string>::const_iterator i = vector.begin();
1040 i != vector.end(); ++i) {
1041 g_ptr_array_add(p, g_strdup(i->c_str()));
1042 }
1043 g_ptr_array_add(p, NULL);
1044 return reinterpret_cast<gchar**>(g_ptr_array_free(p, FALSE));
1045}
1046
1047string StringVectorToString(const vector<string> &vector) {
1048 string str = "[";
1049 for (std::vector<string>::const_iterator i = vector.begin();
1050 i != vector.end(); ++i) {
1051 if (i != vector.begin())
1052 str += ", ";
1053 str += '"';
1054 str += *i;
1055 str += '"';
1056 }
1057 str += "]";
1058 return str;
1059}
1060
David Zeuthen8f191b22013-08-06 12:27:50 -07001061string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
1062 string encoded_hash;
1063 OmahaHashCalculator::Base64Encode(payload_hash.c_str(),
1064 payload_hash.size(),
1065 &encoded_hash);
1066 return StringPrintf("cros_update_size_%zu_hash_%s",
1067 payload_size,
1068 encoded_hash.c_str());
1069}
1070
David Zeuthen910ec5b2013-09-26 12:10:58 -07001071bool IsXAttrSupported(const base::FilePath& dir_path) {
1072 char *path = strdup(dir_path.Append("xattr_test_XXXXXX").value().c_str());
1073
1074 int fd = mkstemp(path);
1075 if (fd == -1) {
1076 PLOG(ERROR) << "Error creating temporary file in " << dir_path.value();
1077 free(path);
1078 return false;
1079 }
1080
1081 if (unlink(path) != 0) {
1082 PLOG(ERROR) << "Error unlinking temporary file " << path;
1083 close(fd);
1084 free(path);
1085 return false;
1086 }
1087
1088 int xattr_res = fsetxattr(fd, "user.xattr-test", "value", strlen("value"), 0);
1089 if (xattr_res != 0) {
1090 if (errno == ENOTSUP) {
1091 // Leave it to call-sites to warn about non-support.
1092 } else {
1093 PLOG(ERROR) << "Error setting xattr on " << path;
1094 }
1095 }
1096 close(fd);
1097 free(path);
1098 return xattr_res == 0;
1099}
1100
adlr@google.com3defe6a2009-12-04 20:57:17 +00001101} // namespace utils
1102
1103} // namespace chromeos_update_engine