blob: 7e5cf75f998e0f89b5baa3ac769967d98e1859ac [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
Chris Sosa4f8ee272012-11-30 13:01:54 -080063// Cgroup container is created in update-engine's upstart script located at
64// /etc/init/update-engine.conf.
65static const char kCGroupDir[] = "/sys/fs/cgroup/cpu/update-engine";
66
J. Richard Barnette63137e52013-10-28 10:57:29 -070067string ParseECVersion(string input_line) {
68 TrimWhitespaceASCII(input_line, TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -070069
70 // At this point we want to conver the format key=value pair from mosys to
71 // a vector of key value pairs.
72 vector<pair<string, string> > kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -070073 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Chris Sosac1972482013-04-30 22:31:10 -070074 for (vector<pair<string, string> >::iterator it = kv_pairs.begin();
75 it != kv_pairs.end(); ++it) {
76 // Finally match against the fw_verion which may have quotes.
77 if (it->first == "fw_version") {
78 string output;
79 // Trim any quotes.
80 TrimString(it->second, "\"", &output);
81 return output;
82 }
83 }
84 }
85 LOG(ERROR) << "Unable to parse fwid from ec info.";
86 return "";
87}
88
89
J. Richard Barnette30842932013-10-28 15:04:23 -070090const string KernelDeviceOfBootDevice(const std::string& boot_device) {
91 if (boot_device.empty())
92 return boot_device;
93
94 string ubiblock_prefix("/dev/ubiblock");
95 string ret;
96 char partition_num;
97 if (StringHasPrefix(boot_device, ubiblock_prefix)) {
98 // eg: /dev/ubiblock3_0 becomes /dev/mtdblock2
99 ret = "/dev/mtdblock";
100 partition_num = boot_device[ubiblock_prefix.size()];
101 } else {
102 // eg: /dev/sda3 becomes /dev/sda2
103 // eg: /dev/mmcblk0p3 becomes /dev/mmcblk0p2
104 ret = boot_device.substr(0, boot_device.size() - 1);
105 partition_num = boot_device[boot_device.size() - 1];
106 }
107
108 // Currently this assumes the partition number of the boot device is
109 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
110 // get the kernel device.
111 if (partition_num == '3' || partition_num == '5' || partition_num == '7') {
112 ret.append(1, partition_num - 1);
113 return ret;
114 }
115
116 return "";
117}
118
119
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800120bool WriteFile(const char* path, const char* data, int data_len) {
121 DirectFileWriter writer;
122 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
123 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700124 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800125 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800126 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800127 return true;
128}
129
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700130bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700131 const char* c_buf = static_cast<const char*>(buf);
132 ssize_t bytes_written = 0;
133 while (bytes_written < static_cast<ssize_t>(count)) {
134 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
135 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
136 bytes_written += rc;
137 }
138 return true;
139}
140
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700141bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
142 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700143 size_t bytes_written = 0;
144 int num_attempts = 0;
145 while (bytes_written < count) {
146 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700147 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
148 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700149 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
150 if (rc < 0) {
151 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
152 << " bytes_written=" << bytes_written
153 << " count=" << count << " offset=" << offset;
154 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700155 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
156 bytes_written += rc;
157 }
158 return true;
159}
160
161bool PReadAll(int fd, void* buf, size_t count, off_t offset,
162 ssize_t* out_bytes_read) {
163 char* c_buf = static_cast<char*>(buf);
164 ssize_t bytes_read = 0;
165 while (bytes_read < static_cast<ssize_t>(count)) {
166 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
167 offset + bytes_read);
168 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
169 if (rc == 0) {
170 break;
171 }
172 bytes_read += rc;
173 }
174 *out_bytes_read = bytes_read;
175 return true;
Darin Petkov296889c2010-07-23 16:20:54 -0700176
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700177}
178
Gilad Arnold19a45f02012-07-19 12:36:10 -0700179// Append |nbytes| of content from |buf| to the vector pointed to by either
180// |vec_p| or |str_p|.
181static void AppendBytes(const char* buf, size_t nbytes,
182 std::vector<char>* vec_p) {
183 CHECK(buf);
184 CHECK(vec_p);
185 vec_p->insert(vec_p->end(), buf, buf + nbytes);
186}
187static void AppendBytes(const char* buf, size_t nbytes,
188 std::string* str_p) {
189 CHECK(buf);
190 CHECK(str_p);
191 str_p->append(buf, nbytes);
192}
193
194// Reads from an open file |fp|, appending the read content to the container
195// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200196// file's content, false otherwise. If |size| is not -1, reads up to |size|
197// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700198template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200199static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700200 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200201 CHECK(size == -1 || size >= 0);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700202 char buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200203 while (size == -1 || size > 0) {
204 off_t bytes_to_read = sizeof(buf);
205 if (size > 0 && bytes_to_read > size) {
206 bytes_to_read = size;
207 }
208 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
209 if (!nbytes) {
210 break;
211 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700212 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200213 if (size != -1) {
214 CHECK(size >= static_cast<off_t>(nbytes));
215 size -= nbytes;
216 }
217 }
218 if (ferror(fp)) {
219 return false;
220 }
221 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700222}
223
Darin Petkov8e447e02013-04-16 16:23:50 +0200224// Opens a file |path| for reading and appends its the contents to a container
225// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
226// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700227template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200228static bool ReadFileChunkAndAppend(const std::string& path,
229 off_t offset,
230 off_t size,
231 T* out_p) {
232 CHECK_GE(offset, 0);
233 CHECK(size == -1 || size >= 0);
234 file_util::ScopedFILE fp(fopen(path.c_str(), "r"));
235 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000236 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200237 if (offset) {
238 // Return success without appending any data if a chunk beyond the end of
239 // the file is requested.
240 if (offset >= FileSize(path)) {
241 return true;
242 }
243 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
244 }
245 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000246}
247
Gilad Arnold19a45f02012-07-19 12:36:10 -0700248// Invokes a pipe |cmd|, then uses |append_func| to append its stdout to a
249// container |out_p|.
250template <class T>
251static bool ReadPipeAndAppend(const std::string& cmd, T* out_p) {
252 FILE* fp = popen(cmd.c_str(), "r");
253 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000254 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200255 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700256 return (success && pclose(fp) >= 0);
257}
258
259
Darin Petkov8e447e02013-04-16 16:23:50 +0200260bool ReadFile(const string& path, vector<char>* out_p) {
261 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700262}
263
Darin Petkov8e447e02013-04-16 16:23:50 +0200264bool ReadFile(const string& path, string* out_p) {
265 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700266}
267
Darin Petkov8e447e02013-04-16 16:23:50 +0200268bool ReadFileChunk(const string& path, off_t offset, off_t size,
269 vector<char>* out_p) {
270 return ReadFileChunkAndAppend(path, offset, size, out_p);
271}
272
273bool ReadPipe(const string& cmd, vector<char>* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700274 return ReadPipeAndAppend(cmd, out_p);
275}
276
Darin Petkov8e447e02013-04-16 16:23:50 +0200277bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700278 return ReadPipeAndAppend(cmd, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000279}
280
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700281off_t FileSize(const string& path) {
282 struct stat stbuf;
283 int rc = stat(path.c_str(), &stbuf);
284 CHECK_EQ(rc, 0);
285 if (rc < 0)
286 return rc;
287 return stbuf.st_size;
288}
289
adlr@google.com3defe6a2009-12-04 20:57:17 +0000290void HexDumpArray(const unsigned char* const arr, const size_t length) {
291 const unsigned char* const char_arr =
292 reinterpret_cast<const unsigned char* const>(arr);
293 LOG(INFO) << "Logging array of length: " << length;
294 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700295 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000296 const unsigned int bytes_remaining = length - i;
297 const unsigned int bytes_per_this_line = min(bytes_per_line,
298 bytes_remaining);
299 char header[100];
300 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
301 TEST_AND_RETURN(r == 13);
302 string line = header;
303 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
304 char buf[20];
305 unsigned char c = char_arr[i + j];
306 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
307 TEST_AND_RETURN(r == 3);
308 line += buf;
309 }
310 LOG(INFO) << line;
311 }
312}
313
314namespace {
315class ScopedDirCloser {
316 public:
317 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
318 ~ScopedDirCloser() {
319 if (dir_ && *dir_) {
320 int r = closedir(*dir_);
321 TEST_AND_RETURN_ERRNO(r == 0);
322 *dir_ = NULL;
323 dir_ = NULL;
324 }
325 }
326 private:
327 DIR** dir_;
328};
329} // namespace {}
330
331bool RecursiveUnlinkDir(const std::string& path) {
332 struct stat stbuf;
333 int r = lstat(path.c_str(), &stbuf);
334 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
335 if ((r < 0) && (errno == ENOENT))
336 // path request is missing. that's fine.
337 return true;
338 if (!S_ISDIR(stbuf.st_mode)) {
339 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700340 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000341 // success or path disappeared before we could unlink.
342 return true;
343 }
344 {
345 // We have a dir, unlink all children, then delete dir
346 DIR *dir = opendir(path.c_str());
347 TEST_AND_RETURN_FALSE_ERRNO(dir);
348 ScopedDirCloser dir_closer(&dir);
349 struct dirent dir_entry;
350 struct dirent *dir_entry_p;
351 int err = 0;
352 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
353 if (dir_entry_p == NULL) {
354 // end of stream reached
355 break;
356 }
357 // Skip . and ..
358 if (!strcmp(dir_entry_p->d_name, ".") ||
359 !strcmp(dir_entry_p->d_name, ".."))
360 continue;
361 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700362 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000363 }
364 TEST_AND_RETURN_FALSE(err == 0);
365 }
366 // unlink dir
367 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
368 return true;
369}
370
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700371string RootDevice(const string& partition_device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700372 FilePath device_path(partition_device);
373 if (device_path.DirName().value() != "/dev") {
374 return "";
375 }
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700376 string::const_iterator it = --partition_device.end();
377 for (; it >= partition_device.begin(); --it) {
378 if (!isdigit(*it))
379 break;
380 }
381 // Some devices contain a p before the partitions. For example:
382 // /dev/mmc0p4 should be shortened to /dev/mmc0.
383 if (*it == 'p')
384 --it;
385 return string(partition_device.begin(), it + 1);
386}
387
388string PartitionNumber(const string& partition_device) {
389 CHECK(!partition_device.empty());
390 string::const_iterator it = --partition_device.end();
391 for (; it >= partition_device.begin(); --it) {
392 if (!isdigit(*it))
393 break;
394 }
395 return string(it + 1, partition_device.end());
396}
397
Darin Petkovf74eb652010-08-04 12:08:38 -0700398string SysfsBlockDevice(const string& device) {
399 FilePath device_path(device);
400 if (device_path.DirName().value() != "/dev") {
401 return "";
402 }
403 return FilePath("/sys/block").Append(device_path.BaseName()).value();
404}
405
406bool IsRemovableDevice(const std::string& device) {
407 string sysfs_block = SysfsBlockDevice(device);
408 string removable;
409 if (sysfs_block.empty() ||
410 !file_util::ReadFileToString(FilePath(sysfs_block).Append("removable"),
411 &removable)) {
412 return false;
413 }
414 TrimWhitespaceASCII(removable, TRIM_ALL, &removable);
415 return removable == "1";
416}
417
adlr@google.com3defe6a2009-12-04 20:57:17 +0000418std::string ErrnoNumberAsString(int err) {
419 char buf[100];
420 buf[0] = '\0';
421 return strerror_r(err, buf, sizeof(buf));
422}
423
424std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
425 string ret;
426 bool last_insert_was_slash = false;
427 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
428 if (*it == '/') {
429 if (last_insert_was_slash)
430 continue;
431 last_insert_was_slash = true;
432 } else {
433 last_insert_was_slash = false;
434 }
435 ret.push_back(*it);
436 }
437 if (strip_trailing_slash && last_insert_was_slash) {
438 string::size_type last_non_slash = ret.find_last_not_of('/');
439 if (last_non_slash != string::npos) {
440 ret.resize(last_non_slash + 1);
441 } else {
442 ret = "";
443 }
444 }
445 return ret;
446}
447
448bool FileExists(const char* path) {
449 struct stat stbuf;
450 return 0 == lstat(path, &stbuf);
451}
452
Darin Petkov30291ed2010-11-12 10:23:06 -0800453bool IsSymlink(const char* path) {
454 struct stat stbuf;
455 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
456}
457
adlr@google.com3defe6a2009-12-04 20:57:17 +0000458std::string TempFilename(string path) {
459 static const string suffix("XXXXXX");
460 CHECK(StringHasSuffix(path, suffix));
461 do {
462 string new_suffix;
463 for (unsigned int i = 0; i < suffix.size(); i++) {
464 int r = rand() % (26 * 2 + 10); // [a-zA-Z0-9]
465 if (r < 26)
466 new_suffix.append(1, 'a' + r);
467 else if (r < (26 * 2))
468 new_suffix.append(1, 'A' + r - 26);
469 else
470 new_suffix.append(1, '0' + r - (26 * 2));
471 }
472 CHECK_EQ(new_suffix.size(), suffix.size());
473 path.resize(path.size() - new_suffix.size());
474 path.append(new_suffix);
475 } while (FileExists(path.c_str()));
476 return path;
477}
478
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700479bool MakeTempFile(const std::string& filename_template,
480 std::string* filename,
481 int* fd) {
482 DCHECK(filename || fd);
483 vector<char> buf(filename_template.size() + 1);
484 memcpy(&buf[0], filename_template.data(), filename_template.size());
485 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700486
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700487 int mkstemp_fd = mkstemp(&buf[0]);
488 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
489 if (filename) {
490 *filename = &buf[0];
491 }
492 if (fd) {
493 *fd = mkstemp_fd;
494 } else {
495 close(mkstemp_fd);
496 }
497 return true;
498}
499
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700500bool MakeTempDirectory(const std::string& dirname_template,
501 std::string* dirname) {
502 DCHECK(dirname);
503 vector<char> buf(dirname_template.size() + 1);
504 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
505 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700506
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700507 char* return_code = mkdtemp(&buf[0]);
508 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
509 *dirname = &buf[0];
510 return true;
511}
512
adlr@google.com3defe6a2009-12-04 20:57:17 +0000513bool StringHasSuffix(const std::string& str, const std::string& suffix) {
514 if (suffix.size() > str.size())
515 return false;
516 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
517}
518
519bool StringHasPrefix(const std::string& str, const std::string& prefix) {
520 if (prefix.size() > str.size())
521 return false;
522 return 0 == str.compare(0, prefix.size(), prefix);
523}
524
adlr@google.com3defe6a2009-12-04 20:57:17 +0000525bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700526 const string& mountpoint,
527 unsigned long mountflags) {
528 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000529 if (rc < 0) {
530 string msg = ErrnoNumberAsString(errno);
531 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
532 << device << " on " << mountpoint;
533 return false;
534 }
535 return true;
536}
537
538bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700539 for (int num_retries = 0; ; ++num_retries) {
540 if (umount(mountpoint.c_str()) == 0)
541 break;
542
543 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
544 num_retries < kUnmountMaxNumOfRetries);
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800545 g_usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700546 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000547 return true;
548}
549
Darin Petkovd3f8c892010-10-12 21:38:45 -0700550bool GetFilesystemSize(const std::string& device,
551 int* out_block_count,
552 int* out_block_size) {
553 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
554 TEST_AND_RETURN_FALSE(fd >= 0);
555 ScopedFdCloser fd_closer(&fd);
556 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
557}
558
559bool GetFilesystemSizeFromFD(int fd,
560 int* out_block_count,
561 int* out_block_size) {
562 TEST_AND_RETURN_FALSE(fd >= 0);
563
564 // Determine the ext3 filesystem size by directly reading the block count and
565 // block size information from the superblock. See include/linux/ext3_fs.h for
566 // more details on the structure.
567 ssize_t kBufferSize = 16 * sizeof(uint32_t);
568 char buffer[kBufferSize];
569 const int kSuperblockOffset = 1024;
570 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
571 kBufferSize) {
572 PLOG(ERROR) << "Unable to determine file system size:";
573 return false;
574 }
575 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
576 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
577 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
578 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
579 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
580 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
581 block_count = le32toh(block_count);
582 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
583 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
584 magic = le16toh(magic);
585
586 // Sanity check the parameters.
587 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
588 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
589 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
590 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
591 int block_size = 1 << log_block_size;
592 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
593 block_size <= kExt3MaxBlockSize);
594 TEST_AND_RETURN_FALSE(block_count > 0);
595
596 if (out_block_count) {
597 *out_block_count = block_count;
598 }
599 if (out_block_size) {
600 *out_block_size = block_size;
601 }
602 return true;
603}
604
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700605bool GetBootloader(BootLoader* out_bootloader) {
606 // For now, hardcode to syslinux.
607 *out_bootloader = BootLoader_SYSLINUX;
608 return true;
609}
610
Darin Petkova0b9e772011-10-06 05:05:56 -0700611string GetAndFreeGError(GError** error) {
612 if (!*error) {
613 return "Unknown GLib error.";
614 }
615 string message =
616 base::StringPrintf("GError(%d): %s",
617 (*error)->code,
618 (*error)->message ? (*error)->message : "(unknown)");
619 g_error_free(*error);
620 *error = NULL;
621 return message;
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700622}
623
Darin Petkov296889c2010-07-23 16:20:54 -0700624bool Reboot() {
625 vector<string> command;
626 command.push_back("/sbin/shutdown");
627 command.push_back("-r");
628 command.push_back("now");
629 int rc = 0;
Darin Petkov85d02b72011-05-17 13:25:51 -0700630 Subprocess::SynchronousExec(command, &rc, NULL);
Darin Petkov296889c2010-07-23 16:20:54 -0700631 TEST_AND_RETURN_FALSE(rc == 0);
632 return true;
633}
634
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800635namespace {
636// Do the actual trigger. We do it as a main-loop callback to (try to) get a
637// consistent stack trace.
638gboolean TriggerCrashReporterUpload(void* unused) {
639 pid_t pid = fork();
640 CHECK(pid >= 0) << "fork failed"; // fork() failed. Something is very wrong.
641 if (pid == 0) {
642 // We are the child. Crash.
643 abort(); // never returns
644 }
645 // We are the parent. Wait for child to terminate.
646 pid_t result = waitpid(pid, NULL, 0);
647 LOG_IF(ERROR, result < 0) << "waitpid() failed";
648 return FALSE; // Don't call this callback again
649}
650} // namespace {}
651
652void ScheduleCrashReporterUpload() {
653 g_idle_add(&TriggerCrashReporterUpload, NULL);
654}
655
Chris Sosa4f8ee272012-11-30 13:01:54 -0800656bool SetCpuShares(CpuShares shares) {
657 string string_shares = base::IntToString(static_cast<int>(shares));
658 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
659 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
660 if(utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
661 string_shares.size())){
662 return true;
663 } else {
664 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
665 << " using " << cpu_shares_file;
666 return false;
667 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700668}
669
Chris Sosa4f8ee272012-11-30 13:01:54 -0800670int CompareCpuShares(CpuShares shares_lhs,
671 CpuShares shares_rhs) {
672 return static_cast<int>(shares_lhs) - static_cast<int>(shares_rhs);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700673}
674
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700675int FuzzInt(int value, unsigned int range) {
676 int min = value - range / 2;
677 int max = value + range - range / 2;
678 return base::RandInt(min, max);
679}
680
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800681gboolean GlibRunClosure(gpointer data) {
682 google::protobuf::Closure* callback =
683 reinterpret_cast<google::protobuf::Closure*>(data);
684 callback->Run();
685 return FALSE;
686}
687
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700688string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800689 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700690}
691
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800692string FormatTimeDelta(TimeDelta delta) {
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700693 // Canonicalize into days, hours, minutes, seconds and microseconds.
694 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800695 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700696 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800697 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700698 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800699 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700700 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800701 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700702 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800703
704 // Construct and return string.
705 string str;
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700706 if (days)
707 base::StringAppendF(&str, "%ud", days);
708 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800709 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700710 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800711 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700712 base::StringAppendF(&str, "%u", secs);
713 if (usecs) {
714 int width = 6;
715 while ((usecs / 10) * 10 == usecs) {
716 usecs /= 10;
717 width--;
718 }
719 base::StringAppendF(&str, ".%0*u", width, usecs);
720 }
721 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800722 return str;
723}
724
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700725string ToString(const Time utc_time) {
726 Time::Exploded exp_time;
727 utc_time.UTCExplode(&exp_time);
728 return StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
729 exp_time.month,
730 exp_time.day_of_month,
731 exp_time.year,
732 exp_time.hour,
733 exp_time.minute,
734 exp_time.second);
735}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000736
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700737string ToString(bool b) {
738 return (b ? "true" : "false");
739}
740
Alex Deymo1c656c42013-06-28 11:02:14 -0700741string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700742 switch (source) {
743 case kDownloadSourceHttpsServer: return "HttpsServer";
744 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700745 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -0700746 case kNumDownloadSources: return "Unknown";
747 // Don't add a default case to let the compiler warn about newly added
748 // download sources which should be added here.
749 }
750
751 return "Unknown";
752}
753
Alex Deymo1c656c42013-06-28 11:02:14 -0700754string ToString(PayloadType payload_type) {
755 switch (payload_type) {
756 case kPayloadTypeDelta: return "Delta";
757 case kPayloadTypeFull: return "Full";
758 case kPayloadTypeForcedFull: return "ForcedFull";
759 case kNumPayloadTypes: return "Unknown";
760 // Don't add a default case to let the compiler warn about newly added
761 // payload types which should be added here.
762 }
763
764 return "Unknown";
765}
766
David Zeuthena99981f2013-04-29 13:42:47 -0700767ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700768 // Ignore the higher order bits in the code by applying the mask as
769 // we want the enumerations to be in the small contiguous range
David Zeuthena99981f2013-04-29 13:42:47 -0700770 // with values less than kErrorCodeUmaReportedMax.
771 ErrorCode base_code = static_cast<ErrorCode>(code & ~kErrorCodeSpecialFlags);
Jay Srinivasanf0572052012-10-23 18:12:56 -0700772
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800773 // Make additional adjustments required for UMA and error classification.
774 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
775 // chromium-os:34369.
David Zeuthena99981f2013-04-29 13:42:47 -0700776 if (base_code >= kErrorCodeOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700777 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800778 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800779 LOG(INFO) << "Converting error code " << base_code
David Zeuthena99981f2013-04-29 13:42:47 -0700780 << " to kErrorCodeOmahaErrorInHTTPResponse";
781 base_code = kErrorCodeOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700782 }
783
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800784 return base_code;
785}
786
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800787// Returns a printable version of the various flags denoted in the higher order
788// bits of the given code. Returns an empty string if none of those bits are
789// set.
790string GetFlagNames(uint32_t code) {
David Zeuthena99981f2013-04-29 13:42:47 -0700791 uint32_t flags = code & kErrorCodeSpecialFlags;
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800792 string flag_names;
793 string separator = "";
794 for(size_t i = 0; i < sizeof(flags) * 8; i++) {
795 uint32_t flag = flags & (1 << i);
796 if (flag) {
David Zeuthena99981f2013-04-29 13:42:47 -0700797 flag_names += separator + CodeToString(static_cast<ErrorCode>(flag));
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800798 separator = ", ";
799 }
800 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800801
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800802 return flag_names;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700803}
804
David Zeuthena99981f2013-04-29 13:42:47 -0700805void SendErrorCodeToUma(SystemState* system_state, ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800806 if (!system_state)
807 return;
808
David Zeuthena99981f2013-04-29 13:42:47 -0700809 ErrorCode uma_error_code = GetBaseErrorCode(code);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800810
811 // If the code doesn't have flags computed already, compute them now based on
812 // the state of the current update attempt.
David Zeuthena99981f2013-04-29 13:42:47 -0700813 uint32_t flags = code & kErrorCodeSpecialFlags;
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800814 if (!flags)
815 flags = system_state->update_attempter()->GetErrorCodeFlags();
816
817 // Determine the UMA bucket depending on the flags. But, ignore the resumed
818 // flag, as it's perfectly normal for production devices to resume their
819 // downloads and so we want to record those cases also in NormalErrorCodes
820 // bucket.
David Zeuthena99981f2013-04-29 13:42:47 -0700821 string metric = (flags & ~kErrorCodeResumedFlag) ?
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800822 "Installer.DevModeErrorCodes" : "Installer.NormalErrorCodes";
823
824 LOG(INFO) << "Sending error code " << uma_error_code
825 << " (" << CodeToString(uma_error_code) << ")"
826 << " to UMA metric: " << metric
827 << ". Flags = " << (flags ? GetFlagNames(flags) : "None");
828
829 system_state->metrics_lib()->SendEnumToUMA(metric,
830 uma_error_code,
David Zeuthena99981f2013-04-29 13:42:47 -0700831 kErrorCodeUmaReportedMax);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800832}
833
David Zeuthena99981f2013-04-29 13:42:47 -0700834string CodeToString(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800835 // If the given code has both parts (i.e. the error code part and the flags
836 // part) then strip off the flags part since the switch statement below
837 // has case statements only for the base error code or a single flag but
838 // doesn't support any combinations of those.
David Zeuthena99981f2013-04-29 13:42:47 -0700839 if ((code & kErrorCodeSpecialFlags) && (code & ~kErrorCodeSpecialFlags))
840 code = static_cast<ErrorCode>(code & ~kErrorCodeSpecialFlags);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800841 switch (code) {
David Zeuthena99981f2013-04-29 13:42:47 -0700842 case kErrorCodeSuccess: return "kErrorCodeSuccess";
843 case kErrorCodeError: return "kErrorCodeError";
844 case kErrorCodeOmahaRequestError: return "kErrorCodeOmahaRequestError";
845 case kErrorCodeOmahaResponseHandlerError:
846 return "kErrorCodeOmahaResponseHandlerError";
847 case kErrorCodeFilesystemCopierError:
848 return "kErrorCodeFilesystemCopierError";
849 case kErrorCodePostinstallRunnerError:
850 return "kErrorCodePostinstallRunnerError";
Gilad Arnold21504f02013-05-24 08:51:22 -0700851 case kErrorCodePayloadMismatchedType:
852 return "kErrorCodePayloadMismatchedType";
David Zeuthena99981f2013-04-29 13:42:47 -0700853 case kErrorCodeInstallDeviceOpenError:
854 return "kErrorCodeInstallDeviceOpenError";
855 case kErrorCodeKernelDeviceOpenError:
856 return "kErrorCodeKernelDeviceOpenError";
857 case kErrorCodeDownloadTransferError:
858 return "kErrorCodeDownloadTransferError";
859 case kErrorCodePayloadHashMismatchError:
860 return "kErrorCodePayloadHashMismatchError";
861 case kErrorCodePayloadSizeMismatchError:
862 return "kErrorCodePayloadSizeMismatchError";
863 case kErrorCodeDownloadPayloadVerificationError:
864 return "kErrorCodeDownloadPayloadVerificationError";
865 case kErrorCodeDownloadNewPartitionInfoError:
866 return "kErrorCodeDownloadNewPartitionInfoError";
867 case kErrorCodeDownloadWriteError:
868 return "kErrorCodeDownloadWriteError";
869 case kErrorCodeNewRootfsVerificationError:
870 return "kErrorCodeNewRootfsVerificationError";
871 case kErrorCodeNewKernelVerificationError:
872 return "kErrorCodeNewKernelVerificationError";
873 case kErrorCodeSignedDeltaPayloadExpectedError:
874 return "kErrorCodeSignedDeltaPayloadExpectedError";
875 case kErrorCodeDownloadPayloadPubKeyVerificationError:
876 return "kErrorCodeDownloadPayloadPubKeyVerificationError";
877 case kErrorCodePostinstallBootedFromFirmwareB:
878 return "kErrorCodePostinstallBootedFromFirmwareB";
879 case kErrorCodeDownloadStateInitializationError:
880 return "kErrorCodeDownloadStateInitializationError";
881 case kErrorCodeDownloadInvalidMetadataMagicString:
882 return "kErrorCodeDownloadInvalidMetadataMagicString";
883 case kErrorCodeDownloadSignatureMissingInManifest:
884 return "kErrorCodeDownloadSignatureMissingInManifest";
885 case kErrorCodeDownloadManifestParseError:
886 return "kErrorCodeDownloadManifestParseError";
887 case kErrorCodeDownloadMetadataSignatureError:
888 return "kErrorCodeDownloadMetadataSignatureError";
889 case kErrorCodeDownloadMetadataSignatureVerificationError:
890 return "kErrorCodeDownloadMetadataSignatureVerificationError";
891 case kErrorCodeDownloadMetadataSignatureMismatch:
892 return "kErrorCodeDownloadMetadataSignatureMismatch";
893 case kErrorCodeDownloadOperationHashVerificationError:
894 return "kErrorCodeDownloadOperationHashVerificationError";
895 case kErrorCodeDownloadOperationExecutionError:
896 return "kErrorCodeDownloadOperationExecutionError";
897 case kErrorCodeDownloadOperationHashMismatch:
898 return "kErrorCodeDownloadOperationHashMismatch";
899 case kErrorCodeOmahaRequestEmptyResponseError:
900 return "kErrorCodeOmahaRequestEmptyResponseError";
901 case kErrorCodeOmahaRequestXMLParseError:
902 return "kErrorCodeOmahaRequestXMLParseError";
903 case kErrorCodeDownloadInvalidMetadataSize:
904 return "kErrorCodeDownloadInvalidMetadataSize";
905 case kErrorCodeDownloadInvalidMetadataSignature:
906 return "kErrorCodeDownloadInvalidMetadataSignature";
907 case kErrorCodeOmahaResponseInvalid:
908 return "kErrorCodeOmahaResponseInvalid";
909 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
910 return "kErrorCodeOmahaUpdateIgnoredPerPolicy";
911 case kErrorCodeOmahaUpdateDeferredPerPolicy:
912 return "kErrorCodeOmahaUpdateDeferredPerPolicy";
913 case kErrorCodeOmahaErrorInHTTPResponse:
914 return "kErrorCodeOmahaErrorInHTTPResponse";
915 case kErrorCodeDownloadOperationHashMissingError:
916 return "kErrorCodeDownloadOperationHashMissingError";
917 case kErrorCodeDownloadMetadataSignatureMissingError:
918 return "kErrorCodeDownloadMetadataSignatureMissingError";
919 case kErrorCodeOmahaUpdateDeferredForBackoff:
920 return "kErrorCodeOmahaUpdateDeferredForBackoff";
921 case kErrorCodePostinstallPowerwashError:
922 return "kErrorCodePostinstallPowerwashError";
923 case kErrorCodeUpdateCanceledByChannelChange:
924 return "kErrorCodeUpdateCanceledByChannelChange";
925 case kErrorCodeUmaReportedMax:
926 return "kErrorCodeUmaReportedMax";
927 case kErrorCodeOmahaRequestHTTPResponseBase:
928 return "kErrorCodeOmahaRequestHTTPResponseBase";
929 case kErrorCodeResumedFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800930 return "Resumed";
David Zeuthena99981f2013-04-29 13:42:47 -0700931 case kErrorCodeDevModeFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800932 return "DevMode";
David Zeuthena99981f2013-04-29 13:42:47 -0700933 case kErrorCodeTestImageFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800934 return "TestImage";
David Zeuthena99981f2013-04-29 13:42:47 -0700935 case kErrorCodeTestOmahaUrlFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800936 return "TestOmahaUrl";
David Zeuthena99981f2013-04-29 13:42:47 -0700937 case kErrorCodeSpecialFlags:
938 return "kErrorCodeSpecialFlags";
Don Garrett81018e02013-07-30 18:46:31 -0700939 case kErrorCodePostinstallFirmwareRONotUpdatable:
940 return "kErrorCodePostinstallFirmwareRONotUpdatable";
Don Garrett4d039442013-10-28 18:40:06 -0700941 case kErrorCodeUnsupportedMajorPayloadVersion:
942 return "kErrorCodeUnsupportedMajorPayloadVersion";
943 case kErrorCodeUnsupportedMinorPayloadVersion:
944 return "kErrorCodeUnsupportedMinorPayloadVersion";
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800945 // Don't add a default case to let the compiler warn about newly added
946 // error codes which should be added here.
947 }
948
949 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
950}
Jay Srinivasanf0572052012-10-23 18:12:56 -0700951
Gilad Arnold30dedd82013-07-03 06:19:09 -0700952bool CreatePowerwashMarkerFile(const char* file_path) {
953 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
954 bool result = utils::WriteFile(marker_file,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700955 kPowerwashCommand,
956 strlen(kPowerwashCommand));
Gilad Arnold30dedd82013-07-03 06:19:09 -0700957 if (result) {
958 LOG(INFO) << "Created " << marker_file << " to powerwash on next reboot";
959 } else {
960 PLOG(ERROR) << "Error in creating powerwash marker file: " << marker_file;
961 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700962
963 return result;
964}
965
Gilad Arnold30dedd82013-07-03 06:19:09 -0700966bool DeletePowerwashMarkerFile(const char* file_path) {
967 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
968 const FilePath kPowerwashMarkerPath(marker_file);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700969 bool result = file_util::Delete(kPowerwashMarkerPath, false);
970
971 if (result)
972 LOG(INFO) << "Successfully deleted the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -0700973 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700974 else
975 PLOG(ERROR) << "Could not delete the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -0700976 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700977
978 return result;
979}
980
Chris Sosad317e402013-06-12 13:47:09 -0700981bool GetInstallDev(const std::string& boot_dev, std::string* install_dev) {
982 TEST_AND_RETURN_FALSE(StringHasPrefix(boot_dev, "/dev/"));
Liam McLoughlin049d1652013-07-31 18:47:46 -0700983 string::iterator it;
984 string ubiblock_prefix("/dev/ubiblock");
985
986 install_dev->assign(boot_dev);
987
988 if(StringHasPrefix(boot_dev, ubiblock_prefix)) {
989 // UBI-based device
990 it = install_dev->begin() + ubiblock_prefix.length();
991 } else {
992 // non-UBI device
993 it = install_dev->end() - 1; // last character in string
994 }
995
Chris Sosad317e402013-06-12 13:47:09 -0700996 // Right now, we just switch '3' and '5' partition numbers.
Liam McLoughlin049d1652013-07-31 18:47:46 -0700997 TEST_AND_RETURN_FALSE(*it == '3' || *it == '5');
998 *it = (*it == '3' ? '5' : '3');
999
Chris Sosad317e402013-06-12 13:47:09 -07001000 return true;
1001}
1002
David Zeuthen27a48bc2013-08-06 12:06:29 -07001003Time TimeFromStructTimespec(struct timespec *ts) {
1004 int64 us = static_cast<int64>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
1005 static_cast<int64>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
1006 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
1007}
1008
1009gchar** StringVectorToGStrv(const vector<string> &vector) {
1010 GPtrArray *p = g_ptr_array_new();
1011 for (std::vector<string>::const_iterator i = vector.begin();
1012 i != vector.end(); ++i) {
1013 g_ptr_array_add(p, g_strdup(i->c_str()));
1014 }
1015 g_ptr_array_add(p, NULL);
1016 return reinterpret_cast<gchar**>(g_ptr_array_free(p, FALSE));
1017}
1018
1019string StringVectorToString(const vector<string> &vector) {
1020 string str = "[";
1021 for (std::vector<string>::const_iterator i = vector.begin();
1022 i != vector.end(); ++i) {
1023 if (i != vector.begin())
1024 str += ", ";
1025 str += '"';
1026 str += *i;
1027 str += '"';
1028 }
1029 str += "]";
1030 return str;
1031}
1032
David Zeuthen8f191b22013-08-06 12:27:50 -07001033string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
1034 string encoded_hash;
1035 OmahaHashCalculator::Base64Encode(payload_hash.c_str(),
1036 payload_hash.size(),
1037 &encoded_hash);
1038 return StringPrintf("cros_update_size_%zu_hash_%s",
1039 payload_size,
1040 encoded_hash.c_str());
1041}
1042
David Zeuthen910ec5b2013-09-26 12:10:58 -07001043bool IsXAttrSupported(const base::FilePath& dir_path) {
1044 char *path = strdup(dir_path.Append("xattr_test_XXXXXX").value().c_str());
1045
1046 int fd = mkstemp(path);
1047 if (fd == -1) {
1048 PLOG(ERROR) << "Error creating temporary file in " << dir_path.value();
1049 free(path);
1050 return false;
1051 }
1052
1053 if (unlink(path) != 0) {
1054 PLOG(ERROR) << "Error unlinking temporary file " << path;
1055 close(fd);
1056 free(path);
1057 return false;
1058 }
1059
1060 int xattr_res = fsetxattr(fd, "user.xattr-test", "value", strlen("value"), 0);
1061 if (xattr_res != 0) {
1062 if (errno == ENOTSUP) {
1063 // Leave it to call-sites to warn about non-support.
1064 } else {
1065 PLOG(ERROR) << "Error setting xattr on " << path;
1066 }
1067 }
1068 close(fd);
1069 free(path);
1070 return xattr_res == 0;
1071}
1072
David Zeuthene7f89172013-10-31 10:21:04 -07001073bool DecodeAndStoreBase64String(const std::string& base64_encoded,
1074 base::FilePath *out_path) {
1075 vector<char> contents;
1076
1077 out_path->clear();
1078
1079 if (base64_encoded.size() == 0) {
1080 LOG(ERROR) << "Can't decode empty string.";
1081 return false;
1082 }
1083
1084 if (!OmahaHashCalculator::Base64Decode(base64_encoded, &contents) ||
1085 contents.size() == 0) {
1086 LOG(ERROR) << "Error decoding base64.";
1087 return false;
1088 }
1089
1090 FILE *file = file_util::CreateAndOpenTemporaryFile(out_path);
1091 if (file == NULL) {
1092 LOG(ERROR) << "Error creating temporary file.";
1093 return false;
1094 }
1095
1096 if (fwrite(&contents[0], 1, contents.size(), file) != contents.size()) {
1097 PLOG(ERROR) << "Error writing to temporary file.";
1098 if (fclose(file) != 0)
1099 PLOG(ERROR) << "Error closing temporary file.";
1100 if (unlink(out_path->value().c_str()) != 0)
1101 PLOG(ERROR) << "Error unlinking temporary file.";
1102 out_path->clear();
1103 return false;
1104 }
1105
1106 if (fclose(file) != 0) {
1107 PLOG(ERROR) << "Error closing temporary file.";
1108 out_path->clear();
1109 return false;
1110 }
1111
1112 return true;
1113}
1114
adlr@google.com3defe6a2009-12-04 20:57:17 +00001115} // namespace utils
1116
1117} // namespace chromeos_update_engine