blob: e379aae4c1a67c2318f7040419cf4453cd0f17ac [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
J. Richard Barnette30842932013-10-28 15:04:23 -070097const string KernelDeviceOfBootDevice(const std::string& boot_device) {
98 if (boot_device.empty())
99 return boot_device;
100
101 string ubiblock_prefix("/dev/ubiblock");
102 string ret;
103 char partition_num;
104 if (StringHasPrefix(boot_device, ubiblock_prefix)) {
105 // eg: /dev/ubiblock3_0 becomes /dev/mtdblock2
106 ret = "/dev/mtdblock";
107 partition_num = boot_device[ubiblock_prefix.size()];
108 } else {
109 // eg: /dev/sda3 becomes /dev/sda2
110 // eg: /dev/mmcblk0p3 becomes /dev/mmcblk0p2
111 ret = boot_device.substr(0, boot_device.size() - 1);
112 partition_num = boot_device[boot_device.size() - 1];
113 }
114
115 // Currently this assumes the partition number of the boot device is
116 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
117 // get the kernel device.
118 if (partition_num == '3' || partition_num == '5' || partition_num == '7') {
119 ret.append(1, partition_num - 1);
120 return ret;
121 }
122
123 return "";
124}
125
126
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800127bool WriteFile(const char* path, const char* data, int data_len) {
128 DirectFileWriter writer;
129 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
130 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700131 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800132 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800133 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800134 return true;
135}
136
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700137bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700138 const char* c_buf = static_cast<const char*>(buf);
139 ssize_t bytes_written = 0;
140 while (bytes_written < static_cast<ssize_t>(count)) {
141 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
142 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
143 bytes_written += rc;
144 }
145 return true;
146}
147
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700148bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
149 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700150 size_t bytes_written = 0;
151 int num_attempts = 0;
152 while (bytes_written < count) {
153 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700154 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
155 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700156 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
157 if (rc < 0) {
158 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
159 << " bytes_written=" << bytes_written
160 << " count=" << count << " offset=" << offset;
161 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700162 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
163 bytes_written += rc;
164 }
165 return true;
166}
167
168bool PReadAll(int fd, void* buf, size_t count, off_t offset,
169 ssize_t* out_bytes_read) {
170 char* c_buf = static_cast<char*>(buf);
171 ssize_t bytes_read = 0;
172 while (bytes_read < static_cast<ssize_t>(count)) {
173 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
174 offset + bytes_read);
175 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
176 if (rc == 0) {
177 break;
178 }
179 bytes_read += rc;
180 }
181 *out_bytes_read = bytes_read;
182 return true;
Darin Petkov296889c2010-07-23 16:20:54 -0700183
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700184}
185
Gilad Arnold19a45f02012-07-19 12:36:10 -0700186// Append |nbytes| of content from |buf| to the vector pointed to by either
187// |vec_p| or |str_p|.
188static void AppendBytes(const char* buf, size_t nbytes,
189 std::vector<char>* vec_p) {
190 CHECK(buf);
191 CHECK(vec_p);
192 vec_p->insert(vec_p->end(), buf, buf + nbytes);
193}
194static void AppendBytes(const char* buf, size_t nbytes,
195 std::string* str_p) {
196 CHECK(buf);
197 CHECK(str_p);
198 str_p->append(buf, nbytes);
199}
200
201// Reads from an open file |fp|, appending the read content to the container
202// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200203// file's content, false otherwise. If |size| is not -1, reads up to |size|
204// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700205template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200206static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700207 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200208 CHECK(size == -1 || size >= 0);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700209 char buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200210 while (size == -1 || size > 0) {
211 off_t bytes_to_read = sizeof(buf);
212 if (size > 0 && bytes_to_read > size) {
213 bytes_to_read = size;
214 }
215 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
216 if (!nbytes) {
217 break;
218 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700219 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200220 if (size != -1) {
221 CHECK(size >= static_cast<off_t>(nbytes));
222 size -= nbytes;
223 }
224 }
225 if (ferror(fp)) {
226 return false;
227 }
228 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700229}
230
Darin Petkov8e447e02013-04-16 16:23:50 +0200231// Opens a file |path| for reading and appends its the contents to a container
232// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
233// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700234template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200235static bool ReadFileChunkAndAppend(const std::string& path,
236 off_t offset,
237 off_t size,
238 T* out_p) {
239 CHECK_GE(offset, 0);
240 CHECK(size == -1 || size >= 0);
241 file_util::ScopedFILE fp(fopen(path.c_str(), "r"));
242 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000243 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200244 if (offset) {
245 // Return success without appending any data if a chunk beyond the end of
246 // the file is requested.
247 if (offset >= FileSize(path)) {
248 return true;
249 }
250 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
251 }
252 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000253}
254
Gilad Arnold19a45f02012-07-19 12:36:10 -0700255// Invokes a pipe |cmd|, then uses |append_func| to append its stdout to a
256// container |out_p|.
257template <class T>
258static bool ReadPipeAndAppend(const std::string& cmd, T* out_p) {
259 FILE* fp = popen(cmd.c_str(), "r");
260 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000261 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200262 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700263 return (success && pclose(fp) >= 0);
264}
265
266
Darin Petkov8e447e02013-04-16 16:23:50 +0200267bool ReadFile(const string& path, vector<char>* out_p) {
268 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700269}
270
Darin Petkov8e447e02013-04-16 16:23:50 +0200271bool ReadFile(const string& path, string* out_p) {
272 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700273}
274
Darin Petkov8e447e02013-04-16 16:23:50 +0200275bool ReadFileChunk(const string& path, off_t offset, off_t size,
276 vector<char>* out_p) {
277 return ReadFileChunkAndAppend(path, offset, size, out_p);
278}
279
280bool ReadPipe(const string& cmd, vector<char>* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700281 return ReadPipeAndAppend(cmd, out_p);
282}
283
Darin Petkov8e447e02013-04-16 16:23:50 +0200284bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700285 return ReadPipeAndAppend(cmd, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000286}
287
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700288off_t FileSize(const string& path) {
289 struct stat stbuf;
290 int rc = stat(path.c_str(), &stbuf);
291 CHECK_EQ(rc, 0);
292 if (rc < 0)
293 return rc;
294 return stbuf.st_size;
295}
296
adlr@google.com3defe6a2009-12-04 20:57:17 +0000297void HexDumpArray(const unsigned char* const arr, const size_t length) {
298 const unsigned char* const char_arr =
299 reinterpret_cast<const unsigned char* const>(arr);
300 LOG(INFO) << "Logging array of length: " << length;
301 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700302 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000303 const unsigned int bytes_remaining = length - i;
304 const unsigned int bytes_per_this_line = min(bytes_per_line,
305 bytes_remaining);
306 char header[100];
307 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
308 TEST_AND_RETURN(r == 13);
309 string line = header;
310 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
311 char buf[20];
312 unsigned char c = char_arr[i + j];
313 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
314 TEST_AND_RETURN(r == 3);
315 line += buf;
316 }
317 LOG(INFO) << line;
318 }
319}
320
321namespace {
322class ScopedDirCloser {
323 public:
324 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
325 ~ScopedDirCloser() {
326 if (dir_ && *dir_) {
327 int r = closedir(*dir_);
328 TEST_AND_RETURN_ERRNO(r == 0);
329 *dir_ = NULL;
330 dir_ = NULL;
331 }
332 }
333 private:
334 DIR** dir_;
335};
336} // namespace {}
337
338bool RecursiveUnlinkDir(const std::string& path) {
339 struct stat stbuf;
340 int r = lstat(path.c_str(), &stbuf);
341 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
342 if ((r < 0) && (errno == ENOENT))
343 // path request is missing. that's fine.
344 return true;
345 if (!S_ISDIR(stbuf.st_mode)) {
346 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700347 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000348 // success or path disappeared before we could unlink.
349 return true;
350 }
351 {
352 // We have a dir, unlink all children, then delete dir
353 DIR *dir = opendir(path.c_str());
354 TEST_AND_RETURN_FALSE_ERRNO(dir);
355 ScopedDirCloser dir_closer(&dir);
356 struct dirent dir_entry;
357 struct dirent *dir_entry_p;
358 int err = 0;
359 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
360 if (dir_entry_p == NULL) {
361 // end of stream reached
362 break;
363 }
364 // Skip . and ..
365 if (!strcmp(dir_entry_p->d_name, ".") ||
366 !strcmp(dir_entry_p->d_name, ".."))
367 continue;
368 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700369 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000370 }
371 TEST_AND_RETURN_FALSE(err == 0);
372 }
373 // unlink dir
374 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
375 return true;
376}
377
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800378std::string GetDiskName(const string& partition_name) {
379 std::string disk_name;
380 return SplitPartitionName(partition_name, &disk_name, nullptr) ?
381 disk_name : std::string();
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700382}
383
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800384int GetPartitionNumber(const std::string& partition_name) {
385 int partition_num = 0;
386 return SplitPartitionName(partition_name, nullptr, &partition_num) ?
387 partition_num : 0;
388}
389
390bool SplitPartitionName(const std::string& partition_name,
391 std::string* out_disk_name,
392 int* out_partition_num) {
393 if (!StringHasPrefix(partition_name, "/dev/")) {
394 LOG(ERROR) << "Invalid partition device name: " << partition_name;
395 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700396 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800397
398 if (StringHasPrefix(partition_name, "/dev/ubiblock")) {
399 // NAND block devices have weird naming which could be something
400 // like "/dev/ubiblock2_0". Since update engine doesn't have proper
401 // support for NAND devices yet, don't bother parsing their names for now.
402 LOG(ERROR) << "UBI block devices are not supported: " << partition_name;
403 return false;
404 }
405
406 size_t pos = partition_name.find_last_not_of("0123456789");
407 if (pos == string::npos || (pos + 1) == partition_name.size()) {
408 LOG(ERROR) << "Unable to parse partition device name: "
409 << partition_name;
410 return false;
411 }
412
413 if (out_disk_name) {
414 // Special case for MMC devices which have the following naming scheme:
415 // mmcblk0p2
416 bool valid_mmc_device = StringHasPrefix(partition_name, "/dev/mmcblk") &&
417 partition_name[pos] == 'p';
418 *out_disk_name =
419 partition_name.substr(0, valid_mmc_device ? pos : (pos + 1));
420 }
421
422 if (out_partition_num) {
423 std::string partition_str = partition_name.substr(pos + 1);
424 *out_partition_num = atoi(partition_str.c_str());
425 }
426 return true;
427}
428
429std::string MakePartitionName(const std::string& disk_name,
430 int partition_num) {
431 if (!StringHasPrefix(disk_name, "/dev/")) {
432 LOG(ERROR) << "Invalid disk name: " << disk_name;
433 return std::string();
434 }
435
436 if (partition_num < 1) {
437 LOG(ERROR) << "Invalid partition number: " << partition_num;
438 return std::string();
439 }
440
441 std::string partition_name = disk_name;
442 if (!StringHasPrefix(disk_name, "/dev/mmcblk")) {
443 // Special case for MMC devices. Add "p" to separate the disk name
444 // from partition number
445 partition_name += 'p';
446 }
447
448 base::StringAppendF(&partition_name, "%d", partition_num);
449 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700450}
451
Darin Petkovf74eb652010-08-04 12:08:38 -0700452string SysfsBlockDevice(const string& device) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700453 base::FilePath device_path(device);
Darin Petkovf74eb652010-08-04 12:08:38 -0700454 if (device_path.DirName().value() != "/dev") {
455 return "";
456 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700457 return base::FilePath("/sys/block").Append(device_path.BaseName()).value();
Darin Petkovf74eb652010-08-04 12:08:38 -0700458}
459
460bool IsRemovableDevice(const std::string& device) {
461 string sysfs_block = SysfsBlockDevice(device);
462 string removable;
463 if (sysfs_block.empty() ||
Alex Vakulenko75039d72014-03-25 12:36:28 -0700464 !base::ReadFileToString(base::FilePath(sysfs_block).Append("removable"),
Darin Petkovf74eb652010-08-04 12:08:38 -0700465 &removable)) {
466 return false;
467 }
468 TrimWhitespaceASCII(removable, TRIM_ALL, &removable);
469 return removable == "1";
470}
471
adlr@google.com3defe6a2009-12-04 20:57:17 +0000472std::string ErrnoNumberAsString(int err) {
473 char buf[100];
474 buf[0] = '\0';
475 return strerror_r(err, buf, sizeof(buf));
476}
477
478std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
479 string ret;
480 bool last_insert_was_slash = false;
481 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
482 if (*it == '/') {
483 if (last_insert_was_slash)
484 continue;
485 last_insert_was_slash = true;
486 } else {
487 last_insert_was_slash = false;
488 }
489 ret.push_back(*it);
490 }
491 if (strip_trailing_slash && last_insert_was_slash) {
492 string::size_type last_non_slash = ret.find_last_not_of('/');
493 if (last_non_slash != string::npos) {
494 ret.resize(last_non_slash + 1);
495 } else {
496 ret = "";
497 }
498 }
499 return ret;
500}
501
502bool FileExists(const char* path) {
503 struct stat stbuf;
504 return 0 == lstat(path, &stbuf);
505}
506
Darin Petkov30291ed2010-11-12 10:23:06 -0800507bool IsSymlink(const char* path) {
508 struct stat stbuf;
509 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
510}
511
adlr@google.com3defe6a2009-12-04 20:57:17 +0000512std::string TempFilename(string path) {
513 static const string suffix("XXXXXX");
514 CHECK(StringHasSuffix(path, suffix));
515 do {
516 string new_suffix;
517 for (unsigned int i = 0; i < suffix.size(); i++) {
518 int r = rand() % (26 * 2 + 10); // [a-zA-Z0-9]
519 if (r < 26)
520 new_suffix.append(1, 'a' + r);
521 else if (r < (26 * 2))
522 new_suffix.append(1, 'A' + r - 26);
523 else
524 new_suffix.append(1, '0' + r - (26 * 2));
525 }
526 CHECK_EQ(new_suffix.size(), suffix.size());
527 path.resize(path.size() - new_suffix.size());
528 path.append(new_suffix);
529 } while (FileExists(path.c_str()));
530 return path;
531}
532
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800533// If |path| is absolute, or explicit relative to the current working directory,
534// leaves it as is. Otherwise, if TMPDIR is defined in the environment and is
535// non-empty, prepends it to |path|. Otherwise, prepends /tmp. Returns the
536// resulting path.
537static const string PrependTmpdir(const string& path) {
538 if (path[0] == '/' || StartsWithASCII(path, "./", true) ||
539 StartsWithASCII(path, "../", true))
540 return path;
541
542 const char *tmpdir = getenv("TMPDIR");
543 const string prefix = (tmpdir && *tmpdir ? tmpdir : "/tmp");
544 return prefix + "/" + path;
545}
546
547bool MakeTempFile(const std::string& base_filename_template,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700548 std::string* filename,
549 int* fd) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800550 const string filename_template = PrependTmpdir(base_filename_template);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700551 DCHECK(filename || fd);
552 vector<char> buf(filename_template.size() + 1);
553 memcpy(&buf[0], filename_template.data(), filename_template.size());
554 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700555
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700556 int mkstemp_fd = mkstemp(&buf[0]);
557 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
558 if (filename) {
559 *filename = &buf[0];
560 }
561 if (fd) {
562 *fd = mkstemp_fd;
563 } else {
564 close(mkstemp_fd);
565 }
566 return true;
567}
568
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800569bool MakeTempDirectory(const std::string& base_dirname_template,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700570 std::string* dirname) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800571 const string dirname_template = PrependTmpdir(base_dirname_template);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700572 DCHECK(dirname);
573 vector<char> buf(dirname_template.size() + 1);
574 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
575 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700576
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700577 char* return_code = mkdtemp(&buf[0]);
578 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
579 *dirname = &buf[0];
580 return true;
581}
582
adlr@google.com3defe6a2009-12-04 20:57:17 +0000583bool StringHasSuffix(const std::string& str, const std::string& suffix) {
584 if (suffix.size() > str.size())
585 return false;
586 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
587}
588
589bool StringHasPrefix(const std::string& str, const std::string& prefix) {
590 if (prefix.size() > str.size())
591 return false;
592 return 0 == str.compare(0, prefix.size(), prefix);
593}
594
adlr@google.com3defe6a2009-12-04 20:57:17 +0000595bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700596 const string& mountpoint,
597 unsigned long mountflags) {
598 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000599 if (rc < 0) {
600 string msg = ErrnoNumberAsString(errno);
601 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
602 << device << " on " << mountpoint;
603 return false;
604 }
605 return true;
606}
607
608bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700609 for (int num_retries = 0; ; ++num_retries) {
610 if (umount(mountpoint.c_str()) == 0)
611 break;
612
613 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
614 num_retries < kUnmountMaxNumOfRetries);
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800615 g_usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700616 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000617 return true;
618}
619
Darin Petkovd3f8c892010-10-12 21:38:45 -0700620bool GetFilesystemSize(const std::string& device,
621 int* out_block_count,
622 int* out_block_size) {
623 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
624 TEST_AND_RETURN_FALSE(fd >= 0);
625 ScopedFdCloser fd_closer(&fd);
626 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
627}
628
629bool GetFilesystemSizeFromFD(int fd,
630 int* out_block_count,
631 int* out_block_size) {
632 TEST_AND_RETURN_FALSE(fd >= 0);
633
634 // Determine the ext3 filesystem size by directly reading the block count and
635 // block size information from the superblock. See include/linux/ext3_fs.h for
636 // more details on the structure.
637 ssize_t kBufferSize = 16 * sizeof(uint32_t);
638 char buffer[kBufferSize];
639 const int kSuperblockOffset = 1024;
640 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
641 kBufferSize) {
642 PLOG(ERROR) << "Unable to determine file system size:";
643 return false;
644 }
645 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
646 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
647 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
648 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
649 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
650 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
651 block_count = le32toh(block_count);
652 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
653 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
654 magic = le16toh(magic);
655
656 // Sanity check the parameters.
657 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
658 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
659 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
660 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
661 int block_size = 1 << log_block_size;
662 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
663 block_size <= kExt3MaxBlockSize);
664 TEST_AND_RETURN_FALSE(block_count > 0);
665
666 if (out_block_count) {
667 *out_block_count = block_count;
668 }
669 if (out_block_size) {
670 *out_block_size = block_size;
671 }
672 return true;
673}
674
Alex Deymo032e7722014-03-25 17:53:56 -0700675// Tries to parse the header of an ELF file to obtain a human-readable
676// description of it on the |output| string.
677static bool GetFileFormatELF(const char* buffer, size_t size, string* output) {
678 // 0x00: EI_MAG - ELF magic header, 4 bytes.
679 if (size < 4 || memcmp(buffer, "\x7F""ELF", 4) != 0)
680 return false;
681 *output = "ELF";
682
683 // 0x04: EI_CLASS, 1 byte.
684 if (size < 0x04 + 1)
685 return true;
686 switch (buffer[4]) {
687 case 1:
688 *output += " 32-bit";
689 break;
690 case 2:
691 *output += " 64-bit";
692 break;
693 default:
694 *output += " ?-bit";
695 }
696
697 // 0x05: EI_DATA, endianness, 1 byte.
698 if (size < 0x05 + 1)
699 return true;
700 char ei_data = buffer[5];
701 switch (ei_data) {
702 case 1:
703 *output += " little-endian";
704 break;
705 case 2:
706 *output += " big-endian";
707 break;
708 default:
709 *output += " ?-endian";
710 // Don't parse anything after the 0x10 offset if endianness is unknown.
711 return true;
712 }
713
714 // 0x12: e_machine, 2 byte endianness based on ei_data
715 if (size < 0x12 + 2)
716 return true;
717 uint16 e_machine = *reinterpret_cast<const uint16*>(buffer+0x12);
718 // Fix endianess regardless of the host endianess.
719 if (ei_data == 1)
720 e_machine = le16toh(e_machine);
721 else
722 e_machine = be16toh(e_machine);
723
724 switch (e_machine) {
725 case 0x03:
726 *output += " x86";
727 break;
728 case 0x28:
729 *output += " arm";
730 break;
731 case 0x3E:
732 *output += " x86-64";
733 break;
734 default:
735 *output += " unknown-arch";
736 }
737 return true;
738}
739
740string GetFileFormat(const string& path) {
741 vector<char> buffer;
742 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
743 return "File not found.";
744
745 string result;
746 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
747 return result;
748
749 return "data";
750}
751
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700752bool GetBootloader(BootLoader* out_bootloader) {
753 // For now, hardcode to syslinux.
754 *out_bootloader = BootLoader_SYSLINUX;
755 return true;
756}
757
Darin Petkova0b9e772011-10-06 05:05:56 -0700758string GetAndFreeGError(GError** error) {
759 if (!*error) {
760 return "Unknown GLib error.";
761 }
762 string message =
763 base::StringPrintf("GError(%d): %s",
764 (*error)->code,
765 (*error)->message ? (*error)->message : "(unknown)");
766 g_error_free(*error);
767 *error = NULL;
768 return message;
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700769}
770
Darin Petkov296889c2010-07-23 16:20:54 -0700771bool Reboot() {
772 vector<string> command;
773 command.push_back("/sbin/shutdown");
774 command.push_back("-r");
775 command.push_back("now");
776 int rc = 0;
Darin Petkov85d02b72011-05-17 13:25:51 -0700777 Subprocess::SynchronousExec(command, &rc, NULL);
Darin Petkov296889c2010-07-23 16:20:54 -0700778 TEST_AND_RETURN_FALSE(rc == 0);
779 return true;
780}
781
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800782namespace {
783// Do the actual trigger. We do it as a main-loop callback to (try to) get a
784// consistent stack trace.
785gboolean TriggerCrashReporterUpload(void* unused) {
786 pid_t pid = fork();
787 CHECK(pid >= 0) << "fork failed"; // fork() failed. Something is very wrong.
788 if (pid == 0) {
789 // We are the child. Crash.
790 abort(); // never returns
791 }
792 // We are the parent. Wait for child to terminate.
793 pid_t result = waitpid(pid, NULL, 0);
794 LOG_IF(ERROR, result < 0) << "waitpid() failed";
795 return FALSE; // Don't call this callback again
796}
797} // namespace {}
798
799void ScheduleCrashReporterUpload() {
800 g_idle_add(&TriggerCrashReporterUpload, NULL);
801}
802
Chris Sosa4f8ee272012-11-30 13:01:54 -0800803bool SetCpuShares(CpuShares shares) {
804 string string_shares = base::IntToString(static_cast<int>(shares));
805 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
806 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
807 if(utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
808 string_shares.size())){
809 return true;
810 } else {
811 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
812 << " using " << cpu_shares_file;
813 return false;
814 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700815}
816
Chris Sosa4f8ee272012-11-30 13:01:54 -0800817int CompareCpuShares(CpuShares shares_lhs,
818 CpuShares shares_rhs) {
819 return static_cast<int>(shares_lhs) - static_cast<int>(shares_rhs);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700820}
821
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700822int FuzzInt(int value, unsigned int range) {
823 int min = value - range / 2;
824 int max = value + range - range / 2;
825 return base::RandInt(min, max);
826}
827
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800828gboolean GlibRunClosure(gpointer data) {
829 google::protobuf::Closure* callback =
830 reinterpret_cast<google::protobuf::Closure*>(data);
831 callback->Run();
832 return FALSE;
833}
834
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700835string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800836 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700837}
838
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800839string FormatTimeDelta(TimeDelta delta) {
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700840 // Canonicalize into days, hours, minutes, seconds and microseconds.
841 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800842 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700843 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800844 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700845 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800846 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700847 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800848 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700849 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800850
851 // Construct and return string.
852 string str;
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700853 if (days)
854 base::StringAppendF(&str, "%ud", days);
855 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800856 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700857 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800858 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700859 base::StringAppendF(&str, "%u", secs);
860 if (usecs) {
861 int width = 6;
862 while ((usecs / 10) * 10 == usecs) {
863 usecs /= 10;
864 width--;
865 }
866 base::StringAppendF(&str, ".%0*u", width, usecs);
867 }
868 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800869 return str;
870}
871
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700872string ToString(const Time utc_time) {
873 Time::Exploded exp_time;
874 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700875 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700876 exp_time.month,
877 exp_time.day_of_month,
878 exp_time.year,
879 exp_time.hour,
880 exp_time.minute,
881 exp_time.second);
882}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000883
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700884string ToString(bool b) {
885 return (b ? "true" : "false");
886}
887
Alex Deymo1c656c42013-06-28 11:02:14 -0700888string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700889 switch (source) {
890 case kDownloadSourceHttpsServer: return "HttpsServer";
891 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700892 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -0700893 case kNumDownloadSources: return "Unknown";
894 // Don't add a default case to let the compiler warn about newly added
895 // download sources which should be added here.
896 }
897
898 return "Unknown";
899}
900
Alex Deymo1c656c42013-06-28 11:02:14 -0700901string ToString(PayloadType payload_type) {
902 switch (payload_type) {
903 case kPayloadTypeDelta: return "Delta";
904 case kPayloadTypeFull: return "Full";
905 case kPayloadTypeForcedFull: return "ForcedFull";
906 case kNumPayloadTypes: return "Unknown";
907 // Don't add a default case to let the compiler warn about newly added
908 // payload types which should be added here.
909 }
910
911 return "Unknown";
912}
913
David Zeuthena99981f2013-04-29 13:42:47 -0700914ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700915 // Ignore the higher order bits in the code by applying the mask as
916 // we want the enumerations to be in the small contiguous range
David Zeuthena99981f2013-04-29 13:42:47 -0700917 // with values less than kErrorCodeUmaReportedMax.
918 ErrorCode base_code = static_cast<ErrorCode>(code & ~kErrorCodeSpecialFlags);
Jay Srinivasanf0572052012-10-23 18:12:56 -0700919
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800920 // Make additional adjustments required for UMA and error classification.
921 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
922 // chromium-os:34369.
David Zeuthena99981f2013-04-29 13:42:47 -0700923 if (base_code >= kErrorCodeOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700924 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800925 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800926 LOG(INFO) << "Converting error code " << base_code
David Zeuthena99981f2013-04-29 13:42:47 -0700927 << " to kErrorCodeOmahaErrorInHTTPResponse";
928 base_code = kErrorCodeOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700929 }
930
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800931 return base_code;
932}
933
David Zeuthen33bae492014-02-25 16:16:18 -0800934metrics::AttemptResult GetAttemptResult(ErrorCode code) {
935 ErrorCode base_code = static_cast<ErrorCode>(code & ~kErrorCodeSpecialFlags);
936
937 switch (base_code) {
938 case kErrorCodeSuccess:
939 return metrics::AttemptResult::kUpdateSucceeded;
940
941 case kErrorCodeDownloadTransferError:
942 return metrics::AttemptResult::kPayloadDownloadError;
943
944 case kErrorCodeDownloadInvalidMetadataSize:
945 case kErrorCodeDownloadInvalidMetadataMagicString:
946 case kErrorCodeDownloadMetadataSignatureError:
947 case kErrorCodeDownloadMetadataSignatureVerificationError:
948 case kErrorCodePayloadMismatchedType:
949 case kErrorCodeUnsupportedMajorPayloadVersion:
950 case kErrorCodeUnsupportedMinorPayloadVersion:
951 case kErrorCodeDownloadNewPartitionInfoError:
952 case kErrorCodeDownloadSignatureMissingInManifest:
953 case kErrorCodeDownloadManifestParseError:
954 case kErrorCodeDownloadOperationHashMissingError:
955 return metrics::AttemptResult::kMetadataMalformed;
956
957 case kErrorCodeDownloadOperationHashMismatch:
958 case kErrorCodeDownloadOperationHashVerificationError:
959 return metrics::AttemptResult::kOperationMalformed;
960
961 case kErrorCodeDownloadOperationExecutionError:
962 case kErrorCodeInstallDeviceOpenError:
963 case kErrorCodeKernelDeviceOpenError:
964 case kErrorCodeDownloadWriteError:
965 case kErrorCodeFilesystemCopierError:
966 return metrics::AttemptResult::kOperationExecutionError;
967
968 case kErrorCodeDownloadMetadataSignatureMismatch:
969 return metrics::AttemptResult::kMetadataVerificationFailed;
970
971 case kErrorCodePayloadSizeMismatchError:
972 case kErrorCodePayloadHashMismatchError:
973 case kErrorCodeDownloadPayloadVerificationError:
974 case kErrorCodeSignedDeltaPayloadExpectedError:
975 case kErrorCodeDownloadPayloadPubKeyVerificationError:
976 return metrics::AttemptResult::kPayloadVerificationFailed;
977
978 case kErrorCodeNewRootfsVerificationError:
979 case kErrorCodeNewKernelVerificationError:
980 return metrics::AttemptResult::kVerificationFailed;
981
982 case kErrorCodePostinstallRunnerError:
983 case kErrorCodePostinstallBootedFromFirmwareB:
984 case kErrorCodePostinstallFirmwareRONotUpdatable:
985 return metrics::AttemptResult::kPostInstallFailed;
986
987 // We should never get these errors in the update-attempt stage so
988 // return internal error if this happens.
989 case kErrorCodeError:
990 case kErrorCodeOmahaRequestXMLParseError:
991 case kErrorCodeOmahaRequestError:
992 case kErrorCodeOmahaResponseHandlerError:
993 case kErrorCodeDownloadStateInitializationError:
994 case kErrorCodeOmahaRequestEmptyResponseError:
995 case kErrorCodeDownloadInvalidMetadataSignature:
996 case kErrorCodeOmahaResponseInvalid:
997 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
998 case kErrorCodeOmahaUpdateDeferredPerPolicy:
999 case kErrorCodeOmahaErrorInHTTPResponse:
1000 case kErrorCodeDownloadMetadataSignatureMissingError:
1001 case kErrorCodeOmahaUpdateDeferredForBackoff:
1002 case kErrorCodePostinstallPowerwashError:
1003 case kErrorCodeUpdateCanceledByChannelChange:
1004 return metrics::AttemptResult::kInternalError;
1005
1006 // Special flags. These can't happen (we mask them out above) but
1007 // the compiler doesn't know that. Just break out so we can warn and
1008 // return |kInternalError|.
1009 case kErrorCodeUmaReportedMax:
1010 case kErrorCodeOmahaRequestHTTPResponseBase:
1011 case kErrorCodeDevModeFlag:
1012 case kErrorCodeResumedFlag:
1013 case kErrorCodeTestImageFlag:
1014 case kErrorCodeTestOmahaUrlFlag:
1015 case kErrorCodeSpecialFlags:
1016 break;
1017 }
1018
1019 LOG(ERROR) << "Unexpected error code " << base_code;
1020 return metrics::AttemptResult::kInternalError;
1021}
1022
1023
1024metrics::DownloadErrorCode GetDownloadErrorCode(ErrorCode code) {
1025 ErrorCode base_code = static_cast<ErrorCode>(code & ~kErrorCodeSpecialFlags);
1026
1027 if (base_code >= kErrorCodeOmahaRequestHTTPResponseBase) {
1028 int http_status = base_code - kErrorCodeOmahaRequestHTTPResponseBase;
1029 if (http_status >= 200 && http_status <= 599) {
1030 return static_cast<metrics::DownloadErrorCode>(
1031 static_cast<int>(metrics::DownloadErrorCode::kHttpStatus200) +
1032 http_status - 200);
1033 } else if (http_status == 0) {
1034 // The code is using HTTP Status 0 for "Unable to get http
1035 // response code."
1036 return metrics::DownloadErrorCode::kDownloadError;
1037 }
1038 LOG(WARNING) << "Unexpected HTTP status code " << http_status;
1039 return metrics::DownloadErrorCode::kHttpStatusOther;
1040 }
1041
1042 switch (base_code) {
1043 // Unfortunately, kErrorCodeDownloadTransferError is returned for a wide
1044 // variety of errors (proxy errors, host not reachable, timeouts etc.).
1045 //
1046 // For now just map that to kDownloading. See http://crbug.com/355745
1047 // for how we plan to add more detail in the future.
1048 case kErrorCodeDownloadTransferError:
1049 return metrics::DownloadErrorCode::kDownloadError;
1050
1051 // All of these error codes are not related to downloading so break
1052 // out so we can warn and return InputMalformed.
1053 case kErrorCodeSuccess:
1054 case kErrorCodeError:
1055 case kErrorCodeOmahaRequestError:
1056 case kErrorCodeOmahaResponseHandlerError:
1057 case kErrorCodeFilesystemCopierError:
1058 case kErrorCodePostinstallRunnerError:
1059 case kErrorCodePayloadMismatchedType:
1060 case kErrorCodeInstallDeviceOpenError:
1061 case kErrorCodeKernelDeviceOpenError:
1062 case kErrorCodePayloadHashMismatchError:
1063 case kErrorCodePayloadSizeMismatchError:
1064 case kErrorCodeDownloadPayloadVerificationError:
1065 case kErrorCodeDownloadNewPartitionInfoError:
1066 case kErrorCodeDownloadWriteError:
1067 case kErrorCodeNewRootfsVerificationError:
1068 case kErrorCodeNewKernelVerificationError:
1069 case kErrorCodeSignedDeltaPayloadExpectedError:
1070 case kErrorCodeDownloadPayloadPubKeyVerificationError:
1071 case kErrorCodePostinstallBootedFromFirmwareB:
1072 case kErrorCodeDownloadStateInitializationError:
1073 case kErrorCodeDownloadInvalidMetadataMagicString:
1074 case kErrorCodeDownloadSignatureMissingInManifest:
1075 case kErrorCodeDownloadManifestParseError:
1076 case kErrorCodeDownloadMetadataSignatureError:
1077 case kErrorCodeDownloadMetadataSignatureVerificationError:
1078 case kErrorCodeDownloadMetadataSignatureMismatch:
1079 case kErrorCodeDownloadOperationHashVerificationError:
1080 case kErrorCodeDownloadOperationExecutionError:
1081 case kErrorCodeDownloadOperationHashMismatch:
1082 case kErrorCodeOmahaRequestEmptyResponseError:
1083 case kErrorCodeOmahaRequestXMLParseError:
1084 case kErrorCodeDownloadInvalidMetadataSize:
1085 case kErrorCodeDownloadInvalidMetadataSignature:
1086 case kErrorCodeOmahaResponseInvalid:
1087 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
1088 case kErrorCodeOmahaUpdateDeferredPerPolicy:
1089 case kErrorCodeOmahaErrorInHTTPResponse:
1090 case kErrorCodeDownloadOperationHashMissingError:
1091 case kErrorCodeDownloadMetadataSignatureMissingError:
1092 case kErrorCodeOmahaUpdateDeferredForBackoff:
1093 case kErrorCodePostinstallPowerwashError:
1094 case kErrorCodeUpdateCanceledByChannelChange:
1095 case kErrorCodePostinstallFirmwareRONotUpdatable:
1096 case kErrorCodeUnsupportedMajorPayloadVersion:
1097 case kErrorCodeUnsupportedMinorPayloadVersion:
1098 break;
1099
1100 // Special flags. These can't happen (we mask them out above) but
1101 // the compiler doesn't know that. Just break out so we can warn and
1102 // return |kInputMalformed|.
1103 case kErrorCodeUmaReportedMax:
1104 case kErrorCodeOmahaRequestHTTPResponseBase:
1105 case kErrorCodeDevModeFlag:
1106 case kErrorCodeResumedFlag:
1107 case kErrorCodeTestImageFlag:
1108 case kErrorCodeTestOmahaUrlFlag:
1109 case kErrorCodeSpecialFlags:
1110 LOG(ERROR) << "Unexpected error code " << base_code;
1111 break;
1112 }
1113
1114 return metrics::DownloadErrorCode::kInputMalformed;
1115}
1116
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001117// Returns a printable version of the various flags denoted in the higher order
1118// bits of the given code. Returns an empty string if none of those bits are
1119// set.
1120string GetFlagNames(uint32_t code) {
David Zeuthena99981f2013-04-29 13:42:47 -07001121 uint32_t flags = code & kErrorCodeSpecialFlags;
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001122 string flag_names;
1123 string separator = "";
1124 for(size_t i = 0; i < sizeof(flags) * 8; i++) {
1125 uint32_t flag = flags & (1 << i);
1126 if (flag) {
David Zeuthena99981f2013-04-29 13:42:47 -07001127 flag_names += separator + CodeToString(static_cast<ErrorCode>(flag));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001128 separator = ", ";
1129 }
1130 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001131
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001132 return flag_names;
Jay Srinivasanf0572052012-10-23 18:12:56 -07001133}
1134
David Zeuthena99981f2013-04-29 13:42:47 -07001135void SendErrorCodeToUma(SystemState* system_state, ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001136 if (!system_state)
1137 return;
1138
David Zeuthena99981f2013-04-29 13:42:47 -07001139 ErrorCode uma_error_code = GetBaseErrorCode(code);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001140
1141 // If the code doesn't have flags computed already, compute them now based on
1142 // the state of the current update attempt.
David Zeuthena99981f2013-04-29 13:42:47 -07001143 uint32_t flags = code & kErrorCodeSpecialFlags;
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001144 if (!flags)
1145 flags = system_state->update_attempter()->GetErrorCodeFlags();
1146
1147 // Determine the UMA bucket depending on the flags. But, ignore the resumed
1148 // flag, as it's perfectly normal for production devices to resume their
1149 // downloads and so we want to record those cases also in NormalErrorCodes
1150 // bucket.
David Zeuthena99981f2013-04-29 13:42:47 -07001151 string metric = (flags & ~kErrorCodeResumedFlag) ?
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001152 "Installer.DevModeErrorCodes" : "Installer.NormalErrorCodes";
1153
1154 LOG(INFO) << "Sending error code " << uma_error_code
1155 << " (" << CodeToString(uma_error_code) << ")"
1156 << " to UMA metric: " << metric
1157 << ". Flags = " << (flags ? GetFlagNames(flags) : "None");
1158
1159 system_state->metrics_lib()->SendEnumToUMA(metric,
1160 uma_error_code,
David Zeuthena99981f2013-04-29 13:42:47 -07001161 kErrorCodeUmaReportedMax);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001162}
1163
David Zeuthena99981f2013-04-29 13:42:47 -07001164string CodeToString(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001165 // If the given code has both parts (i.e. the error code part and the flags
1166 // part) then strip off the flags part since the switch statement below
1167 // has case statements only for the base error code or a single flag but
1168 // doesn't support any combinations of those.
David Zeuthena99981f2013-04-29 13:42:47 -07001169 if ((code & kErrorCodeSpecialFlags) && (code & ~kErrorCodeSpecialFlags))
1170 code = static_cast<ErrorCode>(code & ~kErrorCodeSpecialFlags);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001171 switch (code) {
David Zeuthena99981f2013-04-29 13:42:47 -07001172 case kErrorCodeSuccess: return "kErrorCodeSuccess";
1173 case kErrorCodeError: return "kErrorCodeError";
1174 case kErrorCodeOmahaRequestError: return "kErrorCodeOmahaRequestError";
1175 case kErrorCodeOmahaResponseHandlerError:
1176 return "kErrorCodeOmahaResponseHandlerError";
1177 case kErrorCodeFilesystemCopierError:
1178 return "kErrorCodeFilesystemCopierError";
1179 case kErrorCodePostinstallRunnerError:
1180 return "kErrorCodePostinstallRunnerError";
Gilad Arnold21504f02013-05-24 08:51:22 -07001181 case kErrorCodePayloadMismatchedType:
1182 return "kErrorCodePayloadMismatchedType";
David Zeuthena99981f2013-04-29 13:42:47 -07001183 case kErrorCodeInstallDeviceOpenError:
1184 return "kErrorCodeInstallDeviceOpenError";
1185 case kErrorCodeKernelDeviceOpenError:
1186 return "kErrorCodeKernelDeviceOpenError";
1187 case kErrorCodeDownloadTransferError:
1188 return "kErrorCodeDownloadTransferError";
1189 case kErrorCodePayloadHashMismatchError:
1190 return "kErrorCodePayloadHashMismatchError";
1191 case kErrorCodePayloadSizeMismatchError:
1192 return "kErrorCodePayloadSizeMismatchError";
1193 case kErrorCodeDownloadPayloadVerificationError:
1194 return "kErrorCodeDownloadPayloadVerificationError";
1195 case kErrorCodeDownloadNewPartitionInfoError:
1196 return "kErrorCodeDownloadNewPartitionInfoError";
1197 case kErrorCodeDownloadWriteError:
1198 return "kErrorCodeDownloadWriteError";
1199 case kErrorCodeNewRootfsVerificationError:
1200 return "kErrorCodeNewRootfsVerificationError";
1201 case kErrorCodeNewKernelVerificationError:
1202 return "kErrorCodeNewKernelVerificationError";
1203 case kErrorCodeSignedDeltaPayloadExpectedError:
1204 return "kErrorCodeSignedDeltaPayloadExpectedError";
1205 case kErrorCodeDownloadPayloadPubKeyVerificationError:
1206 return "kErrorCodeDownloadPayloadPubKeyVerificationError";
1207 case kErrorCodePostinstallBootedFromFirmwareB:
1208 return "kErrorCodePostinstallBootedFromFirmwareB";
1209 case kErrorCodeDownloadStateInitializationError:
1210 return "kErrorCodeDownloadStateInitializationError";
1211 case kErrorCodeDownloadInvalidMetadataMagicString:
1212 return "kErrorCodeDownloadInvalidMetadataMagicString";
1213 case kErrorCodeDownloadSignatureMissingInManifest:
1214 return "kErrorCodeDownloadSignatureMissingInManifest";
1215 case kErrorCodeDownloadManifestParseError:
1216 return "kErrorCodeDownloadManifestParseError";
1217 case kErrorCodeDownloadMetadataSignatureError:
1218 return "kErrorCodeDownloadMetadataSignatureError";
1219 case kErrorCodeDownloadMetadataSignatureVerificationError:
1220 return "kErrorCodeDownloadMetadataSignatureVerificationError";
1221 case kErrorCodeDownloadMetadataSignatureMismatch:
1222 return "kErrorCodeDownloadMetadataSignatureMismatch";
1223 case kErrorCodeDownloadOperationHashVerificationError:
1224 return "kErrorCodeDownloadOperationHashVerificationError";
1225 case kErrorCodeDownloadOperationExecutionError:
1226 return "kErrorCodeDownloadOperationExecutionError";
1227 case kErrorCodeDownloadOperationHashMismatch:
1228 return "kErrorCodeDownloadOperationHashMismatch";
1229 case kErrorCodeOmahaRequestEmptyResponseError:
1230 return "kErrorCodeOmahaRequestEmptyResponseError";
1231 case kErrorCodeOmahaRequestXMLParseError:
1232 return "kErrorCodeOmahaRequestXMLParseError";
1233 case kErrorCodeDownloadInvalidMetadataSize:
1234 return "kErrorCodeDownloadInvalidMetadataSize";
1235 case kErrorCodeDownloadInvalidMetadataSignature:
1236 return "kErrorCodeDownloadInvalidMetadataSignature";
1237 case kErrorCodeOmahaResponseInvalid:
1238 return "kErrorCodeOmahaResponseInvalid";
1239 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
1240 return "kErrorCodeOmahaUpdateIgnoredPerPolicy";
1241 case kErrorCodeOmahaUpdateDeferredPerPolicy:
1242 return "kErrorCodeOmahaUpdateDeferredPerPolicy";
1243 case kErrorCodeOmahaErrorInHTTPResponse:
1244 return "kErrorCodeOmahaErrorInHTTPResponse";
1245 case kErrorCodeDownloadOperationHashMissingError:
1246 return "kErrorCodeDownloadOperationHashMissingError";
1247 case kErrorCodeDownloadMetadataSignatureMissingError:
1248 return "kErrorCodeDownloadMetadataSignatureMissingError";
1249 case kErrorCodeOmahaUpdateDeferredForBackoff:
1250 return "kErrorCodeOmahaUpdateDeferredForBackoff";
1251 case kErrorCodePostinstallPowerwashError:
1252 return "kErrorCodePostinstallPowerwashError";
1253 case kErrorCodeUpdateCanceledByChannelChange:
1254 return "kErrorCodeUpdateCanceledByChannelChange";
1255 case kErrorCodeUmaReportedMax:
1256 return "kErrorCodeUmaReportedMax";
1257 case kErrorCodeOmahaRequestHTTPResponseBase:
1258 return "kErrorCodeOmahaRequestHTTPResponseBase";
1259 case kErrorCodeResumedFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001260 return "Resumed";
David Zeuthena99981f2013-04-29 13:42:47 -07001261 case kErrorCodeDevModeFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001262 return "DevMode";
David Zeuthena99981f2013-04-29 13:42:47 -07001263 case kErrorCodeTestImageFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001264 return "TestImage";
David Zeuthena99981f2013-04-29 13:42:47 -07001265 case kErrorCodeTestOmahaUrlFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001266 return "TestOmahaUrl";
David Zeuthena99981f2013-04-29 13:42:47 -07001267 case kErrorCodeSpecialFlags:
1268 return "kErrorCodeSpecialFlags";
Don Garrett81018e02013-07-30 18:46:31 -07001269 case kErrorCodePostinstallFirmwareRONotUpdatable:
1270 return "kErrorCodePostinstallFirmwareRONotUpdatable";
Don Garrett4d039442013-10-28 18:40:06 -07001271 case kErrorCodeUnsupportedMajorPayloadVersion:
1272 return "kErrorCodeUnsupportedMajorPayloadVersion";
1273 case kErrorCodeUnsupportedMinorPayloadVersion:
1274 return "kErrorCodeUnsupportedMinorPayloadVersion";
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001275 // Don't add a default case to let the compiler warn about newly added
1276 // error codes which should be added here.
1277 }
1278
1279 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
1280}
Jay Srinivasanf0572052012-10-23 18:12:56 -07001281
Gilad Arnold30dedd82013-07-03 06:19:09 -07001282bool CreatePowerwashMarkerFile(const char* file_path) {
1283 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
1284 bool result = utils::WriteFile(marker_file,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001285 kPowerwashCommand,
1286 strlen(kPowerwashCommand));
Gilad Arnold30dedd82013-07-03 06:19:09 -07001287 if (result) {
1288 LOG(INFO) << "Created " << marker_file << " to powerwash on next reboot";
1289 } else {
1290 PLOG(ERROR) << "Error in creating powerwash marker file: " << marker_file;
1291 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001292
1293 return result;
1294}
1295
Gilad Arnold30dedd82013-07-03 06:19:09 -07001296bool DeletePowerwashMarkerFile(const char* file_path) {
1297 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
Alex Vakulenko75039d72014-03-25 12:36:28 -07001298 const base::FilePath kPowerwashMarkerPath(marker_file);
1299 bool result = base::DeleteFile(kPowerwashMarkerPath, false);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001300
1301 if (result)
1302 LOG(INFO) << "Successfully deleted the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001303 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001304 else
1305 PLOG(ERROR) << "Could not delete the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001306 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001307
1308 return result;
1309}
1310
Chris Sosad317e402013-06-12 13:47:09 -07001311bool GetInstallDev(const std::string& boot_dev, std::string* install_dev) {
1312 TEST_AND_RETURN_FALSE(StringHasPrefix(boot_dev, "/dev/"));
Liam McLoughlin049d1652013-07-31 18:47:46 -07001313 string::iterator it;
1314 string ubiblock_prefix("/dev/ubiblock");
1315
1316 install_dev->assign(boot_dev);
1317
1318 if(StringHasPrefix(boot_dev, ubiblock_prefix)) {
1319 // UBI-based device
1320 it = install_dev->begin() + ubiblock_prefix.length();
1321 } else {
1322 // non-UBI device
1323 it = install_dev->end() - 1; // last character in string
1324 }
1325
Chris Sosad317e402013-06-12 13:47:09 -07001326 // Right now, we just switch '3' and '5' partition numbers.
Liam McLoughlin049d1652013-07-31 18:47:46 -07001327 TEST_AND_RETURN_FALSE(*it == '3' || *it == '5');
1328 *it = (*it == '3' ? '5' : '3');
1329
Chris Sosad317e402013-06-12 13:47:09 -07001330 return true;
1331}
1332
David Zeuthen27a48bc2013-08-06 12:06:29 -07001333Time TimeFromStructTimespec(struct timespec *ts) {
1334 int64 us = static_cast<int64>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
1335 static_cast<int64>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
1336 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
1337}
1338
1339gchar** StringVectorToGStrv(const vector<string> &vector) {
1340 GPtrArray *p = g_ptr_array_new();
1341 for (std::vector<string>::const_iterator i = vector.begin();
1342 i != vector.end(); ++i) {
1343 g_ptr_array_add(p, g_strdup(i->c_str()));
1344 }
1345 g_ptr_array_add(p, NULL);
1346 return reinterpret_cast<gchar**>(g_ptr_array_free(p, FALSE));
1347}
1348
1349string StringVectorToString(const vector<string> &vector) {
1350 string str = "[";
1351 for (std::vector<string>::const_iterator i = vector.begin();
1352 i != vector.end(); ++i) {
1353 if (i != vector.begin())
1354 str += ", ";
1355 str += '"';
1356 str += *i;
1357 str += '"';
1358 }
1359 str += "]";
1360 return str;
1361}
1362
David Zeuthen8f191b22013-08-06 12:27:50 -07001363string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
1364 string encoded_hash;
1365 OmahaHashCalculator::Base64Encode(payload_hash.c_str(),
1366 payload_hash.size(),
1367 &encoded_hash);
Alex Vakulenko75039d72014-03-25 12:36:28 -07001368 return base::StringPrintf("cros_update_size_%zu_hash_%s",
David Zeuthen8f191b22013-08-06 12:27:50 -07001369 payload_size,
1370 encoded_hash.c_str());
1371}
1372
David Zeuthen910ec5b2013-09-26 12:10:58 -07001373bool IsXAttrSupported(const base::FilePath& dir_path) {
1374 char *path = strdup(dir_path.Append("xattr_test_XXXXXX").value().c_str());
1375
1376 int fd = mkstemp(path);
1377 if (fd == -1) {
1378 PLOG(ERROR) << "Error creating temporary file in " << dir_path.value();
1379 free(path);
1380 return false;
1381 }
1382
1383 if (unlink(path) != 0) {
1384 PLOG(ERROR) << "Error unlinking temporary file " << path;
1385 close(fd);
1386 free(path);
1387 return false;
1388 }
1389
1390 int xattr_res = fsetxattr(fd, "user.xattr-test", "value", strlen("value"), 0);
1391 if (xattr_res != 0) {
1392 if (errno == ENOTSUP) {
1393 // Leave it to call-sites to warn about non-support.
1394 } else {
1395 PLOG(ERROR) << "Error setting xattr on " << path;
1396 }
1397 }
1398 close(fd);
1399 free(path);
1400 return xattr_res == 0;
1401}
1402
David Zeuthene7f89172013-10-31 10:21:04 -07001403bool DecodeAndStoreBase64String(const std::string& base64_encoded,
1404 base::FilePath *out_path) {
1405 vector<char> contents;
1406
1407 out_path->clear();
1408
1409 if (base64_encoded.size() == 0) {
1410 LOG(ERROR) << "Can't decode empty string.";
1411 return false;
1412 }
1413
1414 if (!OmahaHashCalculator::Base64Decode(base64_encoded, &contents) ||
1415 contents.size() == 0) {
1416 LOG(ERROR) << "Error decoding base64.";
1417 return false;
1418 }
1419
Alex Vakulenko75039d72014-03-25 12:36:28 -07001420 FILE *file = base::CreateAndOpenTemporaryFile(out_path);
David Zeuthene7f89172013-10-31 10:21:04 -07001421 if (file == NULL) {
1422 LOG(ERROR) << "Error creating temporary file.";
1423 return false;
1424 }
1425
1426 if (fwrite(&contents[0], 1, contents.size(), file) != contents.size()) {
1427 PLOG(ERROR) << "Error writing to temporary file.";
1428 if (fclose(file) != 0)
1429 PLOG(ERROR) << "Error closing temporary file.";
1430 if (unlink(out_path->value().c_str()) != 0)
1431 PLOG(ERROR) << "Error unlinking temporary file.";
1432 out_path->clear();
1433 return false;
1434 }
1435
1436 if (fclose(file) != 0) {
1437 PLOG(ERROR) << "Error closing temporary file.";
1438 out_path->clear();
1439 return false;
1440 }
1441
1442 return true;
1443}
1444
David Zeuthen639aa362014-02-03 16:23:44 -08001445bool ConvertToOmahaInstallDate(base::Time time, int *out_num_days) {
1446 time_t unix_time = time.ToTimeT();
1447 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
1448 const time_t kOmahaEpoch = 1167638400;
1449 const int64_t kNumSecondsPerWeek = 7*24*3600;
1450 const int64_t kNumDaysPerWeek = 7;
1451
1452 time_t omaha_time = unix_time - kOmahaEpoch;
1453
1454 if (omaha_time < 0)
1455 return false;
1456
1457 // Note, as per the comment in utils.h we are deliberately not
1458 // handling DST correctly.
1459
1460 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
1461 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
1462
1463 return true;
1464}
1465
David Zeuthen33bae492014-02-25 16:16:18 -08001466bool WallclockDurationHelper(SystemState* system_state,
1467 const std::string& state_variable_key,
1468 base::TimeDelta* out_duration) {
1469 bool ret = false;
1470
1471 base::Time now = system_state->clock()->GetWallclockTime();
1472 int64_t stored_value;
1473 if (system_state->prefs()->GetInt64(state_variable_key, &stored_value)) {
1474 base::Time stored_time = base::Time::FromInternalValue(stored_value);
1475 if (stored_time > now) {
1476 LOG(ERROR) << "Stored time-stamp used for " << state_variable_key
1477 << " is in the future.";
1478 } else {
1479 *out_duration = now - stored_time;
1480 ret = true;
1481 }
1482 }
1483
1484 if (!system_state->prefs()->SetInt64(state_variable_key,
1485 now.ToInternalValue())) {
1486 LOG(ERROR) << "Error storing time-stamp in " << state_variable_key;
1487 }
1488
1489 return ret;
1490}
1491
1492bool MonotonicDurationHelper(SystemState* system_state,
1493 int64_t* storage,
1494 base::TimeDelta* out_duration) {
1495 bool ret = false;
1496
1497 base::Time now = system_state->clock()->GetMonotonicTime();
1498 if (*storage != 0) {
1499 base::Time stored_time = base::Time::FromInternalValue(*storage);
1500 *out_duration = now - stored_time;
1501 ret = true;
1502 }
1503 *storage = now.ToInternalValue();
1504
1505 return ret;
1506}
1507
adlr@google.com3defe6a2009-12-04 20:57:17 +00001508} // namespace utils
1509
1510} // namespace chromeos_update_engine