blob: f23f31f6a0b80045c999a5f161c10d4c608f19c8 [file] [log] [blame]
Mike Frysinger8155d082012-04-06 15:23:18 -04001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
adlr@google.com3defe6a2009-12-04 20:57:17 +00002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "update_engine/utils.h"
Darin Petkovf74eb652010-08-04 12:08:38 -07006
David Zeuthen910ec5b2013-09-26 12:10:58 -07007#include <attr/xattr.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +00008#include <sys/mount.h>
Darin Petkovc6c135c2010-08-11 13:36:18 -07009#include <sys/resource.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000010#include <sys/stat.h>
11#include <sys/types.h>
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -080012#include <sys/wait.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000013#include <dirent.h>
14#include <errno.h>
Andrew de los Reyes970bb282009-12-09 16:34:04 -080015#include <fcntl.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000016#include <stdio.h>
17#include <stdlib.h>
18#include <string.h>
19#include <unistd.h>
Darin Petkovf74eb652010-08-04 12:08:38 -070020
adlr@google.com3defe6a2009-12-04 20:57:17 +000021#include <algorithm>
Chris Sosac1972482013-04-30 22:31:10 -070022#include <vector>
Darin Petkovf74eb652010-08-04 12:08:38 -070023
Will Drewry8f71da82010-08-30 14:07:11 -050024#include <base/file_path.h>
25#include <base/file_util.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040026#include <base/logging.h>
Chris Sosafc661a12013-02-26 14:43:21 -080027#include <base/posix/eintr_wrapper.h>
Will Drewry8f71da82010-08-30 14:07:11 -050028#include <base/rand_util.h>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070029#include <base/string_number_conversions.h>
Chris Sosac1972482013-04-30 22:31:10 -070030#include <base/string_split.h>
Will Drewry8f71da82010-08-30 14:07:11 -050031#include <base/string_util.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040032#include <base/stringprintf.h>
Gilad Arnold8e3f1262013-01-08 14:59:54 -080033#include <glib.h>
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -080034#include <google/protobuf/stubs/common.h>
Will Drewry8f71da82010-08-30 14:07:11 -050035
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070036#include "update_engine/constants.h"
Andrew de los Reyes970bb282009-12-09 16:34:04 -080037#include "update_engine/file_writer.h"
Darin Petkov33d30642010-08-04 10:18:57 -070038#include "update_engine/omaha_request_params.h"
Darin Petkov296889c2010-07-23 16:20:54 -070039#include "update_engine/subprocess.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080040#include "update_engine/system_state.h"
41#include "update_engine/update_attempter.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000042
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070043using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080044using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000045using std::min;
Chris Sosac1972482013-04-30 22:31:10 -070046using std::pair;
adlr@google.com3defe6a2009-12-04 20:57:17 +000047using std::string;
48using std::vector;
49
50namespace chromeos_update_engine {
51
Ben Chan77a1eba2012-10-07 22:54:55 -070052namespace {
53
54// The following constants control how UnmountFilesystem should retry if
55// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
56// one second.
57const int kUnmountMaxNumOfRetries = 5;
58const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Ben Chan77a1eba2012-10-07 22:54:55 -070059} // namespace
60
adlr@google.com3defe6a2009-12-04 20:57:17 +000061namespace utils {
62
Darin Petkova07586b2010-10-20 13:41:15 -070063static const char kDevImageMarker[] = "/root/.dev_mode";
Darin Petkov2a0e6332010-09-24 14:43:41 -070064
Chris Sosa4f8ee272012-11-30 13:01:54 -080065// Cgroup container is created in update-engine's upstart script located at
66// /etc/init/update-engine.conf.
67static const char kCGroupDir[] = "/sys/fs/cgroup/cpu/update-engine";
68
Darin Petkov33d30642010-08-04 10:18:57 -070069bool IsOfficialBuild() {
Darin Petkova07586b2010-10-20 13:41:15 -070070 return !file_util::PathExists(FilePath(kDevImageMarker));
Darin Petkov33d30642010-08-04 10:18:57 -070071}
72
Darin Petkovc91dd6b2011-01-10 12:31:34 -080073bool IsNormalBootMode() {
Darin Petkov44d98d92011-03-21 16:08:11 -070074 // TODO(petkov): Convert to a library call once a crossystem library is
75 // available (crosbug.com/13291).
76 int exit_code = 0;
77 vector<string> cmd(1, "/usr/bin/crossystem");
78 cmd.push_back("devsw_boot?1");
79
80 // Assume dev mode if the dev switch is set to 1 and there was no error
81 // executing crossystem. Assume normal mode otherwise.
Darin Petkov85d02b72011-05-17 13:25:51 -070082 bool success = Subprocess::SynchronousExec(cmd, &exit_code, NULL);
Darin Petkov44d98d92011-03-21 16:08:11 -070083 bool dev_mode = success && exit_code == 0;
84 LOG_IF(INFO, dev_mode) << "Booted in dev mode.";
85 return !dev_mode;
Darin Petkovc91dd6b2011-01-10 12:31:34 -080086}
87
Chris Sosac1972482013-04-30 22:31:10 -070088string ReadValueFromCrosSystem(const string& key){
Darin Petkovf2065b42011-05-17 16:36:27 -070089 int exit_code = 0;
90 vector<string> cmd(1, "/usr/bin/crossystem");
Chris Sosac1972482013-04-30 22:31:10 -070091 cmd.push_back(key);
Darin Petkovf2065b42011-05-17 16:36:27 -070092
Chris Sosac1972482013-04-30 22:31:10 -070093 string return_value;
94 bool success = Subprocess::SynchronousExec(cmd, &exit_code, &return_value);
Darin Petkovf2065b42011-05-17 16:36:27 -070095 if (success && !exit_code) {
Chris Sosac1972482013-04-30 22:31:10 -070096 TrimWhitespaceASCII(return_value, TRIM_ALL, &return_value);
97 return return_value;
Darin Petkovf2065b42011-05-17 16:36:27 -070098 }
Chris Sosac1972482013-04-30 22:31:10 -070099 LOG(ERROR) << "Unable to read " << key << " (" << exit_code << ") "
100 << return_value;
Darin Petkovf2065b42011-05-17 16:36:27 -0700101 return "";
102}
103
Chris Sosac1972482013-04-30 22:31:10 -0700104string GetHardwareClass() {
105 return ReadValueFromCrosSystem("hwid");
106}
107
108string GetFirmwareVersion() {
109 return ReadValueFromCrosSystem("fwid");
110}
111
J. Richard Barnette63137e52013-10-28 10:57:29 -0700112string GetECVersion() {
113 int exit_code = 0;
114 vector<string> cmd(1, "/usr/sbin/mosys");
115 cmd.push_back("-k");
116 cmd.push_back("ec");
117 cmd.push_back("info");
Chris Sosac1972482013-04-30 22:31:10 -0700118
J. Richard Barnette63137e52013-10-28 10:57:29 -0700119 string input_line;
120 bool success = Subprocess::SynchronousExec(cmd, &exit_code, &input_line);
121 if (!success || exit_code) {
122 LOG(ERROR) << "Unable to read ec info from mosys (" << exit_code << ")";
123 return "";
Chris Sosac1972482013-04-30 22:31:10 -0700124 }
125
J. Richard Barnette63137e52013-10-28 10:57:29 -0700126 return ParseECVersion(input_line);
127}
128
129string ParseECVersion(string input_line) {
130 TrimWhitespaceASCII(input_line, TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -0700131
132 // At this point we want to conver the format key=value pair from mosys to
133 // a vector of key value pairs.
134 vector<pair<string, string> > kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -0700135 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Chris Sosac1972482013-04-30 22:31:10 -0700136 for (vector<pair<string, string> >::iterator it = kv_pairs.begin();
137 it != kv_pairs.end(); ++it) {
138 // Finally match against the fw_verion which may have quotes.
139 if (it->first == "fw_version") {
140 string output;
141 // Trim any quotes.
142 TrimString(it->second, "\"", &output);
143 return output;
144 }
145 }
146 }
147 LOG(ERROR) << "Unable to parse fwid from ec info.";
148 return "";
149}
150
151
J. Richard Barnette30842932013-10-28 15:04:23 -0700152const string KernelDeviceOfBootDevice(const std::string& boot_device) {
153 if (boot_device.empty())
154 return boot_device;
155
156 string ubiblock_prefix("/dev/ubiblock");
157 string ret;
158 char partition_num;
159 if (StringHasPrefix(boot_device, ubiblock_prefix)) {
160 // eg: /dev/ubiblock3_0 becomes /dev/mtdblock2
161 ret = "/dev/mtdblock";
162 partition_num = boot_device[ubiblock_prefix.size()];
163 } else {
164 // eg: /dev/sda3 becomes /dev/sda2
165 // eg: /dev/mmcblk0p3 becomes /dev/mmcblk0p2
166 ret = boot_device.substr(0, boot_device.size() - 1);
167 partition_num = boot_device[boot_device.size() - 1];
168 }
169
170 // Currently this assumes the partition number of the boot device is
171 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
172 // get the kernel device.
173 if (partition_num == '3' || partition_num == '5' || partition_num == '7') {
174 ret.append(1, partition_num - 1);
175 return ret;
176 }
177
178 return "";
179}
180
181
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800182bool WriteFile(const char* path, const char* data, int data_len) {
183 DirectFileWriter writer;
184 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
185 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700186 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800187 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800188 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800189 return true;
190}
191
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700192bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700193 const char* c_buf = static_cast<const char*>(buf);
194 ssize_t bytes_written = 0;
195 while (bytes_written < static_cast<ssize_t>(count)) {
196 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
197 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
198 bytes_written += rc;
199 }
200 return true;
201}
202
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700203bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
204 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700205 size_t bytes_written = 0;
206 int num_attempts = 0;
207 while (bytes_written < count) {
208 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700209 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
210 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700211 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
212 if (rc < 0) {
213 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
214 << " bytes_written=" << bytes_written
215 << " count=" << count << " offset=" << offset;
216 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700217 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
218 bytes_written += rc;
219 }
220 return true;
221}
222
223bool PReadAll(int fd, void* buf, size_t count, off_t offset,
224 ssize_t* out_bytes_read) {
225 char* c_buf = static_cast<char*>(buf);
226 ssize_t bytes_read = 0;
227 while (bytes_read < static_cast<ssize_t>(count)) {
228 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
229 offset + bytes_read);
230 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
231 if (rc == 0) {
232 break;
233 }
234 bytes_read += rc;
235 }
236 *out_bytes_read = bytes_read;
237 return true;
Darin Petkov296889c2010-07-23 16:20:54 -0700238
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700239}
240
Gilad Arnold19a45f02012-07-19 12:36:10 -0700241// Append |nbytes| of content from |buf| to the vector pointed to by either
242// |vec_p| or |str_p|.
243static void AppendBytes(const char* buf, size_t nbytes,
244 std::vector<char>* vec_p) {
245 CHECK(buf);
246 CHECK(vec_p);
247 vec_p->insert(vec_p->end(), buf, buf + nbytes);
248}
249static void AppendBytes(const char* buf, size_t nbytes,
250 std::string* str_p) {
251 CHECK(buf);
252 CHECK(str_p);
253 str_p->append(buf, nbytes);
254}
255
256// Reads from an open file |fp|, appending the read content to the container
257// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200258// file's content, false otherwise. If |size| is not -1, reads up to |size|
259// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700260template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200261static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700262 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200263 CHECK(size == -1 || size >= 0);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700264 char buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200265 while (size == -1 || size > 0) {
266 off_t bytes_to_read = sizeof(buf);
267 if (size > 0 && bytes_to_read > size) {
268 bytes_to_read = size;
269 }
270 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
271 if (!nbytes) {
272 break;
273 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700274 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200275 if (size != -1) {
276 CHECK(size >= static_cast<off_t>(nbytes));
277 size -= nbytes;
278 }
279 }
280 if (ferror(fp)) {
281 return false;
282 }
283 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700284}
285
Darin Petkov8e447e02013-04-16 16:23:50 +0200286// Opens a file |path| for reading and appends its the contents to a container
287// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
288// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700289template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200290static bool ReadFileChunkAndAppend(const std::string& path,
291 off_t offset,
292 off_t size,
293 T* out_p) {
294 CHECK_GE(offset, 0);
295 CHECK(size == -1 || size >= 0);
296 file_util::ScopedFILE fp(fopen(path.c_str(), "r"));
297 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000298 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200299 if (offset) {
300 // Return success without appending any data if a chunk beyond the end of
301 // the file is requested.
302 if (offset >= FileSize(path)) {
303 return true;
304 }
305 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
306 }
307 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000308}
309
Gilad Arnold19a45f02012-07-19 12:36:10 -0700310// Invokes a pipe |cmd|, then uses |append_func| to append its stdout to a
311// container |out_p|.
312template <class T>
313static bool ReadPipeAndAppend(const std::string& cmd, T* out_p) {
314 FILE* fp = popen(cmd.c_str(), "r");
315 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000316 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200317 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700318 return (success && pclose(fp) >= 0);
319}
320
321
Darin Petkov8e447e02013-04-16 16:23:50 +0200322bool ReadFile(const string& path, vector<char>* out_p) {
323 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700324}
325
Darin Petkov8e447e02013-04-16 16:23:50 +0200326bool ReadFile(const string& path, string* out_p) {
327 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700328}
329
Darin Petkov8e447e02013-04-16 16:23:50 +0200330bool ReadFileChunk(const string& path, off_t offset, off_t size,
331 vector<char>* out_p) {
332 return ReadFileChunkAndAppend(path, offset, size, out_p);
333}
334
335bool ReadPipe(const string& cmd, vector<char>* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700336 return ReadPipeAndAppend(cmd, out_p);
337}
338
Darin Petkov8e447e02013-04-16 16:23:50 +0200339bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700340 return ReadPipeAndAppend(cmd, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000341}
342
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700343off_t FileSize(const string& path) {
344 struct stat stbuf;
345 int rc = stat(path.c_str(), &stbuf);
346 CHECK_EQ(rc, 0);
347 if (rc < 0)
348 return rc;
349 return stbuf.st_size;
350}
351
adlr@google.com3defe6a2009-12-04 20:57:17 +0000352void HexDumpArray(const unsigned char* const arr, const size_t length) {
353 const unsigned char* const char_arr =
354 reinterpret_cast<const unsigned char* const>(arr);
355 LOG(INFO) << "Logging array of length: " << length;
356 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700357 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000358 const unsigned int bytes_remaining = length - i;
359 const unsigned int bytes_per_this_line = min(bytes_per_line,
360 bytes_remaining);
361 char header[100];
362 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
363 TEST_AND_RETURN(r == 13);
364 string line = header;
365 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
366 char buf[20];
367 unsigned char c = char_arr[i + j];
368 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
369 TEST_AND_RETURN(r == 3);
370 line += buf;
371 }
372 LOG(INFO) << line;
373 }
374}
375
376namespace {
377class ScopedDirCloser {
378 public:
379 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
380 ~ScopedDirCloser() {
381 if (dir_ && *dir_) {
382 int r = closedir(*dir_);
383 TEST_AND_RETURN_ERRNO(r == 0);
384 *dir_ = NULL;
385 dir_ = NULL;
386 }
387 }
388 private:
389 DIR** dir_;
390};
391} // namespace {}
392
393bool RecursiveUnlinkDir(const std::string& path) {
394 struct stat stbuf;
395 int r = lstat(path.c_str(), &stbuf);
396 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
397 if ((r < 0) && (errno == ENOENT))
398 // path request is missing. that's fine.
399 return true;
400 if (!S_ISDIR(stbuf.st_mode)) {
401 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700402 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000403 // success or path disappeared before we could unlink.
404 return true;
405 }
406 {
407 // We have a dir, unlink all children, then delete dir
408 DIR *dir = opendir(path.c_str());
409 TEST_AND_RETURN_FALSE_ERRNO(dir);
410 ScopedDirCloser dir_closer(&dir);
411 struct dirent dir_entry;
412 struct dirent *dir_entry_p;
413 int err = 0;
414 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
415 if (dir_entry_p == NULL) {
416 // end of stream reached
417 break;
418 }
419 // Skip . and ..
420 if (!strcmp(dir_entry_p->d_name, ".") ||
421 !strcmp(dir_entry_p->d_name, ".."))
422 continue;
423 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700424 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000425 }
426 TEST_AND_RETURN_FALSE(err == 0);
427 }
428 // unlink dir
429 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
430 return true;
431}
432
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700433string RootDevice(const string& partition_device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700434 FilePath device_path(partition_device);
435 if (device_path.DirName().value() != "/dev") {
436 return "";
437 }
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700438 string::const_iterator it = --partition_device.end();
439 for (; it >= partition_device.begin(); --it) {
440 if (!isdigit(*it))
441 break;
442 }
443 // Some devices contain a p before the partitions. For example:
444 // /dev/mmc0p4 should be shortened to /dev/mmc0.
445 if (*it == 'p')
446 --it;
447 return string(partition_device.begin(), it + 1);
448}
449
450string PartitionNumber(const string& partition_device) {
451 CHECK(!partition_device.empty());
452 string::const_iterator it = --partition_device.end();
453 for (; it >= partition_device.begin(); --it) {
454 if (!isdigit(*it))
455 break;
456 }
457 return string(it + 1, partition_device.end());
458}
459
Darin Petkovf74eb652010-08-04 12:08:38 -0700460string SysfsBlockDevice(const string& device) {
461 FilePath device_path(device);
462 if (device_path.DirName().value() != "/dev") {
463 return "";
464 }
465 return FilePath("/sys/block").Append(device_path.BaseName()).value();
466}
467
468bool IsRemovableDevice(const std::string& device) {
469 string sysfs_block = SysfsBlockDevice(device);
470 string removable;
471 if (sysfs_block.empty() ||
472 !file_util::ReadFileToString(FilePath(sysfs_block).Append("removable"),
473 &removable)) {
474 return false;
475 }
476 TrimWhitespaceASCII(removable, TRIM_ALL, &removable);
477 return removable == "1";
478}
479
adlr@google.com3defe6a2009-12-04 20:57:17 +0000480std::string ErrnoNumberAsString(int err) {
481 char buf[100];
482 buf[0] = '\0';
483 return strerror_r(err, buf, sizeof(buf));
484}
485
486std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
487 string ret;
488 bool last_insert_was_slash = false;
489 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
490 if (*it == '/') {
491 if (last_insert_was_slash)
492 continue;
493 last_insert_was_slash = true;
494 } else {
495 last_insert_was_slash = false;
496 }
497 ret.push_back(*it);
498 }
499 if (strip_trailing_slash && last_insert_was_slash) {
500 string::size_type last_non_slash = ret.find_last_not_of('/');
501 if (last_non_slash != string::npos) {
502 ret.resize(last_non_slash + 1);
503 } else {
504 ret = "";
505 }
506 }
507 return ret;
508}
509
510bool FileExists(const char* path) {
511 struct stat stbuf;
512 return 0 == lstat(path, &stbuf);
513}
514
Darin Petkov30291ed2010-11-12 10:23:06 -0800515bool IsSymlink(const char* path) {
516 struct stat stbuf;
517 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
518}
519
adlr@google.com3defe6a2009-12-04 20:57:17 +0000520std::string TempFilename(string path) {
521 static const string suffix("XXXXXX");
522 CHECK(StringHasSuffix(path, suffix));
523 do {
524 string new_suffix;
525 for (unsigned int i = 0; i < suffix.size(); i++) {
526 int r = rand() % (26 * 2 + 10); // [a-zA-Z0-9]
527 if (r < 26)
528 new_suffix.append(1, 'a' + r);
529 else if (r < (26 * 2))
530 new_suffix.append(1, 'A' + r - 26);
531 else
532 new_suffix.append(1, '0' + r - (26 * 2));
533 }
534 CHECK_EQ(new_suffix.size(), suffix.size());
535 path.resize(path.size() - new_suffix.size());
536 path.append(new_suffix);
537 } while (FileExists(path.c_str()));
538 return path;
539}
540
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700541bool MakeTempFile(const std::string& filename_template,
542 std::string* filename,
543 int* fd) {
544 DCHECK(filename || fd);
545 vector<char> buf(filename_template.size() + 1);
546 memcpy(&buf[0], filename_template.data(), filename_template.size());
547 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700548
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700549 int mkstemp_fd = mkstemp(&buf[0]);
550 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
551 if (filename) {
552 *filename = &buf[0];
553 }
554 if (fd) {
555 *fd = mkstemp_fd;
556 } else {
557 close(mkstemp_fd);
558 }
559 return true;
560}
561
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700562bool MakeTempDirectory(const std::string& dirname_template,
563 std::string* dirname) {
564 DCHECK(dirname);
565 vector<char> buf(dirname_template.size() + 1);
566 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
567 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700568
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700569 char* return_code = mkdtemp(&buf[0]);
570 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
571 *dirname = &buf[0];
572 return true;
573}
574
adlr@google.com3defe6a2009-12-04 20:57:17 +0000575bool StringHasSuffix(const std::string& str, const std::string& suffix) {
576 if (suffix.size() > str.size())
577 return false;
578 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
579}
580
581bool StringHasPrefix(const std::string& str, const std::string& prefix) {
582 if (prefix.size() > str.size())
583 return false;
584 return 0 == str.compare(0, prefix.size(), prefix);
585}
586
adlr@google.com3defe6a2009-12-04 20:57:17 +0000587bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700588 const string& mountpoint,
589 unsigned long mountflags) {
590 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000591 if (rc < 0) {
592 string msg = ErrnoNumberAsString(errno);
593 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
594 << device << " on " << mountpoint;
595 return false;
596 }
597 return true;
598}
599
600bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700601 for (int num_retries = 0; ; ++num_retries) {
602 if (umount(mountpoint.c_str()) == 0)
603 break;
604
605 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
606 num_retries < kUnmountMaxNumOfRetries);
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800607 g_usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700608 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000609 return true;
610}
611
Darin Petkovd3f8c892010-10-12 21:38:45 -0700612bool GetFilesystemSize(const std::string& device,
613 int* out_block_count,
614 int* out_block_size) {
615 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
616 TEST_AND_RETURN_FALSE(fd >= 0);
617 ScopedFdCloser fd_closer(&fd);
618 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
619}
620
621bool GetFilesystemSizeFromFD(int fd,
622 int* out_block_count,
623 int* out_block_size) {
624 TEST_AND_RETURN_FALSE(fd >= 0);
625
626 // Determine the ext3 filesystem size by directly reading the block count and
627 // block size information from the superblock. See include/linux/ext3_fs.h for
628 // more details on the structure.
629 ssize_t kBufferSize = 16 * sizeof(uint32_t);
630 char buffer[kBufferSize];
631 const int kSuperblockOffset = 1024;
632 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
633 kBufferSize) {
634 PLOG(ERROR) << "Unable to determine file system size:";
635 return false;
636 }
637 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
638 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
639 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
640 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
641 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
642 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
643 block_count = le32toh(block_count);
644 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
645 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
646 magic = le16toh(magic);
647
648 // Sanity check the parameters.
649 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
650 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
651 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
652 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
653 int block_size = 1 << log_block_size;
654 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
655 block_size <= kExt3MaxBlockSize);
656 TEST_AND_RETURN_FALSE(block_count > 0);
657
658 if (out_block_count) {
659 *out_block_count = block_count;
660 }
661 if (out_block_size) {
662 *out_block_size = block_size;
663 }
664 return true;
665}
666
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700667bool GetBootloader(BootLoader* out_bootloader) {
668 // For now, hardcode to syslinux.
669 *out_bootloader = BootLoader_SYSLINUX;
670 return true;
671}
672
Darin Petkova0b9e772011-10-06 05:05:56 -0700673string GetAndFreeGError(GError** error) {
674 if (!*error) {
675 return "Unknown GLib error.";
676 }
677 string message =
678 base::StringPrintf("GError(%d): %s",
679 (*error)->code,
680 (*error)->message ? (*error)->message : "(unknown)");
681 g_error_free(*error);
682 *error = NULL;
683 return message;
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700684}
685
Darin Petkov296889c2010-07-23 16:20:54 -0700686bool Reboot() {
687 vector<string> command;
688 command.push_back("/sbin/shutdown");
689 command.push_back("-r");
690 command.push_back("now");
691 int rc = 0;
Darin Petkov85d02b72011-05-17 13:25:51 -0700692 Subprocess::SynchronousExec(command, &rc, NULL);
Darin Petkov296889c2010-07-23 16:20:54 -0700693 TEST_AND_RETURN_FALSE(rc == 0);
694 return true;
695}
696
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800697namespace {
698// Do the actual trigger. We do it as a main-loop callback to (try to) get a
699// consistent stack trace.
700gboolean TriggerCrashReporterUpload(void* unused) {
701 pid_t pid = fork();
702 CHECK(pid >= 0) << "fork failed"; // fork() failed. Something is very wrong.
703 if (pid == 0) {
704 // We are the child. Crash.
705 abort(); // never returns
706 }
707 // We are the parent. Wait for child to terminate.
708 pid_t result = waitpid(pid, NULL, 0);
709 LOG_IF(ERROR, result < 0) << "waitpid() failed";
710 return FALSE; // Don't call this callback again
711}
712} // namespace {}
713
714void ScheduleCrashReporterUpload() {
715 g_idle_add(&TriggerCrashReporterUpload, NULL);
716}
717
Chris Sosa4f8ee272012-11-30 13:01:54 -0800718bool SetCpuShares(CpuShares shares) {
719 string string_shares = base::IntToString(static_cast<int>(shares));
720 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
721 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
722 if(utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
723 string_shares.size())){
724 return true;
725 } else {
726 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
727 << " using " << cpu_shares_file;
728 return false;
729 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700730}
731
Chris Sosa4f8ee272012-11-30 13:01:54 -0800732int CompareCpuShares(CpuShares shares_lhs,
733 CpuShares shares_rhs) {
734 return static_cast<int>(shares_lhs) - static_cast<int>(shares_rhs);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700735}
736
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700737int FuzzInt(int value, unsigned int range) {
738 int min = value - range / 2;
739 int max = value + range - range / 2;
740 return base::RandInt(min, max);
741}
742
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800743gboolean GlibRunClosure(gpointer data) {
744 google::protobuf::Closure* callback =
745 reinterpret_cast<google::protobuf::Closure*>(data);
746 callback->Run();
747 return FALSE;
748}
749
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700750string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800751 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700752}
753
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800754string FormatTimeDelta(TimeDelta delta) {
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700755 // Canonicalize into days, hours, minutes, seconds and microseconds.
756 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800757 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700758 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800759 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700760 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800761 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700762 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800763 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700764 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800765
766 // Construct and return string.
767 string str;
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700768 if (days)
769 base::StringAppendF(&str, "%ud", days);
770 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800771 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700772 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800773 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700774 base::StringAppendF(&str, "%u", secs);
775 if (usecs) {
776 int width = 6;
777 while ((usecs / 10) * 10 == usecs) {
778 usecs /= 10;
779 width--;
780 }
781 base::StringAppendF(&str, ".%0*u", width, usecs);
782 }
783 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800784 return str;
785}
786
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700787string ToString(const Time utc_time) {
788 Time::Exploded exp_time;
789 utc_time.UTCExplode(&exp_time);
790 return StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
791 exp_time.month,
792 exp_time.day_of_month,
793 exp_time.year,
794 exp_time.hour,
795 exp_time.minute,
796 exp_time.second);
797}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000798
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700799string ToString(bool b) {
800 return (b ? "true" : "false");
801}
802
Alex Deymo1c656c42013-06-28 11:02:14 -0700803string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700804 switch (source) {
805 case kDownloadSourceHttpsServer: return "HttpsServer";
806 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700807 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -0700808 case kNumDownloadSources: return "Unknown";
809 // Don't add a default case to let the compiler warn about newly added
810 // download sources which should be added here.
811 }
812
813 return "Unknown";
814}
815
Alex Deymo1c656c42013-06-28 11:02:14 -0700816string ToString(PayloadType payload_type) {
817 switch (payload_type) {
818 case kPayloadTypeDelta: return "Delta";
819 case kPayloadTypeFull: return "Full";
820 case kPayloadTypeForcedFull: return "ForcedFull";
821 case kNumPayloadTypes: return "Unknown";
822 // Don't add a default case to let the compiler warn about newly added
823 // payload types which should be added here.
824 }
825
826 return "Unknown";
827}
828
David Zeuthena99981f2013-04-29 13:42:47 -0700829ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700830 // Ignore the higher order bits in the code by applying the mask as
831 // we want the enumerations to be in the small contiguous range
David Zeuthena99981f2013-04-29 13:42:47 -0700832 // with values less than kErrorCodeUmaReportedMax.
833 ErrorCode base_code = static_cast<ErrorCode>(code & ~kErrorCodeSpecialFlags);
Jay Srinivasanf0572052012-10-23 18:12:56 -0700834
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800835 // Make additional adjustments required for UMA and error classification.
836 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
837 // chromium-os:34369.
David Zeuthena99981f2013-04-29 13:42:47 -0700838 if (base_code >= kErrorCodeOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700839 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800840 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800841 LOG(INFO) << "Converting error code " << base_code
David Zeuthena99981f2013-04-29 13:42:47 -0700842 << " to kErrorCodeOmahaErrorInHTTPResponse";
843 base_code = kErrorCodeOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700844 }
845
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800846 return base_code;
847}
848
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800849// Returns a printable version of the various flags denoted in the higher order
850// bits of the given code. Returns an empty string if none of those bits are
851// set.
852string GetFlagNames(uint32_t code) {
David Zeuthena99981f2013-04-29 13:42:47 -0700853 uint32_t flags = code & kErrorCodeSpecialFlags;
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800854 string flag_names;
855 string separator = "";
856 for(size_t i = 0; i < sizeof(flags) * 8; i++) {
857 uint32_t flag = flags & (1 << i);
858 if (flag) {
David Zeuthena99981f2013-04-29 13:42:47 -0700859 flag_names += separator + CodeToString(static_cast<ErrorCode>(flag));
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800860 separator = ", ";
861 }
862 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800863
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800864 return flag_names;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700865}
866
David Zeuthena99981f2013-04-29 13:42:47 -0700867void SendErrorCodeToUma(SystemState* system_state, ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800868 if (!system_state)
869 return;
870
David Zeuthena99981f2013-04-29 13:42:47 -0700871 ErrorCode uma_error_code = GetBaseErrorCode(code);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800872
873 // If the code doesn't have flags computed already, compute them now based on
874 // the state of the current update attempt.
David Zeuthena99981f2013-04-29 13:42:47 -0700875 uint32_t flags = code & kErrorCodeSpecialFlags;
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800876 if (!flags)
877 flags = system_state->update_attempter()->GetErrorCodeFlags();
878
879 // Determine the UMA bucket depending on the flags. But, ignore the resumed
880 // flag, as it's perfectly normal for production devices to resume their
881 // downloads and so we want to record those cases also in NormalErrorCodes
882 // bucket.
David Zeuthena99981f2013-04-29 13:42:47 -0700883 string metric = (flags & ~kErrorCodeResumedFlag) ?
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800884 "Installer.DevModeErrorCodes" : "Installer.NormalErrorCodes";
885
886 LOG(INFO) << "Sending error code " << uma_error_code
887 << " (" << CodeToString(uma_error_code) << ")"
888 << " to UMA metric: " << metric
889 << ". Flags = " << (flags ? GetFlagNames(flags) : "None");
890
891 system_state->metrics_lib()->SendEnumToUMA(metric,
892 uma_error_code,
David Zeuthena99981f2013-04-29 13:42:47 -0700893 kErrorCodeUmaReportedMax);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800894}
895
David Zeuthena99981f2013-04-29 13:42:47 -0700896string CodeToString(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800897 // If the given code has both parts (i.e. the error code part and the flags
898 // part) then strip off the flags part since the switch statement below
899 // has case statements only for the base error code or a single flag but
900 // doesn't support any combinations of those.
David Zeuthena99981f2013-04-29 13:42:47 -0700901 if ((code & kErrorCodeSpecialFlags) && (code & ~kErrorCodeSpecialFlags))
902 code = static_cast<ErrorCode>(code & ~kErrorCodeSpecialFlags);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800903 switch (code) {
David Zeuthena99981f2013-04-29 13:42:47 -0700904 case kErrorCodeSuccess: return "kErrorCodeSuccess";
905 case kErrorCodeError: return "kErrorCodeError";
906 case kErrorCodeOmahaRequestError: return "kErrorCodeOmahaRequestError";
907 case kErrorCodeOmahaResponseHandlerError:
908 return "kErrorCodeOmahaResponseHandlerError";
909 case kErrorCodeFilesystemCopierError:
910 return "kErrorCodeFilesystemCopierError";
911 case kErrorCodePostinstallRunnerError:
912 return "kErrorCodePostinstallRunnerError";
Gilad Arnold21504f02013-05-24 08:51:22 -0700913 case kErrorCodePayloadMismatchedType:
914 return "kErrorCodePayloadMismatchedType";
David Zeuthena99981f2013-04-29 13:42:47 -0700915 case kErrorCodeInstallDeviceOpenError:
916 return "kErrorCodeInstallDeviceOpenError";
917 case kErrorCodeKernelDeviceOpenError:
918 return "kErrorCodeKernelDeviceOpenError";
919 case kErrorCodeDownloadTransferError:
920 return "kErrorCodeDownloadTransferError";
921 case kErrorCodePayloadHashMismatchError:
922 return "kErrorCodePayloadHashMismatchError";
923 case kErrorCodePayloadSizeMismatchError:
924 return "kErrorCodePayloadSizeMismatchError";
925 case kErrorCodeDownloadPayloadVerificationError:
926 return "kErrorCodeDownloadPayloadVerificationError";
927 case kErrorCodeDownloadNewPartitionInfoError:
928 return "kErrorCodeDownloadNewPartitionInfoError";
929 case kErrorCodeDownloadWriteError:
930 return "kErrorCodeDownloadWriteError";
931 case kErrorCodeNewRootfsVerificationError:
932 return "kErrorCodeNewRootfsVerificationError";
933 case kErrorCodeNewKernelVerificationError:
934 return "kErrorCodeNewKernelVerificationError";
935 case kErrorCodeSignedDeltaPayloadExpectedError:
936 return "kErrorCodeSignedDeltaPayloadExpectedError";
937 case kErrorCodeDownloadPayloadPubKeyVerificationError:
938 return "kErrorCodeDownloadPayloadPubKeyVerificationError";
939 case kErrorCodePostinstallBootedFromFirmwareB:
940 return "kErrorCodePostinstallBootedFromFirmwareB";
941 case kErrorCodeDownloadStateInitializationError:
942 return "kErrorCodeDownloadStateInitializationError";
943 case kErrorCodeDownloadInvalidMetadataMagicString:
944 return "kErrorCodeDownloadInvalidMetadataMagicString";
945 case kErrorCodeDownloadSignatureMissingInManifest:
946 return "kErrorCodeDownloadSignatureMissingInManifest";
947 case kErrorCodeDownloadManifestParseError:
948 return "kErrorCodeDownloadManifestParseError";
949 case kErrorCodeDownloadMetadataSignatureError:
950 return "kErrorCodeDownloadMetadataSignatureError";
951 case kErrorCodeDownloadMetadataSignatureVerificationError:
952 return "kErrorCodeDownloadMetadataSignatureVerificationError";
953 case kErrorCodeDownloadMetadataSignatureMismatch:
954 return "kErrorCodeDownloadMetadataSignatureMismatch";
955 case kErrorCodeDownloadOperationHashVerificationError:
956 return "kErrorCodeDownloadOperationHashVerificationError";
957 case kErrorCodeDownloadOperationExecutionError:
958 return "kErrorCodeDownloadOperationExecutionError";
959 case kErrorCodeDownloadOperationHashMismatch:
960 return "kErrorCodeDownloadOperationHashMismatch";
961 case kErrorCodeOmahaRequestEmptyResponseError:
962 return "kErrorCodeOmahaRequestEmptyResponseError";
963 case kErrorCodeOmahaRequestXMLParseError:
964 return "kErrorCodeOmahaRequestXMLParseError";
965 case kErrorCodeDownloadInvalidMetadataSize:
966 return "kErrorCodeDownloadInvalidMetadataSize";
967 case kErrorCodeDownloadInvalidMetadataSignature:
968 return "kErrorCodeDownloadInvalidMetadataSignature";
969 case kErrorCodeOmahaResponseInvalid:
970 return "kErrorCodeOmahaResponseInvalid";
971 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
972 return "kErrorCodeOmahaUpdateIgnoredPerPolicy";
973 case kErrorCodeOmahaUpdateDeferredPerPolicy:
974 return "kErrorCodeOmahaUpdateDeferredPerPolicy";
975 case kErrorCodeOmahaErrorInHTTPResponse:
976 return "kErrorCodeOmahaErrorInHTTPResponse";
977 case kErrorCodeDownloadOperationHashMissingError:
978 return "kErrorCodeDownloadOperationHashMissingError";
979 case kErrorCodeDownloadMetadataSignatureMissingError:
980 return "kErrorCodeDownloadMetadataSignatureMissingError";
981 case kErrorCodeOmahaUpdateDeferredForBackoff:
982 return "kErrorCodeOmahaUpdateDeferredForBackoff";
983 case kErrorCodePostinstallPowerwashError:
984 return "kErrorCodePostinstallPowerwashError";
985 case kErrorCodeUpdateCanceledByChannelChange:
986 return "kErrorCodeUpdateCanceledByChannelChange";
987 case kErrorCodeUmaReportedMax:
988 return "kErrorCodeUmaReportedMax";
989 case kErrorCodeOmahaRequestHTTPResponseBase:
990 return "kErrorCodeOmahaRequestHTTPResponseBase";
991 case kErrorCodeResumedFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800992 return "Resumed";
David Zeuthena99981f2013-04-29 13:42:47 -0700993 case kErrorCodeDevModeFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800994 return "DevMode";
David Zeuthena99981f2013-04-29 13:42:47 -0700995 case kErrorCodeTestImageFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800996 return "TestImage";
David Zeuthena99981f2013-04-29 13:42:47 -0700997 case kErrorCodeTestOmahaUrlFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800998 return "TestOmahaUrl";
David Zeuthena99981f2013-04-29 13:42:47 -0700999 case kErrorCodeSpecialFlags:
1000 return "kErrorCodeSpecialFlags";
Don Garrett81018e02013-07-30 18:46:31 -07001001 case kErrorCodePostinstallFirmwareRONotUpdatable:
1002 return "kErrorCodePostinstallFirmwareRONotUpdatable";
Don Garrett4d039442013-10-28 18:40:06 -07001003 case kErrorCodeUnsupportedMajorPayloadVersion:
1004 return "kErrorCodeUnsupportedMajorPayloadVersion";
1005 case kErrorCodeUnsupportedMinorPayloadVersion:
1006 return "kErrorCodeUnsupportedMinorPayloadVersion";
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001007 // Don't add a default case to let the compiler warn about newly added
1008 // error codes which should be added here.
1009 }
1010
1011 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
1012}
Jay Srinivasanf0572052012-10-23 18:12:56 -07001013
Gilad Arnold30dedd82013-07-03 06:19:09 -07001014bool CreatePowerwashMarkerFile(const char* file_path) {
1015 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
1016 bool result = utils::WriteFile(marker_file,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001017 kPowerwashCommand,
1018 strlen(kPowerwashCommand));
Gilad Arnold30dedd82013-07-03 06:19:09 -07001019 if (result) {
1020 LOG(INFO) << "Created " << marker_file << " to powerwash on next reboot";
1021 } else {
1022 PLOG(ERROR) << "Error in creating powerwash marker file: " << marker_file;
1023 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001024
1025 return result;
1026}
1027
Gilad Arnold30dedd82013-07-03 06:19:09 -07001028bool DeletePowerwashMarkerFile(const char* file_path) {
1029 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
1030 const FilePath kPowerwashMarkerPath(marker_file);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001031 bool result = file_util::Delete(kPowerwashMarkerPath, false);
1032
1033 if (result)
1034 LOG(INFO) << "Successfully deleted the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001035 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001036 else
1037 PLOG(ERROR) << "Could not delete the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001038 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001039
1040 return result;
1041}
1042
Chris Sosad317e402013-06-12 13:47:09 -07001043bool GetInstallDev(const std::string& boot_dev, std::string* install_dev) {
1044 TEST_AND_RETURN_FALSE(StringHasPrefix(boot_dev, "/dev/"));
Liam McLoughlin049d1652013-07-31 18:47:46 -07001045 string::iterator it;
1046 string ubiblock_prefix("/dev/ubiblock");
1047
1048 install_dev->assign(boot_dev);
1049
1050 if(StringHasPrefix(boot_dev, ubiblock_prefix)) {
1051 // UBI-based device
1052 it = install_dev->begin() + ubiblock_prefix.length();
1053 } else {
1054 // non-UBI device
1055 it = install_dev->end() - 1; // last character in string
1056 }
1057
Chris Sosad317e402013-06-12 13:47:09 -07001058 // Right now, we just switch '3' and '5' partition numbers.
Liam McLoughlin049d1652013-07-31 18:47:46 -07001059 TEST_AND_RETURN_FALSE(*it == '3' || *it == '5');
1060 *it = (*it == '3' ? '5' : '3');
1061
Chris Sosad317e402013-06-12 13:47:09 -07001062 return true;
1063}
1064
David Zeuthen27a48bc2013-08-06 12:06:29 -07001065Time TimeFromStructTimespec(struct timespec *ts) {
1066 int64 us = static_cast<int64>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
1067 static_cast<int64>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
1068 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
1069}
1070
1071gchar** StringVectorToGStrv(const vector<string> &vector) {
1072 GPtrArray *p = g_ptr_array_new();
1073 for (std::vector<string>::const_iterator i = vector.begin();
1074 i != vector.end(); ++i) {
1075 g_ptr_array_add(p, g_strdup(i->c_str()));
1076 }
1077 g_ptr_array_add(p, NULL);
1078 return reinterpret_cast<gchar**>(g_ptr_array_free(p, FALSE));
1079}
1080
1081string StringVectorToString(const vector<string> &vector) {
1082 string str = "[";
1083 for (std::vector<string>::const_iterator i = vector.begin();
1084 i != vector.end(); ++i) {
1085 if (i != vector.begin())
1086 str += ", ";
1087 str += '"';
1088 str += *i;
1089 str += '"';
1090 }
1091 str += "]";
1092 return str;
1093}
1094
David Zeuthen8f191b22013-08-06 12:27:50 -07001095string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
1096 string encoded_hash;
1097 OmahaHashCalculator::Base64Encode(payload_hash.c_str(),
1098 payload_hash.size(),
1099 &encoded_hash);
1100 return StringPrintf("cros_update_size_%zu_hash_%s",
1101 payload_size,
1102 encoded_hash.c_str());
1103}
1104
David Zeuthen910ec5b2013-09-26 12:10:58 -07001105bool IsXAttrSupported(const base::FilePath& dir_path) {
1106 char *path = strdup(dir_path.Append("xattr_test_XXXXXX").value().c_str());
1107
1108 int fd = mkstemp(path);
1109 if (fd == -1) {
1110 PLOG(ERROR) << "Error creating temporary file in " << dir_path.value();
1111 free(path);
1112 return false;
1113 }
1114
1115 if (unlink(path) != 0) {
1116 PLOG(ERROR) << "Error unlinking temporary file " << path;
1117 close(fd);
1118 free(path);
1119 return false;
1120 }
1121
1122 int xattr_res = fsetxattr(fd, "user.xattr-test", "value", strlen("value"), 0);
1123 if (xattr_res != 0) {
1124 if (errno == ENOTSUP) {
1125 // Leave it to call-sites to warn about non-support.
1126 } else {
1127 PLOG(ERROR) << "Error setting xattr on " << path;
1128 }
1129 }
1130 close(fd);
1131 free(path);
1132 return xattr_res == 0;
1133}
1134
adlr@google.com3defe6a2009-12-04 20:57:17 +00001135} // namespace utils
1136
1137} // namespace chromeos_update_engine