blob: d33a5ccf2d99d257b6dfaf5b4c1e2c188947e4e5 [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
J. Richard Barnette63137e52013-10-28 10:57:29 -070088string ParseECVersion(string input_line) {
89 TrimWhitespaceASCII(input_line, TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -070090
91 // At this point we want to conver the format key=value pair from mosys to
92 // a vector of key value pairs.
93 vector<pair<string, string> > kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -070094 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Chris Sosac1972482013-04-30 22:31:10 -070095 for (vector<pair<string, string> >::iterator it = kv_pairs.begin();
96 it != kv_pairs.end(); ++it) {
97 // Finally match against the fw_verion which may have quotes.
98 if (it->first == "fw_version") {
99 string output;
100 // Trim any quotes.
101 TrimString(it->second, "\"", &output);
102 return output;
103 }
104 }
105 }
106 LOG(ERROR) << "Unable to parse fwid from ec info.";
107 return "";
108}
109
110
J. Richard Barnette30842932013-10-28 15:04:23 -0700111const string KernelDeviceOfBootDevice(const std::string& boot_device) {
112 if (boot_device.empty())
113 return boot_device;
114
115 string ubiblock_prefix("/dev/ubiblock");
116 string ret;
117 char partition_num;
118 if (StringHasPrefix(boot_device, ubiblock_prefix)) {
119 // eg: /dev/ubiblock3_0 becomes /dev/mtdblock2
120 ret = "/dev/mtdblock";
121 partition_num = boot_device[ubiblock_prefix.size()];
122 } else {
123 // eg: /dev/sda3 becomes /dev/sda2
124 // eg: /dev/mmcblk0p3 becomes /dev/mmcblk0p2
125 ret = boot_device.substr(0, boot_device.size() - 1);
126 partition_num = boot_device[boot_device.size() - 1];
127 }
128
129 // Currently this assumes the partition number of the boot device is
130 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
131 // get the kernel device.
132 if (partition_num == '3' || partition_num == '5' || partition_num == '7') {
133 ret.append(1, partition_num - 1);
134 return ret;
135 }
136
137 return "";
138}
139
140
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800141bool WriteFile(const char* path, const char* data, int data_len) {
142 DirectFileWriter writer;
143 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
144 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700145 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800146 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800147 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800148 return true;
149}
150
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700151bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700152 const char* c_buf = static_cast<const char*>(buf);
153 ssize_t bytes_written = 0;
154 while (bytes_written < static_cast<ssize_t>(count)) {
155 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
156 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
157 bytes_written += rc;
158 }
159 return true;
160}
161
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700162bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
163 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700164 size_t bytes_written = 0;
165 int num_attempts = 0;
166 while (bytes_written < count) {
167 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700168 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
169 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700170 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
171 if (rc < 0) {
172 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
173 << " bytes_written=" << bytes_written
174 << " count=" << count << " offset=" << offset;
175 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700176 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
177 bytes_written += rc;
178 }
179 return true;
180}
181
182bool PReadAll(int fd, void* buf, size_t count, off_t offset,
183 ssize_t* out_bytes_read) {
184 char* c_buf = static_cast<char*>(buf);
185 ssize_t bytes_read = 0;
186 while (bytes_read < static_cast<ssize_t>(count)) {
187 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
188 offset + bytes_read);
189 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
190 if (rc == 0) {
191 break;
192 }
193 bytes_read += rc;
194 }
195 *out_bytes_read = bytes_read;
196 return true;
Darin Petkov296889c2010-07-23 16:20:54 -0700197
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700198}
199
Gilad Arnold19a45f02012-07-19 12:36:10 -0700200// Append |nbytes| of content from |buf| to the vector pointed to by either
201// |vec_p| or |str_p|.
202static void AppendBytes(const char* buf, size_t nbytes,
203 std::vector<char>* vec_p) {
204 CHECK(buf);
205 CHECK(vec_p);
206 vec_p->insert(vec_p->end(), buf, buf + nbytes);
207}
208static void AppendBytes(const char* buf, size_t nbytes,
209 std::string* str_p) {
210 CHECK(buf);
211 CHECK(str_p);
212 str_p->append(buf, nbytes);
213}
214
215// Reads from an open file |fp|, appending the read content to the container
216// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200217// file's content, false otherwise. If |size| is not -1, reads up to |size|
218// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700219template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200220static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700221 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200222 CHECK(size == -1 || size >= 0);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700223 char buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200224 while (size == -1 || size > 0) {
225 off_t bytes_to_read = sizeof(buf);
226 if (size > 0 && bytes_to_read > size) {
227 bytes_to_read = size;
228 }
229 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
230 if (!nbytes) {
231 break;
232 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700233 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200234 if (size != -1) {
235 CHECK(size >= static_cast<off_t>(nbytes));
236 size -= nbytes;
237 }
238 }
239 if (ferror(fp)) {
240 return false;
241 }
242 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700243}
244
Darin Petkov8e447e02013-04-16 16:23:50 +0200245// Opens a file |path| for reading and appends its the contents to a container
246// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
247// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700248template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200249static bool ReadFileChunkAndAppend(const std::string& path,
250 off_t offset,
251 off_t size,
252 T* out_p) {
253 CHECK_GE(offset, 0);
254 CHECK(size == -1 || size >= 0);
255 file_util::ScopedFILE fp(fopen(path.c_str(), "r"));
256 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000257 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200258 if (offset) {
259 // Return success without appending any data if a chunk beyond the end of
260 // the file is requested.
261 if (offset >= FileSize(path)) {
262 return true;
263 }
264 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
265 }
266 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000267}
268
Gilad Arnold19a45f02012-07-19 12:36:10 -0700269// Invokes a pipe |cmd|, then uses |append_func| to append its stdout to a
270// container |out_p|.
271template <class T>
272static bool ReadPipeAndAppend(const std::string& cmd, T* out_p) {
273 FILE* fp = popen(cmd.c_str(), "r");
274 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000275 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200276 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700277 return (success && pclose(fp) >= 0);
278}
279
280
Darin Petkov8e447e02013-04-16 16:23:50 +0200281bool ReadFile(const string& path, vector<char>* out_p) {
282 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700283}
284
Darin Petkov8e447e02013-04-16 16:23:50 +0200285bool ReadFile(const string& path, string* out_p) {
286 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700287}
288
Darin Petkov8e447e02013-04-16 16:23:50 +0200289bool ReadFileChunk(const string& path, off_t offset, off_t size,
290 vector<char>* out_p) {
291 return ReadFileChunkAndAppend(path, offset, size, out_p);
292}
293
294bool ReadPipe(const string& cmd, vector<char>* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700295 return ReadPipeAndAppend(cmd, out_p);
296}
297
Darin Petkov8e447e02013-04-16 16:23:50 +0200298bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700299 return ReadPipeAndAppend(cmd, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000300}
301
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700302off_t FileSize(const string& path) {
303 struct stat stbuf;
304 int rc = stat(path.c_str(), &stbuf);
305 CHECK_EQ(rc, 0);
306 if (rc < 0)
307 return rc;
308 return stbuf.st_size;
309}
310
adlr@google.com3defe6a2009-12-04 20:57:17 +0000311void HexDumpArray(const unsigned char* const arr, const size_t length) {
312 const unsigned char* const char_arr =
313 reinterpret_cast<const unsigned char* const>(arr);
314 LOG(INFO) << "Logging array of length: " << length;
315 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700316 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000317 const unsigned int bytes_remaining = length - i;
318 const unsigned int bytes_per_this_line = min(bytes_per_line,
319 bytes_remaining);
320 char header[100];
321 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
322 TEST_AND_RETURN(r == 13);
323 string line = header;
324 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
325 char buf[20];
326 unsigned char c = char_arr[i + j];
327 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
328 TEST_AND_RETURN(r == 3);
329 line += buf;
330 }
331 LOG(INFO) << line;
332 }
333}
334
335namespace {
336class ScopedDirCloser {
337 public:
338 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
339 ~ScopedDirCloser() {
340 if (dir_ && *dir_) {
341 int r = closedir(*dir_);
342 TEST_AND_RETURN_ERRNO(r == 0);
343 *dir_ = NULL;
344 dir_ = NULL;
345 }
346 }
347 private:
348 DIR** dir_;
349};
350} // namespace {}
351
352bool RecursiveUnlinkDir(const std::string& path) {
353 struct stat stbuf;
354 int r = lstat(path.c_str(), &stbuf);
355 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
356 if ((r < 0) && (errno == ENOENT))
357 // path request is missing. that's fine.
358 return true;
359 if (!S_ISDIR(stbuf.st_mode)) {
360 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700361 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000362 // success or path disappeared before we could unlink.
363 return true;
364 }
365 {
366 // We have a dir, unlink all children, then delete dir
367 DIR *dir = opendir(path.c_str());
368 TEST_AND_RETURN_FALSE_ERRNO(dir);
369 ScopedDirCloser dir_closer(&dir);
370 struct dirent dir_entry;
371 struct dirent *dir_entry_p;
372 int err = 0;
373 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
374 if (dir_entry_p == NULL) {
375 // end of stream reached
376 break;
377 }
378 // Skip . and ..
379 if (!strcmp(dir_entry_p->d_name, ".") ||
380 !strcmp(dir_entry_p->d_name, ".."))
381 continue;
382 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700383 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000384 }
385 TEST_AND_RETURN_FALSE(err == 0);
386 }
387 // unlink dir
388 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
389 return true;
390}
391
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700392string RootDevice(const string& partition_device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700393 FilePath device_path(partition_device);
394 if (device_path.DirName().value() != "/dev") {
395 return "";
396 }
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700397 string::const_iterator it = --partition_device.end();
398 for (; it >= partition_device.begin(); --it) {
399 if (!isdigit(*it))
400 break;
401 }
402 // Some devices contain a p before the partitions. For example:
403 // /dev/mmc0p4 should be shortened to /dev/mmc0.
404 if (*it == 'p')
405 --it;
406 return string(partition_device.begin(), it + 1);
407}
408
409string PartitionNumber(const string& partition_device) {
410 CHECK(!partition_device.empty());
411 string::const_iterator it = --partition_device.end();
412 for (; it >= partition_device.begin(); --it) {
413 if (!isdigit(*it))
414 break;
415 }
416 return string(it + 1, partition_device.end());
417}
418
Darin Petkovf74eb652010-08-04 12:08:38 -0700419string SysfsBlockDevice(const string& device) {
420 FilePath device_path(device);
421 if (device_path.DirName().value() != "/dev") {
422 return "";
423 }
424 return FilePath("/sys/block").Append(device_path.BaseName()).value();
425}
426
427bool IsRemovableDevice(const std::string& device) {
428 string sysfs_block = SysfsBlockDevice(device);
429 string removable;
430 if (sysfs_block.empty() ||
431 !file_util::ReadFileToString(FilePath(sysfs_block).Append("removable"),
432 &removable)) {
433 return false;
434 }
435 TrimWhitespaceASCII(removable, TRIM_ALL, &removable);
436 return removable == "1";
437}
438
adlr@google.com3defe6a2009-12-04 20:57:17 +0000439std::string ErrnoNumberAsString(int err) {
440 char buf[100];
441 buf[0] = '\0';
442 return strerror_r(err, buf, sizeof(buf));
443}
444
445std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
446 string ret;
447 bool last_insert_was_slash = false;
448 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
449 if (*it == '/') {
450 if (last_insert_was_slash)
451 continue;
452 last_insert_was_slash = true;
453 } else {
454 last_insert_was_slash = false;
455 }
456 ret.push_back(*it);
457 }
458 if (strip_trailing_slash && last_insert_was_slash) {
459 string::size_type last_non_slash = ret.find_last_not_of('/');
460 if (last_non_slash != string::npos) {
461 ret.resize(last_non_slash + 1);
462 } else {
463 ret = "";
464 }
465 }
466 return ret;
467}
468
469bool FileExists(const char* path) {
470 struct stat stbuf;
471 return 0 == lstat(path, &stbuf);
472}
473
Darin Petkov30291ed2010-11-12 10:23:06 -0800474bool IsSymlink(const char* path) {
475 struct stat stbuf;
476 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
477}
478
adlr@google.com3defe6a2009-12-04 20:57:17 +0000479std::string TempFilename(string path) {
480 static const string suffix("XXXXXX");
481 CHECK(StringHasSuffix(path, suffix));
482 do {
483 string new_suffix;
484 for (unsigned int i = 0; i < suffix.size(); i++) {
485 int r = rand() % (26 * 2 + 10); // [a-zA-Z0-9]
486 if (r < 26)
487 new_suffix.append(1, 'a' + r);
488 else if (r < (26 * 2))
489 new_suffix.append(1, 'A' + r - 26);
490 else
491 new_suffix.append(1, '0' + r - (26 * 2));
492 }
493 CHECK_EQ(new_suffix.size(), suffix.size());
494 path.resize(path.size() - new_suffix.size());
495 path.append(new_suffix);
496 } while (FileExists(path.c_str()));
497 return path;
498}
499
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700500bool MakeTempFile(const std::string& filename_template,
501 std::string* filename,
502 int* fd) {
503 DCHECK(filename || fd);
504 vector<char> buf(filename_template.size() + 1);
505 memcpy(&buf[0], filename_template.data(), filename_template.size());
506 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700507
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700508 int mkstemp_fd = mkstemp(&buf[0]);
509 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
510 if (filename) {
511 *filename = &buf[0];
512 }
513 if (fd) {
514 *fd = mkstemp_fd;
515 } else {
516 close(mkstemp_fd);
517 }
518 return true;
519}
520
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700521bool MakeTempDirectory(const std::string& dirname_template,
522 std::string* dirname) {
523 DCHECK(dirname);
524 vector<char> buf(dirname_template.size() + 1);
525 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
526 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700527
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700528 char* return_code = mkdtemp(&buf[0]);
529 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
530 *dirname = &buf[0];
531 return true;
532}
533
adlr@google.com3defe6a2009-12-04 20:57:17 +0000534bool StringHasSuffix(const std::string& str, const std::string& suffix) {
535 if (suffix.size() > str.size())
536 return false;
537 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
538}
539
540bool StringHasPrefix(const std::string& str, const std::string& prefix) {
541 if (prefix.size() > str.size())
542 return false;
543 return 0 == str.compare(0, prefix.size(), prefix);
544}
545
adlr@google.com3defe6a2009-12-04 20:57:17 +0000546bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700547 const string& mountpoint,
548 unsigned long mountflags) {
549 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000550 if (rc < 0) {
551 string msg = ErrnoNumberAsString(errno);
552 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
553 << device << " on " << mountpoint;
554 return false;
555 }
556 return true;
557}
558
559bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700560 for (int num_retries = 0; ; ++num_retries) {
561 if (umount(mountpoint.c_str()) == 0)
562 break;
563
564 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
565 num_retries < kUnmountMaxNumOfRetries);
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800566 g_usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700567 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000568 return true;
569}
570
Darin Petkovd3f8c892010-10-12 21:38:45 -0700571bool GetFilesystemSize(const std::string& device,
572 int* out_block_count,
573 int* out_block_size) {
574 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
575 TEST_AND_RETURN_FALSE(fd >= 0);
576 ScopedFdCloser fd_closer(&fd);
577 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
578}
579
580bool GetFilesystemSizeFromFD(int fd,
581 int* out_block_count,
582 int* out_block_size) {
583 TEST_AND_RETURN_FALSE(fd >= 0);
584
585 // Determine the ext3 filesystem size by directly reading the block count and
586 // block size information from the superblock. See include/linux/ext3_fs.h for
587 // more details on the structure.
588 ssize_t kBufferSize = 16 * sizeof(uint32_t);
589 char buffer[kBufferSize];
590 const int kSuperblockOffset = 1024;
591 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
592 kBufferSize) {
593 PLOG(ERROR) << "Unable to determine file system size:";
594 return false;
595 }
596 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
597 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
598 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
599 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
600 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
601 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
602 block_count = le32toh(block_count);
603 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
604 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
605 magic = le16toh(magic);
606
607 // Sanity check the parameters.
608 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
609 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
610 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
611 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
612 int block_size = 1 << log_block_size;
613 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
614 block_size <= kExt3MaxBlockSize);
615 TEST_AND_RETURN_FALSE(block_count > 0);
616
617 if (out_block_count) {
618 *out_block_count = block_count;
619 }
620 if (out_block_size) {
621 *out_block_size = block_size;
622 }
623 return true;
624}
625
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700626bool GetBootloader(BootLoader* out_bootloader) {
627 // For now, hardcode to syslinux.
628 *out_bootloader = BootLoader_SYSLINUX;
629 return true;
630}
631
Darin Petkova0b9e772011-10-06 05:05:56 -0700632string GetAndFreeGError(GError** error) {
633 if (!*error) {
634 return "Unknown GLib error.";
635 }
636 string message =
637 base::StringPrintf("GError(%d): %s",
638 (*error)->code,
639 (*error)->message ? (*error)->message : "(unknown)");
640 g_error_free(*error);
641 *error = NULL;
642 return message;
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700643}
644
Darin Petkov296889c2010-07-23 16:20:54 -0700645bool Reboot() {
646 vector<string> command;
647 command.push_back("/sbin/shutdown");
648 command.push_back("-r");
649 command.push_back("now");
650 int rc = 0;
Darin Petkov85d02b72011-05-17 13:25:51 -0700651 Subprocess::SynchronousExec(command, &rc, NULL);
Darin Petkov296889c2010-07-23 16:20:54 -0700652 TEST_AND_RETURN_FALSE(rc == 0);
653 return true;
654}
655
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800656namespace {
657// Do the actual trigger. We do it as a main-loop callback to (try to) get a
658// consistent stack trace.
659gboolean TriggerCrashReporterUpload(void* unused) {
660 pid_t pid = fork();
661 CHECK(pid >= 0) << "fork failed"; // fork() failed. Something is very wrong.
662 if (pid == 0) {
663 // We are the child. Crash.
664 abort(); // never returns
665 }
666 // We are the parent. Wait for child to terminate.
667 pid_t result = waitpid(pid, NULL, 0);
668 LOG_IF(ERROR, result < 0) << "waitpid() failed";
669 return FALSE; // Don't call this callback again
670}
671} // namespace {}
672
673void ScheduleCrashReporterUpload() {
674 g_idle_add(&TriggerCrashReporterUpload, NULL);
675}
676
Chris Sosa4f8ee272012-11-30 13:01:54 -0800677bool SetCpuShares(CpuShares shares) {
678 string string_shares = base::IntToString(static_cast<int>(shares));
679 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
680 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
681 if(utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
682 string_shares.size())){
683 return true;
684 } else {
685 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
686 << " using " << cpu_shares_file;
687 return false;
688 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700689}
690
Chris Sosa4f8ee272012-11-30 13:01:54 -0800691int CompareCpuShares(CpuShares shares_lhs,
692 CpuShares shares_rhs) {
693 return static_cast<int>(shares_lhs) - static_cast<int>(shares_rhs);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700694}
695
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700696int FuzzInt(int value, unsigned int range) {
697 int min = value - range / 2;
698 int max = value + range - range / 2;
699 return base::RandInt(min, max);
700}
701
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800702gboolean GlibRunClosure(gpointer data) {
703 google::protobuf::Closure* callback =
704 reinterpret_cast<google::protobuf::Closure*>(data);
705 callback->Run();
706 return FALSE;
707}
708
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700709string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800710 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700711}
712
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800713string FormatTimeDelta(TimeDelta delta) {
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700714 // Canonicalize into days, hours, minutes, seconds and microseconds.
715 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800716 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700717 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800718 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700719 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800720 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700721 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800722 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700723 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800724
725 // Construct and return string.
726 string str;
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700727 if (days)
728 base::StringAppendF(&str, "%ud", days);
729 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800730 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700731 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800732 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700733 base::StringAppendF(&str, "%u", secs);
734 if (usecs) {
735 int width = 6;
736 while ((usecs / 10) * 10 == usecs) {
737 usecs /= 10;
738 width--;
739 }
740 base::StringAppendF(&str, ".%0*u", width, usecs);
741 }
742 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800743 return str;
744}
745
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700746string ToString(const Time utc_time) {
747 Time::Exploded exp_time;
748 utc_time.UTCExplode(&exp_time);
749 return StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
750 exp_time.month,
751 exp_time.day_of_month,
752 exp_time.year,
753 exp_time.hour,
754 exp_time.minute,
755 exp_time.second);
756}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000757
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700758string ToString(bool b) {
759 return (b ? "true" : "false");
760}
761
Alex Deymo1c656c42013-06-28 11:02:14 -0700762string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700763 switch (source) {
764 case kDownloadSourceHttpsServer: return "HttpsServer";
765 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700766 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -0700767 case kNumDownloadSources: return "Unknown";
768 // Don't add a default case to let the compiler warn about newly added
769 // download sources which should be added here.
770 }
771
772 return "Unknown";
773}
774
Alex Deymo1c656c42013-06-28 11:02:14 -0700775string ToString(PayloadType payload_type) {
776 switch (payload_type) {
777 case kPayloadTypeDelta: return "Delta";
778 case kPayloadTypeFull: return "Full";
779 case kPayloadTypeForcedFull: return "ForcedFull";
780 case kNumPayloadTypes: return "Unknown";
781 // Don't add a default case to let the compiler warn about newly added
782 // payload types which should be added here.
783 }
784
785 return "Unknown";
786}
787
David Zeuthena99981f2013-04-29 13:42:47 -0700788ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700789 // Ignore the higher order bits in the code by applying the mask as
790 // we want the enumerations to be in the small contiguous range
David Zeuthena99981f2013-04-29 13:42:47 -0700791 // with values less than kErrorCodeUmaReportedMax.
792 ErrorCode base_code = static_cast<ErrorCode>(code & ~kErrorCodeSpecialFlags);
Jay Srinivasanf0572052012-10-23 18:12:56 -0700793
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800794 // Make additional adjustments required for UMA and error classification.
795 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
796 // chromium-os:34369.
David Zeuthena99981f2013-04-29 13:42:47 -0700797 if (base_code >= kErrorCodeOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700798 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800799 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800800 LOG(INFO) << "Converting error code " << base_code
David Zeuthena99981f2013-04-29 13:42:47 -0700801 << " to kErrorCodeOmahaErrorInHTTPResponse";
802 base_code = kErrorCodeOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700803 }
804
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800805 return base_code;
806}
807
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800808// Returns a printable version of the various flags denoted in the higher order
809// bits of the given code. Returns an empty string if none of those bits are
810// set.
811string GetFlagNames(uint32_t code) {
David Zeuthena99981f2013-04-29 13:42:47 -0700812 uint32_t flags = code & kErrorCodeSpecialFlags;
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800813 string flag_names;
814 string separator = "";
815 for(size_t i = 0; i < sizeof(flags) * 8; i++) {
816 uint32_t flag = flags & (1 << i);
817 if (flag) {
David Zeuthena99981f2013-04-29 13:42:47 -0700818 flag_names += separator + CodeToString(static_cast<ErrorCode>(flag));
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800819 separator = ", ";
820 }
821 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800822
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800823 return flag_names;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700824}
825
David Zeuthena99981f2013-04-29 13:42:47 -0700826void SendErrorCodeToUma(SystemState* system_state, ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800827 if (!system_state)
828 return;
829
David Zeuthena99981f2013-04-29 13:42:47 -0700830 ErrorCode uma_error_code = GetBaseErrorCode(code);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800831
832 // If the code doesn't have flags computed already, compute them now based on
833 // the state of the current update attempt.
David Zeuthena99981f2013-04-29 13:42:47 -0700834 uint32_t flags = code & kErrorCodeSpecialFlags;
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800835 if (!flags)
836 flags = system_state->update_attempter()->GetErrorCodeFlags();
837
838 // Determine the UMA bucket depending on the flags. But, ignore the resumed
839 // flag, as it's perfectly normal for production devices to resume their
840 // downloads and so we want to record those cases also in NormalErrorCodes
841 // bucket.
David Zeuthena99981f2013-04-29 13:42:47 -0700842 string metric = (flags & ~kErrorCodeResumedFlag) ?
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800843 "Installer.DevModeErrorCodes" : "Installer.NormalErrorCodes";
844
845 LOG(INFO) << "Sending error code " << uma_error_code
846 << " (" << CodeToString(uma_error_code) << ")"
847 << " to UMA metric: " << metric
848 << ". Flags = " << (flags ? GetFlagNames(flags) : "None");
849
850 system_state->metrics_lib()->SendEnumToUMA(metric,
851 uma_error_code,
David Zeuthena99981f2013-04-29 13:42:47 -0700852 kErrorCodeUmaReportedMax);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800853}
854
David Zeuthena99981f2013-04-29 13:42:47 -0700855string CodeToString(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800856 // If the given code has both parts (i.e. the error code part and the flags
857 // part) then strip off the flags part since the switch statement below
858 // has case statements only for the base error code or a single flag but
859 // doesn't support any combinations of those.
David Zeuthena99981f2013-04-29 13:42:47 -0700860 if ((code & kErrorCodeSpecialFlags) && (code & ~kErrorCodeSpecialFlags))
861 code = static_cast<ErrorCode>(code & ~kErrorCodeSpecialFlags);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800862 switch (code) {
David Zeuthena99981f2013-04-29 13:42:47 -0700863 case kErrorCodeSuccess: return "kErrorCodeSuccess";
864 case kErrorCodeError: return "kErrorCodeError";
865 case kErrorCodeOmahaRequestError: return "kErrorCodeOmahaRequestError";
866 case kErrorCodeOmahaResponseHandlerError:
867 return "kErrorCodeOmahaResponseHandlerError";
868 case kErrorCodeFilesystemCopierError:
869 return "kErrorCodeFilesystemCopierError";
870 case kErrorCodePostinstallRunnerError:
871 return "kErrorCodePostinstallRunnerError";
Gilad Arnold21504f02013-05-24 08:51:22 -0700872 case kErrorCodePayloadMismatchedType:
873 return "kErrorCodePayloadMismatchedType";
David Zeuthena99981f2013-04-29 13:42:47 -0700874 case kErrorCodeInstallDeviceOpenError:
875 return "kErrorCodeInstallDeviceOpenError";
876 case kErrorCodeKernelDeviceOpenError:
877 return "kErrorCodeKernelDeviceOpenError";
878 case kErrorCodeDownloadTransferError:
879 return "kErrorCodeDownloadTransferError";
880 case kErrorCodePayloadHashMismatchError:
881 return "kErrorCodePayloadHashMismatchError";
882 case kErrorCodePayloadSizeMismatchError:
883 return "kErrorCodePayloadSizeMismatchError";
884 case kErrorCodeDownloadPayloadVerificationError:
885 return "kErrorCodeDownloadPayloadVerificationError";
886 case kErrorCodeDownloadNewPartitionInfoError:
887 return "kErrorCodeDownloadNewPartitionInfoError";
888 case kErrorCodeDownloadWriteError:
889 return "kErrorCodeDownloadWriteError";
890 case kErrorCodeNewRootfsVerificationError:
891 return "kErrorCodeNewRootfsVerificationError";
892 case kErrorCodeNewKernelVerificationError:
893 return "kErrorCodeNewKernelVerificationError";
894 case kErrorCodeSignedDeltaPayloadExpectedError:
895 return "kErrorCodeSignedDeltaPayloadExpectedError";
896 case kErrorCodeDownloadPayloadPubKeyVerificationError:
897 return "kErrorCodeDownloadPayloadPubKeyVerificationError";
898 case kErrorCodePostinstallBootedFromFirmwareB:
899 return "kErrorCodePostinstallBootedFromFirmwareB";
900 case kErrorCodeDownloadStateInitializationError:
901 return "kErrorCodeDownloadStateInitializationError";
902 case kErrorCodeDownloadInvalidMetadataMagicString:
903 return "kErrorCodeDownloadInvalidMetadataMagicString";
904 case kErrorCodeDownloadSignatureMissingInManifest:
905 return "kErrorCodeDownloadSignatureMissingInManifest";
906 case kErrorCodeDownloadManifestParseError:
907 return "kErrorCodeDownloadManifestParseError";
908 case kErrorCodeDownloadMetadataSignatureError:
909 return "kErrorCodeDownloadMetadataSignatureError";
910 case kErrorCodeDownloadMetadataSignatureVerificationError:
911 return "kErrorCodeDownloadMetadataSignatureVerificationError";
912 case kErrorCodeDownloadMetadataSignatureMismatch:
913 return "kErrorCodeDownloadMetadataSignatureMismatch";
914 case kErrorCodeDownloadOperationHashVerificationError:
915 return "kErrorCodeDownloadOperationHashVerificationError";
916 case kErrorCodeDownloadOperationExecutionError:
917 return "kErrorCodeDownloadOperationExecutionError";
918 case kErrorCodeDownloadOperationHashMismatch:
919 return "kErrorCodeDownloadOperationHashMismatch";
920 case kErrorCodeOmahaRequestEmptyResponseError:
921 return "kErrorCodeOmahaRequestEmptyResponseError";
922 case kErrorCodeOmahaRequestXMLParseError:
923 return "kErrorCodeOmahaRequestXMLParseError";
924 case kErrorCodeDownloadInvalidMetadataSize:
925 return "kErrorCodeDownloadInvalidMetadataSize";
926 case kErrorCodeDownloadInvalidMetadataSignature:
927 return "kErrorCodeDownloadInvalidMetadataSignature";
928 case kErrorCodeOmahaResponseInvalid:
929 return "kErrorCodeOmahaResponseInvalid";
930 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
931 return "kErrorCodeOmahaUpdateIgnoredPerPolicy";
932 case kErrorCodeOmahaUpdateDeferredPerPolicy:
933 return "kErrorCodeOmahaUpdateDeferredPerPolicy";
934 case kErrorCodeOmahaErrorInHTTPResponse:
935 return "kErrorCodeOmahaErrorInHTTPResponse";
936 case kErrorCodeDownloadOperationHashMissingError:
937 return "kErrorCodeDownloadOperationHashMissingError";
938 case kErrorCodeDownloadMetadataSignatureMissingError:
939 return "kErrorCodeDownloadMetadataSignatureMissingError";
940 case kErrorCodeOmahaUpdateDeferredForBackoff:
941 return "kErrorCodeOmahaUpdateDeferredForBackoff";
942 case kErrorCodePostinstallPowerwashError:
943 return "kErrorCodePostinstallPowerwashError";
944 case kErrorCodeUpdateCanceledByChannelChange:
945 return "kErrorCodeUpdateCanceledByChannelChange";
946 case kErrorCodeUmaReportedMax:
947 return "kErrorCodeUmaReportedMax";
948 case kErrorCodeOmahaRequestHTTPResponseBase:
949 return "kErrorCodeOmahaRequestHTTPResponseBase";
950 case kErrorCodeResumedFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800951 return "Resumed";
David Zeuthena99981f2013-04-29 13:42:47 -0700952 case kErrorCodeDevModeFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800953 return "DevMode";
David Zeuthena99981f2013-04-29 13:42:47 -0700954 case kErrorCodeTestImageFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800955 return "TestImage";
David Zeuthena99981f2013-04-29 13:42:47 -0700956 case kErrorCodeTestOmahaUrlFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800957 return "TestOmahaUrl";
David Zeuthena99981f2013-04-29 13:42:47 -0700958 case kErrorCodeSpecialFlags:
959 return "kErrorCodeSpecialFlags";
Don Garrett81018e02013-07-30 18:46:31 -0700960 case kErrorCodePostinstallFirmwareRONotUpdatable:
961 return "kErrorCodePostinstallFirmwareRONotUpdatable";
Don Garrett4d039442013-10-28 18:40:06 -0700962 case kErrorCodeUnsupportedMajorPayloadVersion:
963 return "kErrorCodeUnsupportedMajorPayloadVersion";
964 case kErrorCodeUnsupportedMinorPayloadVersion:
965 return "kErrorCodeUnsupportedMinorPayloadVersion";
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800966 // Don't add a default case to let the compiler warn about newly added
967 // error codes which should be added here.
968 }
969
970 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
971}
Jay Srinivasanf0572052012-10-23 18:12:56 -0700972
Gilad Arnold30dedd82013-07-03 06:19:09 -0700973bool CreatePowerwashMarkerFile(const char* file_path) {
974 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
975 bool result = utils::WriteFile(marker_file,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700976 kPowerwashCommand,
977 strlen(kPowerwashCommand));
Gilad Arnold30dedd82013-07-03 06:19:09 -0700978 if (result) {
979 LOG(INFO) << "Created " << marker_file << " to powerwash on next reboot";
980 } else {
981 PLOG(ERROR) << "Error in creating powerwash marker file: " << marker_file;
982 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700983
984 return result;
985}
986
Gilad Arnold30dedd82013-07-03 06:19:09 -0700987bool DeletePowerwashMarkerFile(const char* file_path) {
988 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
989 const FilePath kPowerwashMarkerPath(marker_file);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700990 bool result = file_util::Delete(kPowerwashMarkerPath, false);
991
992 if (result)
993 LOG(INFO) << "Successfully deleted the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -0700994 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700995 else
996 PLOG(ERROR) << "Could not delete the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -0700997 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700998
999 return result;
1000}
1001
Chris Sosad317e402013-06-12 13:47:09 -07001002bool GetInstallDev(const std::string& boot_dev, std::string* install_dev) {
1003 TEST_AND_RETURN_FALSE(StringHasPrefix(boot_dev, "/dev/"));
Liam McLoughlin049d1652013-07-31 18:47:46 -07001004 string::iterator it;
1005 string ubiblock_prefix("/dev/ubiblock");
1006
1007 install_dev->assign(boot_dev);
1008
1009 if(StringHasPrefix(boot_dev, ubiblock_prefix)) {
1010 // UBI-based device
1011 it = install_dev->begin() + ubiblock_prefix.length();
1012 } else {
1013 // non-UBI device
1014 it = install_dev->end() - 1; // last character in string
1015 }
1016
Chris Sosad317e402013-06-12 13:47:09 -07001017 // Right now, we just switch '3' and '5' partition numbers.
Liam McLoughlin049d1652013-07-31 18:47:46 -07001018 TEST_AND_RETURN_FALSE(*it == '3' || *it == '5');
1019 *it = (*it == '3' ? '5' : '3');
1020
Chris Sosad317e402013-06-12 13:47:09 -07001021 return true;
1022}
1023
David Zeuthen27a48bc2013-08-06 12:06:29 -07001024Time TimeFromStructTimespec(struct timespec *ts) {
1025 int64 us = static_cast<int64>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
1026 static_cast<int64>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
1027 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
1028}
1029
1030gchar** StringVectorToGStrv(const vector<string> &vector) {
1031 GPtrArray *p = g_ptr_array_new();
1032 for (std::vector<string>::const_iterator i = vector.begin();
1033 i != vector.end(); ++i) {
1034 g_ptr_array_add(p, g_strdup(i->c_str()));
1035 }
1036 g_ptr_array_add(p, NULL);
1037 return reinterpret_cast<gchar**>(g_ptr_array_free(p, FALSE));
1038}
1039
1040string StringVectorToString(const vector<string> &vector) {
1041 string str = "[";
1042 for (std::vector<string>::const_iterator i = vector.begin();
1043 i != vector.end(); ++i) {
1044 if (i != vector.begin())
1045 str += ", ";
1046 str += '"';
1047 str += *i;
1048 str += '"';
1049 }
1050 str += "]";
1051 return str;
1052}
1053
David Zeuthen8f191b22013-08-06 12:27:50 -07001054string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
1055 string encoded_hash;
1056 OmahaHashCalculator::Base64Encode(payload_hash.c_str(),
1057 payload_hash.size(),
1058 &encoded_hash);
1059 return StringPrintf("cros_update_size_%zu_hash_%s",
1060 payload_size,
1061 encoded_hash.c_str());
1062}
1063
David Zeuthen910ec5b2013-09-26 12:10:58 -07001064bool IsXAttrSupported(const base::FilePath& dir_path) {
1065 char *path = strdup(dir_path.Append("xattr_test_XXXXXX").value().c_str());
1066
1067 int fd = mkstemp(path);
1068 if (fd == -1) {
1069 PLOG(ERROR) << "Error creating temporary file in " << dir_path.value();
1070 free(path);
1071 return false;
1072 }
1073
1074 if (unlink(path) != 0) {
1075 PLOG(ERROR) << "Error unlinking temporary file " << path;
1076 close(fd);
1077 free(path);
1078 return false;
1079 }
1080
1081 int xattr_res = fsetxattr(fd, "user.xattr-test", "value", strlen("value"), 0);
1082 if (xattr_res != 0) {
1083 if (errno == ENOTSUP) {
1084 // Leave it to call-sites to warn about non-support.
1085 } else {
1086 PLOG(ERROR) << "Error setting xattr on " << path;
1087 }
1088 }
1089 close(fd);
1090 free(path);
1091 return xattr_res == 0;
1092}
1093
adlr@google.com3defe6a2009-12-04 20:57:17 +00001094} // namespace utils
1095
1096} // namespace chromeos_update_engine