blob: 0cde048a24a6908673bbe790c56946635362d8f0 [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
Alex Vakulenko75039d72014-03-25 12:36:28 -070024#include <base/files/file_path.h>
Will Drewry8f71da82010-08-30 14:07:11 -050025#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>
Alex Vakulenko75039d72014-03-25 12:36:28 -070029#include <base/strings/string_number_conversions.h>
30#include <base/strings/string_split.h>
31#include <base/strings/string_util.h>
32#include <base/strings/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
David Zeuthen33bae492014-02-25 16:16:18 -080036#include "update_engine/clock_interface.h"
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070037#include "update_engine/constants.h"
Andrew de los Reyes970bb282009-12-09 16:34:04 -080038#include "update_engine/file_writer.h"
Darin Petkov33d30642010-08-04 10:18:57 -070039#include "update_engine/omaha_request_params.h"
David Zeuthen33bae492014-02-25 16:16:18 -080040#include "update_engine/prefs_interface.h"
Darin Petkov296889c2010-07-23 16:20:54 -070041#include "update_engine/subprocess.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080042#include "update_engine/system_state.h"
43#include "update_engine/update_attempter.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000044
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070045using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080046using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000047using std::min;
Chris Sosac1972482013-04-30 22:31:10 -070048using std::pair;
adlr@google.com3defe6a2009-12-04 20:57:17 +000049using std::string;
50using std::vector;
51
52namespace chromeos_update_engine {
53
Ben Chan77a1eba2012-10-07 22:54:55 -070054namespace {
55
56// The following constants control how UnmountFilesystem should retry if
57// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
58// one second.
59const int kUnmountMaxNumOfRetries = 5;
60const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Alex Deymo032e7722014-03-25 17:53:56 -070061
62// Number of bytes to read from a file to attempt to detect its contents. Used
63// in GetFileFormat.
64const int kGetFileFormatMaxHeaderSize = 32;
65
Ben Chan77a1eba2012-10-07 22:54:55 -070066} // namespace
67
adlr@google.com3defe6a2009-12-04 20:57:17 +000068namespace utils {
69
Chris Sosa4f8ee272012-11-30 13:01:54 -080070// Cgroup container is created in update-engine's upstart script located at
71// /etc/init/update-engine.conf.
72static const char kCGroupDir[] = "/sys/fs/cgroup/cpu/update-engine";
73
J. Richard Barnette63137e52013-10-28 10:57:29 -070074string ParseECVersion(string input_line) {
75 TrimWhitespaceASCII(input_line, TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -070076
Alex Vakulenko75039d72014-03-25 12:36:28 -070077 // At this point we want to convert the format key=value pair from mosys to
Chris Sosac1972482013-04-30 22:31:10 -070078 // a vector of key value pairs.
79 vector<pair<string, string> > kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -070080 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Chris Sosac1972482013-04-30 22:31:10 -070081 for (vector<pair<string, string> >::iterator it = kv_pairs.begin();
82 it != kv_pairs.end(); ++it) {
83 // Finally match against the fw_verion which may have quotes.
84 if (it->first == "fw_version") {
85 string output;
86 // Trim any quotes.
Alex Vakulenko75039d72014-03-25 12:36:28 -070087 base::TrimString(it->second, "\"", &output);
Chris Sosac1972482013-04-30 22:31:10 -070088 return output;
89 }
90 }
91 }
92 LOG(ERROR) << "Unable to parse fwid from ec info.";
93 return "";
94}
95
96
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -070097const string KernelDeviceOfBootDevice(const string& boot_device) {
98 string kernel_partition_name;
J. Richard Barnette30842932013-10-28 15:04:23 -070099
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700100 string disk_name;
101 int partition_num;
102 if (SplitPartitionName(boot_device, &disk_name, &partition_num)) {
103 if (disk_name == "/dev/ubiblock") {
104 // Special case for NAND devices.
105 // eg: /dev/ubiblock3_0 becomes /dev/mtdblock2
106 disk_name = "/dev/mtdblock";
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 kernel_partition_name = MakePartitionName(disk_name, partition_num - 1);
113 }
J. Richard Barnette30842932013-10-28 15:04:23 -0700114 }
115
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700116 return kernel_partition_name;
J. Richard Barnette30842932013-10-28 15:04:23 -0700117}
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
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800371std::string GetDiskName(const string& partition_name) {
372 std::string disk_name;
373 return SplitPartitionName(partition_name, &disk_name, nullptr) ?
374 disk_name : std::string();
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700375}
376
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800377int GetPartitionNumber(const std::string& partition_name) {
378 int partition_num = 0;
379 return SplitPartitionName(partition_name, nullptr, &partition_num) ?
380 partition_num : 0;
381}
382
383bool SplitPartitionName(const std::string& partition_name,
384 std::string* out_disk_name,
385 int* out_partition_num) {
386 if (!StringHasPrefix(partition_name, "/dev/")) {
387 LOG(ERROR) << "Invalid partition device name: " << partition_name;
388 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700389 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800390
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700391 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
392 if (last_nondigit_pos == string::npos ||
393 (last_nondigit_pos + 1) == partition_name.size()) {
394 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800395 return false;
396 }
397
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700398 size_t partition_name_len = std::string::npos;
399 if (partition_name[last_nondigit_pos] == '_') {
400 // NAND block devices have weird naming which could be something
401 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
402 size_t prev_nondigit_pos =
403 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
404 if (prev_nondigit_pos == string::npos ||
405 (prev_nondigit_pos + 1) == last_nondigit_pos) {
406 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
407 return false;
408 }
409
410 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
411 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800412 }
413
414 if (out_disk_name) {
415 // Special case for MMC devices which have the following naming scheme:
416 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700417 size_t disk_name_len = last_nondigit_pos;
418 if (partition_name[last_nondigit_pos] != 'p' ||
419 last_nondigit_pos == 0 ||
420 !isdigit(partition_name[last_nondigit_pos - 1])) {
421 disk_name_len++;
422 }
423 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800424 }
425
426 if (out_partition_num) {
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700427 std::string partition_str = partition_name.substr(last_nondigit_pos + 1,
428 partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800429 *out_partition_num = atoi(partition_str.c_str());
430 }
431 return true;
432}
433
434std::string MakePartitionName(const std::string& disk_name,
435 int partition_num) {
436 if (!StringHasPrefix(disk_name, "/dev/")) {
437 LOG(ERROR) << "Invalid disk name: " << disk_name;
438 return std::string();
439 }
440
441 if (partition_num < 1) {
442 LOG(ERROR) << "Invalid partition number: " << partition_num;
443 return std::string();
444 }
445
446 std::string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700447 if (isdigit(partition_name.back())) {
448 // Special case for devices with names ending with a digit.
449 // Add "p" to separate the disk name from partition number,
450 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800451 partition_name += 'p';
452 }
453
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700454 partition_name += std::to_string(partition_num);
455
456 if (StringHasPrefix(partition_name, "/dev/ubiblock")) {
457 // Special case for UBI block devieces that have "_0" suffix.
458 partition_name += "_0";
459 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800460 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700461}
462
Darin Petkovf74eb652010-08-04 12:08:38 -0700463string SysfsBlockDevice(const string& device) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700464 base::FilePath device_path(device);
Darin Petkovf74eb652010-08-04 12:08:38 -0700465 if (device_path.DirName().value() != "/dev") {
466 return "";
467 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700468 return base::FilePath("/sys/block").Append(device_path.BaseName()).value();
Darin Petkovf74eb652010-08-04 12:08:38 -0700469}
470
471bool IsRemovableDevice(const std::string& device) {
472 string sysfs_block = SysfsBlockDevice(device);
473 string removable;
474 if (sysfs_block.empty() ||
Alex Vakulenko75039d72014-03-25 12:36:28 -0700475 !base::ReadFileToString(base::FilePath(sysfs_block).Append("removable"),
Darin Petkovf74eb652010-08-04 12:08:38 -0700476 &removable)) {
477 return false;
478 }
479 TrimWhitespaceASCII(removable, TRIM_ALL, &removable);
480 return removable == "1";
481}
482
adlr@google.com3defe6a2009-12-04 20:57:17 +0000483std::string ErrnoNumberAsString(int err) {
484 char buf[100];
485 buf[0] = '\0';
486 return strerror_r(err, buf, sizeof(buf));
487}
488
489std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
490 string ret;
491 bool last_insert_was_slash = false;
492 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
493 if (*it == '/') {
494 if (last_insert_was_slash)
495 continue;
496 last_insert_was_slash = true;
497 } else {
498 last_insert_was_slash = false;
499 }
500 ret.push_back(*it);
501 }
502 if (strip_trailing_slash && last_insert_was_slash) {
503 string::size_type last_non_slash = ret.find_last_not_of('/');
504 if (last_non_slash != string::npos) {
505 ret.resize(last_non_slash + 1);
506 } else {
507 ret = "";
508 }
509 }
510 return ret;
511}
512
513bool FileExists(const char* path) {
514 struct stat stbuf;
515 return 0 == lstat(path, &stbuf);
516}
517
Darin Petkov30291ed2010-11-12 10:23:06 -0800518bool IsSymlink(const char* path) {
519 struct stat stbuf;
520 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
521}
522
adlr@google.com3defe6a2009-12-04 20:57:17 +0000523std::string TempFilename(string path) {
524 static const string suffix("XXXXXX");
525 CHECK(StringHasSuffix(path, suffix));
526 do {
527 string new_suffix;
528 for (unsigned int i = 0; i < suffix.size(); i++) {
529 int r = rand() % (26 * 2 + 10); // [a-zA-Z0-9]
530 if (r < 26)
531 new_suffix.append(1, 'a' + r);
532 else if (r < (26 * 2))
533 new_suffix.append(1, 'A' + r - 26);
534 else
535 new_suffix.append(1, '0' + r - (26 * 2));
536 }
537 CHECK_EQ(new_suffix.size(), suffix.size());
538 path.resize(path.size() - new_suffix.size());
539 path.append(new_suffix);
540 } while (FileExists(path.c_str()));
541 return path;
542}
543
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800544// If |path| is absolute, or explicit relative to the current working directory,
545// leaves it as is. Otherwise, if TMPDIR is defined in the environment and is
546// non-empty, prepends it to |path|. Otherwise, prepends /tmp. Returns the
547// resulting path.
548static const string PrependTmpdir(const string& path) {
549 if (path[0] == '/' || StartsWithASCII(path, "./", true) ||
550 StartsWithASCII(path, "../", true))
551 return path;
552
553 const char *tmpdir = getenv("TMPDIR");
554 const string prefix = (tmpdir && *tmpdir ? tmpdir : "/tmp");
555 return prefix + "/" + path;
556}
557
558bool MakeTempFile(const std::string& base_filename_template,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700559 std::string* filename,
560 int* fd) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800561 const string filename_template = PrependTmpdir(base_filename_template);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700562 DCHECK(filename || fd);
563 vector<char> buf(filename_template.size() + 1);
564 memcpy(&buf[0], filename_template.data(), filename_template.size());
565 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700566
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700567 int mkstemp_fd = mkstemp(&buf[0]);
568 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
569 if (filename) {
570 *filename = &buf[0];
571 }
572 if (fd) {
573 *fd = mkstemp_fd;
574 } else {
575 close(mkstemp_fd);
576 }
577 return true;
578}
579
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800580bool MakeTempDirectory(const std::string& base_dirname_template,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700581 std::string* dirname) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800582 const string dirname_template = PrependTmpdir(base_dirname_template);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700583 DCHECK(dirname);
584 vector<char> buf(dirname_template.size() + 1);
585 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
586 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700587
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700588 char* return_code = mkdtemp(&buf[0]);
589 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
590 *dirname = &buf[0];
591 return true;
592}
593
adlr@google.com3defe6a2009-12-04 20:57:17 +0000594bool StringHasSuffix(const std::string& str, const std::string& suffix) {
595 if (suffix.size() > str.size())
596 return false;
597 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
598}
599
600bool StringHasPrefix(const std::string& str, const std::string& prefix) {
601 if (prefix.size() > str.size())
602 return false;
603 return 0 == str.compare(0, prefix.size(), prefix);
604}
605
adlr@google.com3defe6a2009-12-04 20:57:17 +0000606bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700607 const string& mountpoint,
608 unsigned long mountflags) {
609 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000610 if (rc < 0) {
611 string msg = ErrnoNumberAsString(errno);
612 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
613 << device << " on " << mountpoint;
614 return false;
615 }
616 return true;
617}
618
619bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700620 for (int num_retries = 0; ; ++num_retries) {
621 if (umount(mountpoint.c_str()) == 0)
622 break;
623
624 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
625 num_retries < kUnmountMaxNumOfRetries);
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800626 g_usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700627 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000628 return true;
629}
630
Darin Petkovd3f8c892010-10-12 21:38:45 -0700631bool GetFilesystemSize(const std::string& device,
632 int* out_block_count,
633 int* out_block_size) {
634 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
635 TEST_AND_RETURN_FALSE(fd >= 0);
636 ScopedFdCloser fd_closer(&fd);
637 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
638}
639
640bool GetFilesystemSizeFromFD(int fd,
641 int* out_block_count,
642 int* out_block_size) {
643 TEST_AND_RETURN_FALSE(fd >= 0);
644
645 // Determine the ext3 filesystem size by directly reading the block count and
646 // block size information from the superblock. See include/linux/ext3_fs.h for
647 // more details on the structure.
648 ssize_t kBufferSize = 16 * sizeof(uint32_t);
649 char buffer[kBufferSize];
650 const int kSuperblockOffset = 1024;
651 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
652 kBufferSize) {
653 PLOG(ERROR) << "Unable to determine file system size:";
654 return false;
655 }
656 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
657 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
658 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
659 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
660 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
661 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
662 block_count = le32toh(block_count);
663 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
664 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
665 magic = le16toh(magic);
666
667 // Sanity check the parameters.
668 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
669 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
670 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
671 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
672 int block_size = 1 << log_block_size;
673 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
674 block_size <= kExt3MaxBlockSize);
675 TEST_AND_RETURN_FALSE(block_count > 0);
676
677 if (out_block_count) {
678 *out_block_count = block_count;
679 }
680 if (out_block_size) {
681 *out_block_size = block_size;
682 }
683 return true;
684}
685
Alex Deymo032e7722014-03-25 17:53:56 -0700686// Tries to parse the header of an ELF file to obtain a human-readable
687// description of it on the |output| string.
688static bool GetFileFormatELF(const char* buffer, size_t size, string* output) {
689 // 0x00: EI_MAG - ELF magic header, 4 bytes.
690 if (size < 4 || memcmp(buffer, "\x7F""ELF", 4) != 0)
691 return false;
692 *output = "ELF";
693
694 // 0x04: EI_CLASS, 1 byte.
695 if (size < 0x04 + 1)
696 return true;
697 switch (buffer[4]) {
698 case 1:
699 *output += " 32-bit";
700 break;
701 case 2:
702 *output += " 64-bit";
703 break;
704 default:
705 *output += " ?-bit";
706 }
707
708 // 0x05: EI_DATA, endianness, 1 byte.
709 if (size < 0x05 + 1)
710 return true;
711 char ei_data = buffer[5];
712 switch (ei_data) {
713 case 1:
714 *output += " little-endian";
715 break;
716 case 2:
717 *output += " big-endian";
718 break;
719 default:
720 *output += " ?-endian";
721 // Don't parse anything after the 0x10 offset if endianness is unknown.
722 return true;
723 }
724
725 // 0x12: e_machine, 2 byte endianness based on ei_data
726 if (size < 0x12 + 2)
727 return true;
728 uint16 e_machine = *reinterpret_cast<const uint16*>(buffer+0x12);
729 // Fix endianess regardless of the host endianess.
730 if (ei_data == 1)
731 e_machine = le16toh(e_machine);
732 else
733 e_machine = be16toh(e_machine);
734
735 switch (e_machine) {
736 case 0x03:
737 *output += " x86";
738 break;
739 case 0x28:
740 *output += " arm";
741 break;
742 case 0x3E:
743 *output += " x86-64";
744 break;
745 default:
746 *output += " unknown-arch";
747 }
748 return true;
749}
750
751string GetFileFormat(const string& path) {
752 vector<char> buffer;
753 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
754 return "File not found.";
755
756 string result;
757 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
758 return result;
759
760 return "data";
761}
762
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700763bool GetBootloader(BootLoader* out_bootloader) {
764 // For now, hardcode to syslinux.
765 *out_bootloader = BootLoader_SYSLINUX;
766 return true;
767}
768
Darin Petkova0b9e772011-10-06 05:05:56 -0700769string GetAndFreeGError(GError** error) {
770 if (!*error) {
771 return "Unknown GLib error.";
772 }
773 string message =
774 base::StringPrintf("GError(%d): %s",
775 (*error)->code,
776 (*error)->message ? (*error)->message : "(unknown)");
777 g_error_free(*error);
778 *error = NULL;
779 return message;
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700780}
781
Darin Petkov296889c2010-07-23 16:20:54 -0700782bool Reboot() {
783 vector<string> command;
784 command.push_back("/sbin/shutdown");
785 command.push_back("-r");
786 command.push_back("now");
787 int rc = 0;
Darin Petkov85d02b72011-05-17 13:25:51 -0700788 Subprocess::SynchronousExec(command, &rc, NULL);
Darin Petkov296889c2010-07-23 16:20:54 -0700789 TEST_AND_RETURN_FALSE(rc == 0);
790 return true;
791}
792
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800793namespace {
794// Do the actual trigger. We do it as a main-loop callback to (try to) get a
795// consistent stack trace.
796gboolean TriggerCrashReporterUpload(void* unused) {
797 pid_t pid = fork();
798 CHECK(pid >= 0) << "fork failed"; // fork() failed. Something is very wrong.
799 if (pid == 0) {
800 // We are the child. Crash.
801 abort(); // never returns
802 }
803 // We are the parent. Wait for child to terminate.
804 pid_t result = waitpid(pid, NULL, 0);
805 LOG_IF(ERROR, result < 0) << "waitpid() failed";
806 return FALSE; // Don't call this callback again
807}
808} // namespace {}
809
810void ScheduleCrashReporterUpload() {
811 g_idle_add(&TriggerCrashReporterUpload, NULL);
812}
813
Chris Sosa4f8ee272012-11-30 13:01:54 -0800814bool SetCpuShares(CpuShares shares) {
815 string string_shares = base::IntToString(static_cast<int>(shares));
816 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
817 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
818 if(utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
819 string_shares.size())){
820 return true;
821 } else {
822 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
823 << " using " << cpu_shares_file;
824 return false;
825 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700826}
827
Chris Sosa4f8ee272012-11-30 13:01:54 -0800828int CompareCpuShares(CpuShares shares_lhs,
829 CpuShares shares_rhs) {
830 return static_cast<int>(shares_lhs) - static_cast<int>(shares_rhs);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700831}
832
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700833int FuzzInt(int value, unsigned int range) {
834 int min = value - range / 2;
835 int max = value + range - range / 2;
836 return base::RandInt(min, max);
837}
838
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800839gboolean GlibRunClosure(gpointer data) {
840 google::protobuf::Closure* callback =
841 reinterpret_cast<google::protobuf::Closure*>(data);
842 callback->Run();
843 return FALSE;
844}
845
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700846string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800847 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700848}
849
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800850string FormatTimeDelta(TimeDelta delta) {
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700851 // Canonicalize into days, hours, minutes, seconds and microseconds.
852 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800853 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700854 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800855 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700856 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800857 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700858 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800859 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700860 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800861
862 // Construct and return string.
863 string str;
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700864 if (days)
865 base::StringAppendF(&str, "%ud", days);
866 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800867 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700868 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800869 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700870 base::StringAppendF(&str, "%u", secs);
871 if (usecs) {
872 int width = 6;
873 while ((usecs / 10) * 10 == usecs) {
874 usecs /= 10;
875 width--;
876 }
877 base::StringAppendF(&str, ".%0*u", width, usecs);
878 }
879 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800880 return str;
881}
882
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700883string ToString(const Time utc_time) {
884 Time::Exploded exp_time;
885 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700886 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700887 exp_time.month,
888 exp_time.day_of_month,
889 exp_time.year,
890 exp_time.hour,
891 exp_time.minute,
892 exp_time.second);
893}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000894
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700895string ToString(bool b) {
896 return (b ? "true" : "false");
897}
898
Alex Deymo1c656c42013-06-28 11:02:14 -0700899string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700900 switch (source) {
901 case kDownloadSourceHttpsServer: return "HttpsServer";
902 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700903 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -0700904 case kNumDownloadSources: return "Unknown";
905 // Don't add a default case to let the compiler warn about newly added
906 // download sources which should be added here.
907 }
908
909 return "Unknown";
910}
911
Alex Deymo1c656c42013-06-28 11:02:14 -0700912string ToString(PayloadType payload_type) {
913 switch (payload_type) {
914 case kPayloadTypeDelta: return "Delta";
915 case kPayloadTypeFull: return "Full";
916 case kPayloadTypeForcedFull: return "ForcedFull";
917 case kNumPayloadTypes: return "Unknown";
918 // Don't add a default case to let the compiler warn about newly added
919 // payload types which should be added here.
920 }
921
922 return "Unknown";
923}
924
David Zeuthena99981f2013-04-29 13:42:47 -0700925ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700926 // Ignore the higher order bits in the code by applying the mask as
927 // we want the enumerations to be in the small contiguous range
David Zeuthena99981f2013-04-29 13:42:47 -0700928 // with values less than kErrorCodeUmaReportedMax.
929 ErrorCode base_code = static_cast<ErrorCode>(code & ~kErrorCodeSpecialFlags);
Jay Srinivasanf0572052012-10-23 18:12:56 -0700930
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800931 // Make additional adjustments required for UMA and error classification.
932 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
933 // chromium-os:34369.
David Zeuthena99981f2013-04-29 13:42:47 -0700934 if (base_code >= kErrorCodeOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700935 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800936 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800937 LOG(INFO) << "Converting error code " << base_code
David Zeuthena99981f2013-04-29 13:42:47 -0700938 << " to kErrorCodeOmahaErrorInHTTPResponse";
939 base_code = kErrorCodeOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700940 }
941
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800942 return base_code;
943}
944
David Zeuthen33bae492014-02-25 16:16:18 -0800945metrics::AttemptResult GetAttemptResult(ErrorCode code) {
946 ErrorCode base_code = static_cast<ErrorCode>(code & ~kErrorCodeSpecialFlags);
947
948 switch (base_code) {
949 case kErrorCodeSuccess:
950 return metrics::AttemptResult::kUpdateSucceeded;
951
952 case kErrorCodeDownloadTransferError:
953 return metrics::AttemptResult::kPayloadDownloadError;
954
955 case kErrorCodeDownloadInvalidMetadataSize:
956 case kErrorCodeDownloadInvalidMetadataMagicString:
957 case kErrorCodeDownloadMetadataSignatureError:
958 case kErrorCodeDownloadMetadataSignatureVerificationError:
959 case kErrorCodePayloadMismatchedType:
960 case kErrorCodeUnsupportedMajorPayloadVersion:
961 case kErrorCodeUnsupportedMinorPayloadVersion:
962 case kErrorCodeDownloadNewPartitionInfoError:
963 case kErrorCodeDownloadSignatureMissingInManifest:
964 case kErrorCodeDownloadManifestParseError:
965 case kErrorCodeDownloadOperationHashMissingError:
966 return metrics::AttemptResult::kMetadataMalformed;
967
968 case kErrorCodeDownloadOperationHashMismatch:
969 case kErrorCodeDownloadOperationHashVerificationError:
970 return metrics::AttemptResult::kOperationMalformed;
971
972 case kErrorCodeDownloadOperationExecutionError:
973 case kErrorCodeInstallDeviceOpenError:
974 case kErrorCodeKernelDeviceOpenError:
975 case kErrorCodeDownloadWriteError:
976 case kErrorCodeFilesystemCopierError:
977 return metrics::AttemptResult::kOperationExecutionError;
978
979 case kErrorCodeDownloadMetadataSignatureMismatch:
980 return metrics::AttemptResult::kMetadataVerificationFailed;
981
982 case kErrorCodePayloadSizeMismatchError:
983 case kErrorCodePayloadHashMismatchError:
984 case kErrorCodeDownloadPayloadVerificationError:
985 case kErrorCodeSignedDeltaPayloadExpectedError:
986 case kErrorCodeDownloadPayloadPubKeyVerificationError:
987 return metrics::AttemptResult::kPayloadVerificationFailed;
988
989 case kErrorCodeNewRootfsVerificationError:
990 case kErrorCodeNewKernelVerificationError:
991 return metrics::AttemptResult::kVerificationFailed;
992
993 case kErrorCodePostinstallRunnerError:
994 case kErrorCodePostinstallBootedFromFirmwareB:
995 case kErrorCodePostinstallFirmwareRONotUpdatable:
996 return metrics::AttemptResult::kPostInstallFailed;
997
998 // We should never get these errors in the update-attempt stage so
999 // return internal error if this happens.
1000 case kErrorCodeError:
1001 case kErrorCodeOmahaRequestXMLParseError:
1002 case kErrorCodeOmahaRequestError:
1003 case kErrorCodeOmahaResponseHandlerError:
1004 case kErrorCodeDownloadStateInitializationError:
1005 case kErrorCodeOmahaRequestEmptyResponseError:
1006 case kErrorCodeDownloadInvalidMetadataSignature:
1007 case kErrorCodeOmahaResponseInvalid:
1008 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
1009 case kErrorCodeOmahaUpdateDeferredPerPolicy:
1010 case kErrorCodeOmahaErrorInHTTPResponse:
1011 case kErrorCodeDownloadMetadataSignatureMissingError:
1012 case kErrorCodeOmahaUpdateDeferredForBackoff:
1013 case kErrorCodePostinstallPowerwashError:
1014 case kErrorCodeUpdateCanceledByChannelChange:
1015 return metrics::AttemptResult::kInternalError;
1016
1017 // Special flags. These can't happen (we mask them out above) but
1018 // the compiler doesn't know that. Just break out so we can warn and
1019 // return |kInternalError|.
1020 case kErrorCodeUmaReportedMax:
1021 case kErrorCodeOmahaRequestHTTPResponseBase:
1022 case kErrorCodeDevModeFlag:
1023 case kErrorCodeResumedFlag:
1024 case kErrorCodeTestImageFlag:
1025 case kErrorCodeTestOmahaUrlFlag:
1026 case kErrorCodeSpecialFlags:
1027 break;
1028 }
1029
1030 LOG(ERROR) << "Unexpected error code " << base_code;
1031 return metrics::AttemptResult::kInternalError;
1032}
1033
1034
1035metrics::DownloadErrorCode GetDownloadErrorCode(ErrorCode code) {
1036 ErrorCode base_code = static_cast<ErrorCode>(code & ~kErrorCodeSpecialFlags);
1037
1038 if (base_code >= kErrorCodeOmahaRequestHTTPResponseBase) {
1039 int http_status = base_code - kErrorCodeOmahaRequestHTTPResponseBase;
1040 if (http_status >= 200 && http_status <= 599) {
1041 return static_cast<metrics::DownloadErrorCode>(
1042 static_cast<int>(metrics::DownloadErrorCode::kHttpStatus200) +
1043 http_status - 200);
1044 } else if (http_status == 0) {
1045 // The code is using HTTP Status 0 for "Unable to get http
1046 // response code."
1047 return metrics::DownloadErrorCode::kDownloadError;
1048 }
1049 LOG(WARNING) << "Unexpected HTTP status code " << http_status;
1050 return metrics::DownloadErrorCode::kHttpStatusOther;
1051 }
1052
1053 switch (base_code) {
1054 // Unfortunately, kErrorCodeDownloadTransferError is returned for a wide
1055 // variety of errors (proxy errors, host not reachable, timeouts etc.).
1056 //
1057 // For now just map that to kDownloading. See http://crbug.com/355745
1058 // for how we plan to add more detail in the future.
1059 case kErrorCodeDownloadTransferError:
1060 return metrics::DownloadErrorCode::kDownloadError;
1061
1062 // All of these error codes are not related to downloading so break
1063 // out so we can warn and return InputMalformed.
1064 case kErrorCodeSuccess:
1065 case kErrorCodeError:
1066 case kErrorCodeOmahaRequestError:
1067 case kErrorCodeOmahaResponseHandlerError:
1068 case kErrorCodeFilesystemCopierError:
1069 case kErrorCodePostinstallRunnerError:
1070 case kErrorCodePayloadMismatchedType:
1071 case kErrorCodeInstallDeviceOpenError:
1072 case kErrorCodeKernelDeviceOpenError:
1073 case kErrorCodePayloadHashMismatchError:
1074 case kErrorCodePayloadSizeMismatchError:
1075 case kErrorCodeDownloadPayloadVerificationError:
1076 case kErrorCodeDownloadNewPartitionInfoError:
1077 case kErrorCodeDownloadWriteError:
1078 case kErrorCodeNewRootfsVerificationError:
1079 case kErrorCodeNewKernelVerificationError:
1080 case kErrorCodeSignedDeltaPayloadExpectedError:
1081 case kErrorCodeDownloadPayloadPubKeyVerificationError:
1082 case kErrorCodePostinstallBootedFromFirmwareB:
1083 case kErrorCodeDownloadStateInitializationError:
1084 case kErrorCodeDownloadInvalidMetadataMagicString:
1085 case kErrorCodeDownloadSignatureMissingInManifest:
1086 case kErrorCodeDownloadManifestParseError:
1087 case kErrorCodeDownloadMetadataSignatureError:
1088 case kErrorCodeDownloadMetadataSignatureVerificationError:
1089 case kErrorCodeDownloadMetadataSignatureMismatch:
1090 case kErrorCodeDownloadOperationHashVerificationError:
1091 case kErrorCodeDownloadOperationExecutionError:
1092 case kErrorCodeDownloadOperationHashMismatch:
1093 case kErrorCodeOmahaRequestEmptyResponseError:
1094 case kErrorCodeOmahaRequestXMLParseError:
1095 case kErrorCodeDownloadInvalidMetadataSize:
1096 case kErrorCodeDownloadInvalidMetadataSignature:
1097 case kErrorCodeOmahaResponseInvalid:
1098 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
1099 case kErrorCodeOmahaUpdateDeferredPerPolicy:
1100 case kErrorCodeOmahaErrorInHTTPResponse:
1101 case kErrorCodeDownloadOperationHashMissingError:
1102 case kErrorCodeDownloadMetadataSignatureMissingError:
1103 case kErrorCodeOmahaUpdateDeferredForBackoff:
1104 case kErrorCodePostinstallPowerwashError:
1105 case kErrorCodeUpdateCanceledByChannelChange:
1106 case kErrorCodePostinstallFirmwareRONotUpdatable:
1107 case kErrorCodeUnsupportedMajorPayloadVersion:
1108 case kErrorCodeUnsupportedMinorPayloadVersion:
1109 break;
1110
1111 // Special flags. These can't happen (we mask them out above) but
1112 // the compiler doesn't know that. Just break out so we can warn and
1113 // return |kInputMalformed|.
1114 case kErrorCodeUmaReportedMax:
1115 case kErrorCodeOmahaRequestHTTPResponseBase:
1116 case kErrorCodeDevModeFlag:
1117 case kErrorCodeResumedFlag:
1118 case kErrorCodeTestImageFlag:
1119 case kErrorCodeTestOmahaUrlFlag:
1120 case kErrorCodeSpecialFlags:
1121 LOG(ERROR) << "Unexpected error code " << base_code;
1122 break;
1123 }
1124
1125 return metrics::DownloadErrorCode::kInputMalformed;
1126}
1127
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001128// Returns a printable version of the various flags denoted in the higher order
1129// bits of the given code. Returns an empty string if none of those bits are
1130// set.
1131string GetFlagNames(uint32_t code) {
David Zeuthena99981f2013-04-29 13:42:47 -07001132 uint32_t flags = code & kErrorCodeSpecialFlags;
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001133 string flag_names;
1134 string separator = "";
1135 for(size_t i = 0; i < sizeof(flags) * 8; i++) {
1136 uint32_t flag = flags & (1 << i);
1137 if (flag) {
David Zeuthena99981f2013-04-29 13:42:47 -07001138 flag_names += separator + CodeToString(static_cast<ErrorCode>(flag));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001139 separator = ", ";
1140 }
1141 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001142
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001143 return flag_names;
Jay Srinivasanf0572052012-10-23 18:12:56 -07001144}
1145
David Zeuthena99981f2013-04-29 13:42:47 -07001146void SendErrorCodeToUma(SystemState* system_state, ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001147 if (!system_state)
1148 return;
1149
David Zeuthena99981f2013-04-29 13:42:47 -07001150 ErrorCode uma_error_code = GetBaseErrorCode(code);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001151
1152 // If the code doesn't have flags computed already, compute them now based on
1153 // the state of the current update attempt.
David Zeuthena99981f2013-04-29 13:42:47 -07001154 uint32_t flags = code & kErrorCodeSpecialFlags;
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001155 if (!flags)
1156 flags = system_state->update_attempter()->GetErrorCodeFlags();
1157
1158 // Determine the UMA bucket depending on the flags. But, ignore the resumed
1159 // flag, as it's perfectly normal for production devices to resume their
1160 // downloads and so we want to record those cases also in NormalErrorCodes
1161 // bucket.
David Zeuthena99981f2013-04-29 13:42:47 -07001162 string metric = (flags & ~kErrorCodeResumedFlag) ?
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001163 "Installer.DevModeErrorCodes" : "Installer.NormalErrorCodes";
1164
1165 LOG(INFO) << "Sending error code " << uma_error_code
1166 << " (" << CodeToString(uma_error_code) << ")"
1167 << " to UMA metric: " << metric
1168 << ". Flags = " << (flags ? GetFlagNames(flags) : "None");
1169
1170 system_state->metrics_lib()->SendEnumToUMA(metric,
1171 uma_error_code,
David Zeuthena99981f2013-04-29 13:42:47 -07001172 kErrorCodeUmaReportedMax);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001173}
1174
David Zeuthena99981f2013-04-29 13:42:47 -07001175string CodeToString(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001176 // If the given code has both parts (i.e. the error code part and the flags
1177 // part) then strip off the flags part since the switch statement below
1178 // has case statements only for the base error code or a single flag but
1179 // doesn't support any combinations of those.
David Zeuthena99981f2013-04-29 13:42:47 -07001180 if ((code & kErrorCodeSpecialFlags) && (code & ~kErrorCodeSpecialFlags))
1181 code = static_cast<ErrorCode>(code & ~kErrorCodeSpecialFlags);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001182 switch (code) {
David Zeuthena99981f2013-04-29 13:42:47 -07001183 case kErrorCodeSuccess: return "kErrorCodeSuccess";
1184 case kErrorCodeError: return "kErrorCodeError";
1185 case kErrorCodeOmahaRequestError: return "kErrorCodeOmahaRequestError";
1186 case kErrorCodeOmahaResponseHandlerError:
1187 return "kErrorCodeOmahaResponseHandlerError";
1188 case kErrorCodeFilesystemCopierError:
1189 return "kErrorCodeFilesystemCopierError";
1190 case kErrorCodePostinstallRunnerError:
1191 return "kErrorCodePostinstallRunnerError";
Gilad Arnold21504f02013-05-24 08:51:22 -07001192 case kErrorCodePayloadMismatchedType:
1193 return "kErrorCodePayloadMismatchedType";
David Zeuthena99981f2013-04-29 13:42:47 -07001194 case kErrorCodeInstallDeviceOpenError:
1195 return "kErrorCodeInstallDeviceOpenError";
1196 case kErrorCodeKernelDeviceOpenError:
1197 return "kErrorCodeKernelDeviceOpenError";
1198 case kErrorCodeDownloadTransferError:
1199 return "kErrorCodeDownloadTransferError";
1200 case kErrorCodePayloadHashMismatchError:
1201 return "kErrorCodePayloadHashMismatchError";
1202 case kErrorCodePayloadSizeMismatchError:
1203 return "kErrorCodePayloadSizeMismatchError";
1204 case kErrorCodeDownloadPayloadVerificationError:
1205 return "kErrorCodeDownloadPayloadVerificationError";
1206 case kErrorCodeDownloadNewPartitionInfoError:
1207 return "kErrorCodeDownloadNewPartitionInfoError";
1208 case kErrorCodeDownloadWriteError:
1209 return "kErrorCodeDownloadWriteError";
1210 case kErrorCodeNewRootfsVerificationError:
1211 return "kErrorCodeNewRootfsVerificationError";
1212 case kErrorCodeNewKernelVerificationError:
1213 return "kErrorCodeNewKernelVerificationError";
1214 case kErrorCodeSignedDeltaPayloadExpectedError:
1215 return "kErrorCodeSignedDeltaPayloadExpectedError";
1216 case kErrorCodeDownloadPayloadPubKeyVerificationError:
1217 return "kErrorCodeDownloadPayloadPubKeyVerificationError";
1218 case kErrorCodePostinstallBootedFromFirmwareB:
1219 return "kErrorCodePostinstallBootedFromFirmwareB";
1220 case kErrorCodeDownloadStateInitializationError:
1221 return "kErrorCodeDownloadStateInitializationError";
1222 case kErrorCodeDownloadInvalidMetadataMagicString:
1223 return "kErrorCodeDownloadInvalidMetadataMagicString";
1224 case kErrorCodeDownloadSignatureMissingInManifest:
1225 return "kErrorCodeDownloadSignatureMissingInManifest";
1226 case kErrorCodeDownloadManifestParseError:
1227 return "kErrorCodeDownloadManifestParseError";
1228 case kErrorCodeDownloadMetadataSignatureError:
1229 return "kErrorCodeDownloadMetadataSignatureError";
1230 case kErrorCodeDownloadMetadataSignatureVerificationError:
1231 return "kErrorCodeDownloadMetadataSignatureVerificationError";
1232 case kErrorCodeDownloadMetadataSignatureMismatch:
1233 return "kErrorCodeDownloadMetadataSignatureMismatch";
1234 case kErrorCodeDownloadOperationHashVerificationError:
1235 return "kErrorCodeDownloadOperationHashVerificationError";
1236 case kErrorCodeDownloadOperationExecutionError:
1237 return "kErrorCodeDownloadOperationExecutionError";
1238 case kErrorCodeDownloadOperationHashMismatch:
1239 return "kErrorCodeDownloadOperationHashMismatch";
1240 case kErrorCodeOmahaRequestEmptyResponseError:
1241 return "kErrorCodeOmahaRequestEmptyResponseError";
1242 case kErrorCodeOmahaRequestXMLParseError:
1243 return "kErrorCodeOmahaRequestXMLParseError";
1244 case kErrorCodeDownloadInvalidMetadataSize:
1245 return "kErrorCodeDownloadInvalidMetadataSize";
1246 case kErrorCodeDownloadInvalidMetadataSignature:
1247 return "kErrorCodeDownloadInvalidMetadataSignature";
1248 case kErrorCodeOmahaResponseInvalid:
1249 return "kErrorCodeOmahaResponseInvalid";
1250 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
1251 return "kErrorCodeOmahaUpdateIgnoredPerPolicy";
1252 case kErrorCodeOmahaUpdateDeferredPerPolicy:
1253 return "kErrorCodeOmahaUpdateDeferredPerPolicy";
1254 case kErrorCodeOmahaErrorInHTTPResponse:
1255 return "kErrorCodeOmahaErrorInHTTPResponse";
1256 case kErrorCodeDownloadOperationHashMissingError:
1257 return "kErrorCodeDownloadOperationHashMissingError";
1258 case kErrorCodeDownloadMetadataSignatureMissingError:
1259 return "kErrorCodeDownloadMetadataSignatureMissingError";
1260 case kErrorCodeOmahaUpdateDeferredForBackoff:
1261 return "kErrorCodeOmahaUpdateDeferredForBackoff";
1262 case kErrorCodePostinstallPowerwashError:
1263 return "kErrorCodePostinstallPowerwashError";
1264 case kErrorCodeUpdateCanceledByChannelChange:
1265 return "kErrorCodeUpdateCanceledByChannelChange";
1266 case kErrorCodeUmaReportedMax:
1267 return "kErrorCodeUmaReportedMax";
1268 case kErrorCodeOmahaRequestHTTPResponseBase:
1269 return "kErrorCodeOmahaRequestHTTPResponseBase";
1270 case kErrorCodeResumedFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001271 return "Resumed";
David Zeuthena99981f2013-04-29 13:42:47 -07001272 case kErrorCodeDevModeFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001273 return "DevMode";
David Zeuthena99981f2013-04-29 13:42:47 -07001274 case kErrorCodeTestImageFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001275 return "TestImage";
David Zeuthena99981f2013-04-29 13:42:47 -07001276 case kErrorCodeTestOmahaUrlFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001277 return "TestOmahaUrl";
David Zeuthena99981f2013-04-29 13:42:47 -07001278 case kErrorCodeSpecialFlags:
1279 return "kErrorCodeSpecialFlags";
Don Garrett81018e02013-07-30 18:46:31 -07001280 case kErrorCodePostinstallFirmwareRONotUpdatable:
1281 return "kErrorCodePostinstallFirmwareRONotUpdatable";
Don Garrett4d039442013-10-28 18:40:06 -07001282 case kErrorCodeUnsupportedMajorPayloadVersion:
1283 return "kErrorCodeUnsupportedMajorPayloadVersion";
1284 case kErrorCodeUnsupportedMinorPayloadVersion:
1285 return "kErrorCodeUnsupportedMinorPayloadVersion";
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001286 // Don't add a default case to let the compiler warn about newly added
1287 // error codes which should be added here.
1288 }
1289
1290 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
1291}
Jay Srinivasanf0572052012-10-23 18:12:56 -07001292
Gilad Arnold30dedd82013-07-03 06:19:09 -07001293bool CreatePowerwashMarkerFile(const char* file_path) {
1294 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
1295 bool result = utils::WriteFile(marker_file,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001296 kPowerwashCommand,
1297 strlen(kPowerwashCommand));
Gilad Arnold30dedd82013-07-03 06:19:09 -07001298 if (result) {
1299 LOG(INFO) << "Created " << marker_file << " to powerwash on next reboot";
1300 } else {
1301 PLOG(ERROR) << "Error in creating powerwash marker file: " << marker_file;
1302 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001303
1304 return result;
1305}
1306
Gilad Arnold30dedd82013-07-03 06:19:09 -07001307bool DeletePowerwashMarkerFile(const char* file_path) {
1308 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
Alex Vakulenko75039d72014-03-25 12:36:28 -07001309 const base::FilePath kPowerwashMarkerPath(marker_file);
1310 bool result = base::DeleteFile(kPowerwashMarkerPath, false);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001311
1312 if (result)
1313 LOG(INFO) << "Successfully deleted the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001314 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001315 else
1316 PLOG(ERROR) << "Could not delete the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001317 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001318
1319 return result;
1320}
1321
Chris Sosad317e402013-06-12 13:47:09 -07001322bool GetInstallDev(const std::string& boot_dev, std::string* install_dev) {
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -07001323 std::string disk_name;
1324 int partition_num;
1325 if (!SplitPartitionName(boot_dev, &disk_name, &partition_num))
1326 return false;
Liam McLoughlin049d1652013-07-31 18:47:46 -07001327
Chris Sosad317e402013-06-12 13:47:09 -07001328 // Right now, we just switch '3' and '5' partition numbers.
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -07001329 if (partition_num == 3) {
1330 partition_num = 5;
1331 } else if (partition_num == 5) {
1332 partition_num = 3;
1333 } else {
1334 return false;
1335 }
1336
1337 if (install_dev)
1338 *install_dev = MakePartitionName(disk_name, partition_num);
Liam McLoughlin049d1652013-07-31 18:47:46 -07001339
Chris Sosad317e402013-06-12 13:47:09 -07001340 return true;
1341}
1342
David Zeuthen27a48bc2013-08-06 12:06:29 -07001343Time TimeFromStructTimespec(struct timespec *ts) {
1344 int64 us = static_cast<int64>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
1345 static_cast<int64>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
1346 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
1347}
1348
1349gchar** StringVectorToGStrv(const vector<string> &vector) {
1350 GPtrArray *p = g_ptr_array_new();
1351 for (std::vector<string>::const_iterator i = vector.begin();
1352 i != vector.end(); ++i) {
1353 g_ptr_array_add(p, g_strdup(i->c_str()));
1354 }
1355 g_ptr_array_add(p, NULL);
1356 return reinterpret_cast<gchar**>(g_ptr_array_free(p, FALSE));
1357}
1358
1359string StringVectorToString(const vector<string> &vector) {
1360 string str = "[";
1361 for (std::vector<string>::const_iterator i = vector.begin();
1362 i != vector.end(); ++i) {
1363 if (i != vector.begin())
1364 str += ", ";
1365 str += '"';
1366 str += *i;
1367 str += '"';
1368 }
1369 str += "]";
1370 return str;
1371}
1372
David Zeuthen8f191b22013-08-06 12:27:50 -07001373string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
1374 string encoded_hash;
1375 OmahaHashCalculator::Base64Encode(payload_hash.c_str(),
1376 payload_hash.size(),
1377 &encoded_hash);
Alex Vakulenko75039d72014-03-25 12:36:28 -07001378 return base::StringPrintf("cros_update_size_%zu_hash_%s",
David Zeuthen8f191b22013-08-06 12:27:50 -07001379 payload_size,
1380 encoded_hash.c_str());
1381}
1382
David Zeuthen910ec5b2013-09-26 12:10:58 -07001383bool IsXAttrSupported(const base::FilePath& dir_path) {
1384 char *path = strdup(dir_path.Append("xattr_test_XXXXXX").value().c_str());
1385
1386 int fd = mkstemp(path);
1387 if (fd == -1) {
1388 PLOG(ERROR) << "Error creating temporary file in " << dir_path.value();
1389 free(path);
1390 return false;
1391 }
1392
1393 if (unlink(path) != 0) {
1394 PLOG(ERROR) << "Error unlinking temporary file " << path;
1395 close(fd);
1396 free(path);
1397 return false;
1398 }
1399
1400 int xattr_res = fsetxattr(fd, "user.xattr-test", "value", strlen("value"), 0);
1401 if (xattr_res != 0) {
1402 if (errno == ENOTSUP) {
1403 // Leave it to call-sites to warn about non-support.
1404 } else {
1405 PLOG(ERROR) << "Error setting xattr on " << path;
1406 }
1407 }
1408 close(fd);
1409 free(path);
1410 return xattr_res == 0;
1411}
1412
David Zeuthene7f89172013-10-31 10:21:04 -07001413bool DecodeAndStoreBase64String(const std::string& base64_encoded,
1414 base::FilePath *out_path) {
1415 vector<char> contents;
1416
1417 out_path->clear();
1418
1419 if (base64_encoded.size() == 0) {
1420 LOG(ERROR) << "Can't decode empty string.";
1421 return false;
1422 }
1423
1424 if (!OmahaHashCalculator::Base64Decode(base64_encoded, &contents) ||
1425 contents.size() == 0) {
1426 LOG(ERROR) << "Error decoding base64.";
1427 return false;
1428 }
1429
Alex Vakulenko75039d72014-03-25 12:36:28 -07001430 FILE *file = base::CreateAndOpenTemporaryFile(out_path);
David Zeuthene7f89172013-10-31 10:21:04 -07001431 if (file == NULL) {
1432 LOG(ERROR) << "Error creating temporary file.";
1433 return false;
1434 }
1435
1436 if (fwrite(&contents[0], 1, contents.size(), file) != contents.size()) {
1437 PLOG(ERROR) << "Error writing to temporary file.";
1438 if (fclose(file) != 0)
1439 PLOG(ERROR) << "Error closing temporary file.";
1440 if (unlink(out_path->value().c_str()) != 0)
1441 PLOG(ERROR) << "Error unlinking temporary file.";
1442 out_path->clear();
1443 return false;
1444 }
1445
1446 if (fclose(file) != 0) {
1447 PLOG(ERROR) << "Error closing temporary file.";
1448 out_path->clear();
1449 return false;
1450 }
1451
1452 return true;
1453}
1454
David Zeuthen639aa362014-02-03 16:23:44 -08001455bool ConvertToOmahaInstallDate(base::Time time, int *out_num_days) {
1456 time_t unix_time = time.ToTimeT();
1457 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
1458 const time_t kOmahaEpoch = 1167638400;
1459 const int64_t kNumSecondsPerWeek = 7*24*3600;
1460 const int64_t kNumDaysPerWeek = 7;
1461
1462 time_t omaha_time = unix_time - kOmahaEpoch;
1463
1464 if (omaha_time < 0)
1465 return false;
1466
1467 // Note, as per the comment in utils.h we are deliberately not
1468 // handling DST correctly.
1469
1470 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
1471 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
1472
1473 return true;
1474}
1475
David Zeuthen33bae492014-02-25 16:16:18 -08001476bool WallclockDurationHelper(SystemState* system_state,
1477 const std::string& state_variable_key,
1478 base::TimeDelta* out_duration) {
1479 bool ret = false;
1480
1481 base::Time now = system_state->clock()->GetWallclockTime();
1482 int64_t stored_value;
1483 if (system_state->prefs()->GetInt64(state_variable_key, &stored_value)) {
1484 base::Time stored_time = base::Time::FromInternalValue(stored_value);
1485 if (stored_time > now) {
1486 LOG(ERROR) << "Stored time-stamp used for " << state_variable_key
1487 << " is in the future.";
1488 } else {
1489 *out_duration = now - stored_time;
1490 ret = true;
1491 }
1492 }
1493
1494 if (!system_state->prefs()->SetInt64(state_variable_key,
1495 now.ToInternalValue())) {
1496 LOG(ERROR) << "Error storing time-stamp in " << state_variable_key;
1497 }
1498
1499 return ret;
1500}
1501
1502bool MonotonicDurationHelper(SystemState* system_state,
1503 int64_t* storage,
1504 base::TimeDelta* out_duration) {
1505 bool ret = false;
1506
1507 base::Time now = system_state->clock()->GetMonotonicTime();
1508 if (*storage != 0) {
1509 base::Time stored_time = base::Time::FromInternalValue(*storage);
1510 *out_duration = now - stored_time;
1511 ret = true;
1512 }
1513 *storage = now.ToInternalValue();
1514
1515 return ret;
1516}
1517
adlr@google.com3defe6a2009-12-04 20:57:17 +00001518} // namespace utils
1519
1520} // namespace chromeos_update_engine