blob: 8f041347221ddce83644855199b0e84bc1d32a9a [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
adlr@google.com3defe6a2009-12-04 20:57:17 +00007#include <sys/mount.h>
Darin Petkovc6c135c2010-08-11 13:36:18 -07008#include <sys/resource.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +00009#include <sys/stat.h>
10#include <sys/types.h>
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -080011#include <sys/wait.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000012#include <dirent.h>
13#include <errno.h>
Andrew de los Reyes970bb282009-12-09 16:34:04 -080014#include <fcntl.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000015#include <stdio.h>
16#include <stdlib.h>
17#include <string.h>
18#include <unistd.h>
Darin Petkovf74eb652010-08-04 12:08:38 -070019
adlr@google.com3defe6a2009-12-04 20:57:17 +000020#include <algorithm>
Chris Sosac1972482013-04-30 22:31:10 -070021#include <vector>
Darin Petkovf74eb652010-08-04 12:08:38 -070022
Will Drewry8f71da82010-08-30 14:07:11 -050023#include <base/file_path.h>
24#include <base/file_util.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040025#include <base/logging.h>
Chris Sosafc661a12013-02-26 14:43:21 -080026#include <base/posix/eintr_wrapper.h>
Will Drewry8f71da82010-08-30 14:07:11 -050027#include <base/rand_util.h>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070028#include <base/string_number_conversions.h>
Chris Sosac1972482013-04-30 22:31:10 -070029#include <base/string_split.h>
Will Drewry8f71da82010-08-30 14:07:11 -050030#include <base/string_util.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040031#include <base/stringprintf.h>
Gilad Arnold8e3f1262013-01-08 14:59:54 -080032#include <glib.h>
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -080033#include <google/protobuf/stubs/common.h>
Will Drewry8f71da82010-08-30 14:07:11 -050034
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070035#include "update_engine/constants.h"
Andrew de los Reyes970bb282009-12-09 16:34:04 -080036#include "update_engine/file_writer.h"
Darin Petkov33d30642010-08-04 10:18:57 -070037#include "update_engine/omaha_request_params.h"
Darin Petkov296889c2010-07-23 16:20:54 -070038#include "update_engine/subprocess.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080039#include "update_engine/system_state.h"
40#include "update_engine/update_attempter.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000041
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070042using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080043using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000044using std::min;
Chris Sosac1972482013-04-30 22:31:10 -070045using std::pair;
adlr@google.com3defe6a2009-12-04 20:57:17 +000046using std::string;
47using std::vector;
48
49namespace chromeos_update_engine {
50
Ben Chan77a1eba2012-10-07 22:54:55 -070051namespace {
52
53// The following constants control how UnmountFilesystem should retry if
54// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
55// one second.
56const int kUnmountMaxNumOfRetries = 5;
57const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Ben Chan77a1eba2012-10-07 22:54:55 -070058} // namespace
59
adlr@google.com3defe6a2009-12-04 20:57:17 +000060namespace utils {
61
Darin Petkova07586b2010-10-20 13:41:15 -070062static const char kDevImageMarker[] = "/root/.dev_mode";
Darin Petkov2a0e6332010-09-24 14:43:41 -070063
Chris Sosa4f8ee272012-11-30 13:01:54 -080064// Cgroup container is created in update-engine's upstart script located at
65// /etc/init/update-engine.conf.
66static const char kCGroupDir[] = "/sys/fs/cgroup/cpu/update-engine";
67
Darin Petkov33d30642010-08-04 10:18:57 -070068bool IsOfficialBuild() {
Darin Petkova07586b2010-10-20 13:41:15 -070069 return !file_util::PathExists(FilePath(kDevImageMarker));
Darin Petkov33d30642010-08-04 10:18:57 -070070}
71
Darin Petkovc91dd6b2011-01-10 12:31:34 -080072bool IsNormalBootMode() {
Darin Petkov44d98d92011-03-21 16:08:11 -070073 // TODO(petkov): Convert to a library call once a crossystem library is
74 // available (crosbug.com/13291).
75 int exit_code = 0;
76 vector<string> cmd(1, "/usr/bin/crossystem");
77 cmd.push_back("devsw_boot?1");
78
79 // Assume dev mode if the dev switch is set to 1 and there was no error
80 // executing crossystem. Assume normal mode otherwise.
Darin Petkov85d02b72011-05-17 13:25:51 -070081 bool success = Subprocess::SynchronousExec(cmd, &exit_code, NULL);
Darin Petkov44d98d92011-03-21 16:08:11 -070082 bool dev_mode = success && exit_code == 0;
83 LOG_IF(INFO, dev_mode) << "Booted in dev mode.";
84 return !dev_mode;
Darin Petkovc91dd6b2011-01-10 12:31:34 -080085}
86
Chris Sosac1972482013-04-30 22:31:10 -070087string ReadValueFromCrosSystem(const string& key){
Darin Petkovf2065b42011-05-17 16:36:27 -070088 int exit_code = 0;
89 vector<string> cmd(1, "/usr/bin/crossystem");
Chris Sosac1972482013-04-30 22:31:10 -070090 cmd.push_back(key);
Darin Petkovf2065b42011-05-17 16:36:27 -070091
Chris Sosac1972482013-04-30 22:31:10 -070092 string return_value;
93 bool success = Subprocess::SynchronousExec(cmd, &exit_code, &return_value);
Darin Petkovf2065b42011-05-17 16:36:27 -070094 if (success && !exit_code) {
Chris Sosac1972482013-04-30 22:31:10 -070095 TrimWhitespaceASCII(return_value, TRIM_ALL, &return_value);
96 return return_value;
Darin Petkovf2065b42011-05-17 16:36:27 -070097 }
Chris Sosac1972482013-04-30 22:31:10 -070098 LOG(ERROR) << "Unable to read " << key << " (" << exit_code << ") "
99 << return_value;
Darin Petkovf2065b42011-05-17 16:36:27 -0700100 return "";
101}
102
Chris Sosac1972482013-04-30 22:31:10 -0700103string GetHardwareClass() {
104 return ReadValueFromCrosSystem("hwid");
105}
106
107string GetFirmwareVersion() {
108 return ReadValueFromCrosSystem("fwid");
109}
110
111string GetECVersion(const char* input_line) {
112 string line;
113 if(input_line == NULL) {
114 int exit_code = 0;
115 vector<string> cmd(1, "/usr/sbin/mosys");
116 cmd.push_back("-k");
117 cmd.push_back("ec");
118 cmd.push_back("info");
119
120 bool success = Subprocess::SynchronousExec(cmd, &exit_code, &line);
121 if (!success || exit_code) {
122 LOG(ERROR) << "Unable to read ec info from mosys (" << exit_code << ")";
123 return "";
124 }
125 } else {
126 line = input_line;
127 }
128
129 TrimWhitespaceASCII(line, TRIM_ALL, &line);
130
131 // At this point we want to conver the format key=value pair from mosys to
132 // a vector of key value pairs.
133 vector<pair<string, string> > kv_pairs;
134 if (base::SplitStringIntoKeyValuePairs(line, '=', ' ', &kv_pairs)) {
135 for (vector<pair<string, string> >::iterator it = kv_pairs.begin();
136 it != kv_pairs.end(); ++it) {
137 // Finally match against the fw_verion which may have quotes.
138 if (it->first == "fw_version") {
139 string output;
140 // Trim any quotes.
141 TrimString(it->second, "\"", &output);
142 return output;
143 }
144 }
145 }
146 LOG(ERROR) << "Unable to parse fwid from ec info.";
147 return "";
148}
149
150
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800151bool WriteFile(const char* path, const char* data, int data_len) {
152 DirectFileWriter writer;
153 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
154 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700155 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800156 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800157 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800158 return true;
159}
160
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700161bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700162 const char* c_buf = static_cast<const char*>(buf);
163 ssize_t bytes_written = 0;
164 while (bytes_written < static_cast<ssize_t>(count)) {
165 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
166 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
167 bytes_written += rc;
168 }
169 return true;
170}
171
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700172bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
173 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700174 size_t bytes_written = 0;
175 int num_attempts = 0;
176 while (bytes_written < count) {
177 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700178 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
179 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700180 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
181 if (rc < 0) {
182 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
183 << " bytes_written=" << bytes_written
184 << " count=" << count << " offset=" << offset;
185 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700186 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
187 bytes_written += rc;
188 }
189 return true;
190}
191
192bool PReadAll(int fd, void* buf, size_t count, off_t offset,
193 ssize_t* out_bytes_read) {
194 char* c_buf = static_cast<char*>(buf);
195 ssize_t bytes_read = 0;
196 while (bytes_read < static_cast<ssize_t>(count)) {
197 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
198 offset + bytes_read);
199 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
200 if (rc == 0) {
201 break;
202 }
203 bytes_read += rc;
204 }
205 *out_bytes_read = bytes_read;
206 return true;
Darin Petkov296889c2010-07-23 16:20:54 -0700207
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700208}
209
Gilad Arnold19a45f02012-07-19 12:36:10 -0700210// Append |nbytes| of content from |buf| to the vector pointed to by either
211// |vec_p| or |str_p|.
212static void AppendBytes(const char* buf, size_t nbytes,
213 std::vector<char>* vec_p) {
214 CHECK(buf);
215 CHECK(vec_p);
216 vec_p->insert(vec_p->end(), buf, buf + nbytes);
217}
218static void AppendBytes(const char* buf, size_t nbytes,
219 std::string* str_p) {
220 CHECK(buf);
221 CHECK(str_p);
222 str_p->append(buf, nbytes);
223}
224
225// Reads from an open file |fp|, appending the read content to the container
226// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200227// file's content, false otherwise. If |size| is not -1, reads up to |size|
228// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700229template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200230static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700231 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200232 CHECK(size == -1 || size >= 0);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700233 char buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200234 while (size == -1 || size > 0) {
235 off_t bytes_to_read = sizeof(buf);
236 if (size > 0 && bytes_to_read > size) {
237 bytes_to_read = size;
238 }
239 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
240 if (!nbytes) {
241 break;
242 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700243 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200244 if (size != -1) {
245 CHECK(size >= static_cast<off_t>(nbytes));
246 size -= nbytes;
247 }
248 }
249 if (ferror(fp)) {
250 return false;
251 }
252 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700253}
254
Darin Petkov8e447e02013-04-16 16:23:50 +0200255// Opens a file |path| for reading and appends its the contents to a container
256// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
257// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700258template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200259static bool ReadFileChunkAndAppend(const std::string& path,
260 off_t offset,
261 off_t size,
262 T* out_p) {
263 CHECK_GE(offset, 0);
264 CHECK(size == -1 || size >= 0);
265 file_util::ScopedFILE fp(fopen(path.c_str(), "r"));
266 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000267 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200268 if (offset) {
269 // Return success without appending any data if a chunk beyond the end of
270 // the file is requested.
271 if (offset >= FileSize(path)) {
272 return true;
273 }
274 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
275 }
276 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000277}
278
Gilad Arnold19a45f02012-07-19 12:36:10 -0700279// Invokes a pipe |cmd|, then uses |append_func| to append its stdout to a
280// container |out_p|.
281template <class T>
282static bool ReadPipeAndAppend(const std::string& cmd, T* out_p) {
283 FILE* fp = popen(cmd.c_str(), "r");
284 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000285 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200286 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700287 return (success && pclose(fp) >= 0);
288}
289
290
Darin Petkov8e447e02013-04-16 16:23:50 +0200291bool ReadFile(const string& path, vector<char>* out_p) {
292 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700293}
294
Darin Petkov8e447e02013-04-16 16:23:50 +0200295bool ReadFile(const string& path, string* out_p) {
296 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700297}
298
Darin Petkov8e447e02013-04-16 16:23:50 +0200299bool ReadFileChunk(const string& path, off_t offset, off_t size,
300 vector<char>* out_p) {
301 return ReadFileChunkAndAppend(path, offset, size, out_p);
302}
303
304bool ReadPipe(const string& cmd, vector<char>* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700305 return ReadPipeAndAppend(cmd, out_p);
306}
307
Darin Petkov8e447e02013-04-16 16:23:50 +0200308bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700309 return ReadPipeAndAppend(cmd, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000310}
311
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700312off_t FileSize(const string& path) {
313 struct stat stbuf;
314 int rc = stat(path.c_str(), &stbuf);
315 CHECK_EQ(rc, 0);
316 if (rc < 0)
317 return rc;
318 return stbuf.st_size;
319}
320
adlr@google.com3defe6a2009-12-04 20:57:17 +0000321void HexDumpArray(const unsigned char* const arr, const size_t length) {
322 const unsigned char* const char_arr =
323 reinterpret_cast<const unsigned char* const>(arr);
324 LOG(INFO) << "Logging array of length: " << length;
325 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700326 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000327 const unsigned int bytes_remaining = length - i;
328 const unsigned int bytes_per_this_line = min(bytes_per_line,
329 bytes_remaining);
330 char header[100];
331 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
332 TEST_AND_RETURN(r == 13);
333 string line = header;
334 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
335 char buf[20];
336 unsigned char c = char_arr[i + j];
337 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
338 TEST_AND_RETURN(r == 3);
339 line += buf;
340 }
341 LOG(INFO) << line;
342 }
343}
344
345namespace {
346class ScopedDirCloser {
347 public:
348 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
349 ~ScopedDirCloser() {
350 if (dir_ && *dir_) {
351 int r = closedir(*dir_);
352 TEST_AND_RETURN_ERRNO(r == 0);
353 *dir_ = NULL;
354 dir_ = NULL;
355 }
356 }
357 private:
358 DIR** dir_;
359};
360} // namespace {}
361
362bool RecursiveUnlinkDir(const std::string& path) {
363 struct stat stbuf;
364 int r = lstat(path.c_str(), &stbuf);
365 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
366 if ((r < 0) && (errno == ENOENT))
367 // path request is missing. that's fine.
368 return true;
369 if (!S_ISDIR(stbuf.st_mode)) {
370 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700371 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000372 // success or path disappeared before we could unlink.
373 return true;
374 }
375 {
376 // We have a dir, unlink all children, then delete dir
377 DIR *dir = opendir(path.c_str());
378 TEST_AND_RETURN_FALSE_ERRNO(dir);
379 ScopedDirCloser dir_closer(&dir);
380 struct dirent dir_entry;
381 struct dirent *dir_entry_p;
382 int err = 0;
383 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
384 if (dir_entry_p == NULL) {
385 // end of stream reached
386 break;
387 }
388 // Skip . and ..
389 if (!strcmp(dir_entry_p->d_name, ".") ||
390 !strcmp(dir_entry_p->d_name, ".."))
391 continue;
392 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700393 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000394 }
395 TEST_AND_RETURN_FALSE(err == 0);
396 }
397 // unlink dir
398 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
399 return true;
400}
401
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700402string RootDevice(const string& partition_device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700403 FilePath device_path(partition_device);
404 if (device_path.DirName().value() != "/dev") {
405 return "";
406 }
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700407 string::const_iterator it = --partition_device.end();
408 for (; it >= partition_device.begin(); --it) {
409 if (!isdigit(*it))
410 break;
411 }
412 // Some devices contain a p before the partitions. For example:
413 // /dev/mmc0p4 should be shortened to /dev/mmc0.
414 if (*it == 'p')
415 --it;
416 return string(partition_device.begin(), it + 1);
417}
418
419string PartitionNumber(const string& partition_device) {
420 CHECK(!partition_device.empty());
421 string::const_iterator it = --partition_device.end();
422 for (; it >= partition_device.begin(); --it) {
423 if (!isdigit(*it))
424 break;
425 }
426 return string(it + 1, partition_device.end());
427}
428
Darin Petkovf74eb652010-08-04 12:08:38 -0700429string SysfsBlockDevice(const string& device) {
430 FilePath device_path(device);
431 if (device_path.DirName().value() != "/dev") {
432 return "";
433 }
434 return FilePath("/sys/block").Append(device_path.BaseName()).value();
435}
436
437bool IsRemovableDevice(const std::string& device) {
438 string sysfs_block = SysfsBlockDevice(device);
439 string removable;
440 if (sysfs_block.empty() ||
441 !file_util::ReadFileToString(FilePath(sysfs_block).Append("removable"),
442 &removable)) {
443 return false;
444 }
445 TrimWhitespaceASCII(removable, TRIM_ALL, &removable);
446 return removable == "1";
447}
448
adlr@google.com3defe6a2009-12-04 20:57:17 +0000449std::string ErrnoNumberAsString(int err) {
450 char buf[100];
451 buf[0] = '\0';
452 return strerror_r(err, buf, sizeof(buf));
453}
454
455std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
456 string ret;
457 bool last_insert_was_slash = false;
458 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
459 if (*it == '/') {
460 if (last_insert_was_slash)
461 continue;
462 last_insert_was_slash = true;
463 } else {
464 last_insert_was_slash = false;
465 }
466 ret.push_back(*it);
467 }
468 if (strip_trailing_slash && last_insert_was_slash) {
469 string::size_type last_non_slash = ret.find_last_not_of('/');
470 if (last_non_slash != string::npos) {
471 ret.resize(last_non_slash + 1);
472 } else {
473 ret = "";
474 }
475 }
476 return ret;
477}
478
479bool FileExists(const char* path) {
480 struct stat stbuf;
481 return 0 == lstat(path, &stbuf);
482}
483
Darin Petkov30291ed2010-11-12 10:23:06 -0800484bool IsSymlink(const char* path) {
485 struct stat stbuf;
486 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
487}
488
adlr@google.com3defe6a2009-12-04 20:57:17 +0000489std::string TempFilename(string path) {
490 static const string suffix("XXXXXX");
491 CHECK(StringHasSuffix(path, suffix));
492 do {
493 string new_suffix;
494 for (unsigned int i = 0; i < suffix.size(); i++) {
495 int r = rand() % (26 * 2 + 10); // [a-zA-Z0-9]
496 if (r < 26)
497 new_suffix.append(1, 'a' + r);
498 else if (r < (26 * 2))
499 new_suffix.append(1, 'A' + r - 26);
500 else
501 new_suffix.append(1, '0' + r - (26 * 2));
502 }
503 CHECK_EQ(new_suffix.size(), suffix.size());
504 path.resize(path.size() - new_suffix.size());
505 path.append(new_suffix);
506 } while (FileExists(path.c_str()));
507 return path;
508}
509
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700510bool MakeTempFile(const std::string& filename_template,
511 std::string* filename,
512 int* fd) {
513 DCHECK(filename || fd);
514 vector<char> buf(filename_template.size() + 1);
515 memcpy(&buf[0], filename_template.data(), filename_template.size());
516 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700517
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700518 int mkstemp_fd = mkstemp(&buf[0]);
519 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
520 if (filename) {
521 *filename = &buf[0];
522 }
523 if (fd) {
524 *fd = mkstemp_fd;
525 } else {
526 close(mkstemp_fd);
527 }
528 return true;
529}
530
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700531bool MakeTempDirectory(const std::string& dirname_template,
532 std::string* dirname) {
533 DCHECK(dirname);
534 vector<char> buf(dirname_template.size() + 1);
535 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
536 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700537
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700538 char* return_code = mkdtemp(&buf[0]);
539 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
540 *dirname = &buf[0];
541 return true;
542}
543
adlr@google.com3defe6a2009-12-04 20:57:17 +0000544bool StringHasSuffix(const std::string& str, const std::string& suffix) {
545 if (suffix.size() > str.size())
546 return false;
547 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
548}
549
550bool StringHasPrefix(const std::string& str, const std::string& prefix) {
551 if (prefix.size() > str.size())
552 return false;
553 return 0 == str.compare(0, prefix.size(), prefix);
554}
555
adlr@google.com3defe6a2009-12-04 20:57:17 +0000556bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700557 const string& mountpoint,
558 unsigned long mountflags) {
559 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000560 if (rc < 0) {
561 string msg = ErrnoNumberAsString(errno);
562 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
563 << device << " on " << mountpoint;
564 return false;
565 }
566 return true;
567}
568
569bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700570 for (int num_retries = 0; ; ++num_retries) {
571 if (umount(mountpoint.c_str()) == 0)
572 break;
573
574 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
575 num_retries < kUnmountMaxNumOfRetries);
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800576 g_usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700577 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000578 return true;
579}
580
Darin Petkovd3f8c892010-10-12 21:38:45 -0700581bool GetFilesystemSize(const std::string& device,
582 int* out_block_count,
583 int* out_block_size) {
584 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
585 TEST_AND_RETURN_FALSE(fd >= 0);
586 ScopedFdCloser fd_closer(&fd);
587 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
588}
589
590bool GetFilesystemSizeFromFD(int fd,
591 int* out_block_count,
592 int* out_block_size) {
593 TEST_AND_RETURN_FALSE(fd >= 0);
594
595 // Determine the ext3 filesystem size by directly reading the block count and
596 // block size information from the superblock. See include/linux/ext3_fs.h for
597 // more details on the structure.
598 ssize_t kBufferSize = 16 * sizeof(uint32_t);
599 char buffer[kBufferSize];
600 const int kSuperblockOffset = 1024;
601 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
602 kBufferSize) {
603 PLOG(ERROR) << "Unable to determine file system size:";
604 return false;
605 }
606 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
607 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
608 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
609 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
610 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
611 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
612 block_count = le32toh(block_count);
613 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
614 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
615 magic = le16toh(magic);
616
617 // Sanity check the parameters.
618 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
619 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
620 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
621 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
622 int block_size = 1 << log_block_size;
623 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
624 block_size <= kExt3MaxBlockSize);
625 TEST_AND_RETURN_FALSE(block_count > 0);
626
627 if (out_block_count) {
628 *out_block_count = block_count;
629 }
630 if (out_block_size) {
631 *out_block_size = block_size;
632 }
633 return true;
634}
635
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700636bool GetBootloader(BootLoader* out_bootloader) {
637 // For now, hardcode to syslinux.
638 *out_bootloader = BootLoader_SYSLINUX;
639 return true;
640}
641
Darin Petkova0b9e772011-10-06 05:05:56 -0700642string GetAndFreeGError(GError** error) {
643 if (!*error) {
644 return "Unknown GLib error.";
645 }
646 string message =
647 base::StringPrintf("GError(%d): %s",
648 (*error)->code,
649 (*error)->message ? (*error)->message : "(unknown)");
650 g_error_free(*error);
651 *error = NULL;
652 return message;
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700653}
654
Darin Petkov296889c2010-07-23 16:20:54 -0700655bool Reboot() {
656 vector<string> command;
657 command.push_back("/sbin/shutdown");
658 command.push_back("-r");
659 command.push_back("now");
660 int rc = 0;
Darin Petkov85d02b72011-05-17 13:25:51 -0700661 Subprocess::SynchronousExec(command, &rc, NULL);
Darin Petkov296889c2010-07-23 16:20:54 -0700662 TEST_AND_RETURN_FALSE(rc == 0);
663 return true;
664}
665
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800666namespace {
667// Do the actual trigger. We do it as a main-loop callback to (try to) get a
668// consistent stack trace.
669gboolean TriggerCrashReporterUpload(void* unused) {
670 pid_t pid = fork();
671 CHECK(pid >= 0) << "fork failed"; // fork() failed. Something is very wrong.
672 if (pid == 0) {
673 // We are the child. Crash.
674 abort(); // never returns
675 }
676 // We are the parent. Wait for child to terminate.
677 pid_t result = waitpid(pid, NULL, 0);
678 LOG_IF(ERROR, result < 0) << "waitpid() failed";
679 return FALSE; // Don't call this callback again
680}
681} // namespace {}
682
683void ScheduleCrashReporterUpload() {
684 g_idle_add(&TriggerCrashReporterUpload, NULL);
685}
686
Chris Sosa4f8ee272012-11-30 13:01:54 -0800687bool SetCpuShares(CpuShares shares) {
688 string string_shares = base::IntToString(static_cast<int>(shares));
689 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
690 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
691 if(utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
692 string_shares.size())){
693 return true;
694 } else {
695 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
696 << " using " << cpu_shares_file;
697 return false;
698 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700699}
700
Chris Sosa4f8ee272012-11-30 13:01:54 -0800701int CompareCpuShares(CpuShares shares_lhs,
702 CpuShares shares_rhs) {
703 return static_cast<int>(shares_lhs) - static_cast<int>(shares_rhs);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700704}
705
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700706int FuzzInt(int value, unsigned int range) {
707 int min = value - range / 2;
708 int max = value + range - range / 2;
709 return base::RandInt(min, max);
710}
711
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800712gboolean GlibRunClosure(gpointer data) {
713 google::protobuf::Closure* callback =
714 reinterpret_cast<google::protobuf::Closure*>(data);
715 callback->Run();
716 return FALSE;
717}
718
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700719string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800720 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700721}
722
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800723string FormatTimeDelta(TimeDelta delta) {
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700724 // Canonicalize into days, hours, minutes, seconds and microseconds.
725 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800726 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700727 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800728 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700729 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800730 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700731 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800732 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700733 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800734
735 // Construct and return string.
736 string str;
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700737 if (days)
738 base::StringAppendF(&str, "%ud", days);
739 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800740 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700741 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800742 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700743 base::StringAppendF(&str, "%u", secs);
744 if (usecs) {
745 int width = 6;
746 while ((usecs / 10) * 10 == usecs) {
747 usecs /= 10;
748 width--;
749 }
750 base::StringAppendF(&str, ".%0*u", width, usecs);
751 }
752 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800753 return str;
754}
755
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700756string ToString(const Time utc_time) {
757 Time::Exploded exp_time;
758 utc_time.UTCExplode(&exp_time);
759 return StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
760 exp_time.month,
761 exp_time.day_of_month,
762 exp_time.year,
763 exp_time.hour,
764 exp_time.minute,
765 exp_time.second);
766}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000767
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700768string ToString(bool b) {
769 return (b ? "true" : "false");
770}
771
Alex Deymo1c656c42013-06-28 11:02:14 -0700772string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700773 switch (source) {
774 case kDownloadSourceHttpsServer: return "HttpsServer";
775 case kDownloadSourceHttpServer: return "HttpServer";
776 case kNumDownloadSources: return "Unknown";
777 // Don't add a default case to let the compiler warn about newly added
778 // download sources which should be added here.
779 }
780
781 return "Unknown";
782}
783
Alex Deymo1c656c42013-06-28 11:02:14 -0700784string ToString(PayloadType payload_type) {
785 switch (payload_type) {
786 case kPayloadTypeDelta: return "Delta";
787 case kPayloadTypeFull: return "Full";
788 case kPayloadTypeForcedFull: return "ForcedFull";
789 case kNumPayloadTypes: return "Unknown";
790 // Don't add a default case to let the compiler warn about newly added
791 // payload types which should be added here.
792 }
793
794 return "Unknown";
795}
796
David Zeuthena99981f2013-04-29 13:42:47 -0700797ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700798 // Ignore the higher order bits in the code by applying the mask as
799 // we want the enumerations to be in the small contiguous range
David Zeuthena99981f2013-04-29 13:42:47 -0700800 // with values less than kErrorCodeUmaReportedMax.
801 ErrorCode base_code = static_cast<ErrorCode>(code & ~kErrorCodeSpecialFlags);
Jay Srinivasanf0572052012-10-23 18:12:56 -0700802
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800803 // Make additional adjustments required for UMA and error classification.
804 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
805 // chromium-os:34369.
David Zeuthena99981f2013-04-29 13:42:47 -0700806 if (base_code >= kErrorCodeOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700807 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800808 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800809 LOG(INFO) << "Converting error code " << base_code
David Zeuthena99981f2013-04-29 13:42:47 -0700810 << " to kErrorCodeOmahaErrorInHTTPResponse";
811 base_code = kErrorCodeOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700812 }
813
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800814 return base_code;
815}
816
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800817// Returns a printable version of the various flags denoted in the higher order
818// bits of the given code. Returns an empty string if none of those bits are
819// set.
820string GetFlagNames(uint32_t code) {
David Zeuthena99981f2013-04-29 13:42:47 -0700821 uint32_t flags = code & kErrorCodeSpecialFlags;
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800822 string flag_names;
823 string separator = "";
824 for(size_t i = 0; i < sizeof(flags) * 8; i++) {
825 uint32_t flag = flags & (1 << i);
826 if (flag) {
David Zeuthena99981f2013-04-29 13:42:47 -0700827 flag_names += separator + CodeToString(static_cast<ErrorCode>(flag));
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800828 separator = ", ";
829 }
830 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800831
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800832 return flag_names;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700833}
834
David Zeuthena99981f2013-04-29 13:42:47 -0700835void SendErrorCodeToUma(SystemState* system_state, ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800836 if (!system_state)
837 return;
838
David Zeuthena99981f2013-04-29 13:42:47 -0700839 ErrorCode uma_error_code = GetBaseErrorCode(code);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800840
841 // If the code doesn't have flags computed already, compute them now based on
842 // the state of the current update attempt.
David Zeuthena99981f2013-04-29 13:42:47 -0700843 uint32_t flags = code & kErrorCodeSpecialFlags;
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800844 if (!flags)
845 flags = system_state->update_attempter()->GetErrorCodeFlags();
846
847 // Determine the UMA bucket depending on the flags. But, ignore the resumed
848 // flag, as it's perfectly normal for production devices to resume their
849 // downloads and so we want to record those cases also in NormalErrorCodes
850 // bucket.
David Zeuthena99981f2013-04-29 13:42:47 -0700851 string metric = (flags & ~kErrorCodeResumedFlag) ?
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800852 "Installer.DevModeErrorCodes" : "Installer.NormalErrorCodes";
853
854 LOG(INFO) << "Sending error code " << uma_error_code
855 << " (" << CodeToString(uma_error_code) << ")"
856 << " to UMA metric: " << metric
857 << ". Flags = " << (flags ? GetFlagNames(flags) : "None");
858
859 system_state->metrics_lib()->SendEnumToUMA(metric,
860 uma_error_code,
David Zeuthena99981f2013-04-29 13:42:47 -0700861 kErrorCodeUmaReportedMax);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800862}
863
David Zeuthena99981f2013-04-29 13:42:47 -0700864string CodeToString(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800865 // If the given code has both parts (i.e. the error code part and the flags
866 // part) then strip off the flags part since the switch statement below
867 // has case statements only for the base error code or a single flag but
868 // doesn't support any combinations of those.
David Zeuthena99981f2013-04-29 13:42:47 -0700869 if ((code & kErrorCodeSpecialFlags) && (code & ~kErrorCodeSpecialFlags))
870 code = static_cast<ErrorCode>(code & ~kErrorCodeSpecialFlags);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800871 switch (code) {
David Zeuthena99981f2013-04-29 13:42:47 -0700872 case kErrorCodeSuccess: return "kErrorCodeSuccess";
873 case kErrorCodeError: return "kErrorCodeError";
874 case kErrorCodeOmahaRequestError: return "kErrorCodeOmahaRequestError";
875 case kErrorCodeOmahaResponseHandlerError:
876 return "kErrorCodeOmahaResponseHandlerError";
877 case kErrorCodeFilesystemCopierError:
878 return "kErrorCodeFilesystemCopierError";
879 case kErrorCodePostinstallRunnerError:
880 return "kErrorCodePostinstallRunnerError";
Gilad Arnold21504f02013-05-24 08:51:22 -0700881 case kErrorCodePayloadMismatchedType:
882 return "kErrorCodePayloadMismatchedType";
David Zeuthena99981f2013-04-29 13:42:47 -0700883 case kErrorCodeInstallDeviceOpenError:
884 return "kErrorCodeInstallDeviceOpenError";
885 case kErrorCodeKernelDeviceOpenError:
886 return "kErrorCodeKernelDeviceOpenError";
887 case kErrorCodeDownloadTransferError:
888 return "kErrorCodeDownloadTransferError";
889 case kErrorCodePayloadHashMismatchError:
890 return "kErrorCodePayloadHashMismatchError";
891 case kErrorCodePayloadSizeMismatchError:
892 return "kErrorCodePayloadSizeMismatchError";
893 case kErrorCodeDownloadPayloadVerificationError:
894 return "kErrorCodeDownloadPayloadVerificationError";
895 case kErrorCodeDownloadNewPartitionInfoError:
896 return "kErrorCodeDownloadNewPartitionInfoError";
897 case kErrorCodeDownloadWriteError:
898 return "kErrorCodeDownloadWriteError";
899 case kErrorCodeNewRootfsVerificationError:
900 return "kErrorCodeNewRootfsVerificationError";
901 case kErrorCodeNewKernelVerificationError:
902 return "kErrorCodeNewKernelVerificationError";
903 case kErrorCodeSignedDeltaPayloadExpectedError:
904 return "kErrorCodeSignedDeltaPayloadExpectedError";
905 case kErrorCodeDownloadPayloadPubKeyVerificationError:
906 return "kErrorCodeDownloadPayloadPubKeyVerificationError";
907 case kErrorCodePostinstallBootedFromFirmwareB:
908 return "kErrorCodePostinstallBootedFromFirmwareB";
909 case kErrorCodeDownloadStateInitializationError:
910 return "kErrorCodeDownloadStateInitializationError";
911 case kErrorCodeDownloadInvalidMetadataMagicString:
912 return "kErrorCodeDownloadInvalidMetadataMagicString";
913 case kErrorCodeDownloadSignatureMissingInManifest:
914 return "kErrorCodeDownloadSignatureMissingInManifest";
915 case kErrorCodeDownloadManifestParseError:
916 return "kErrorCodeDownloadManifestParseError";
917 case kErrorCodeDownloadMetadataSignatureError:
918 return "kErrorCodeDownloadMetadataSignatureError";
919 case kErrorCodeDownloadMetadataSignatureVerificationError:
920 return "kErrorCodeDownloadMetadataSignatureVerificationError";
921 case kErrorCodeDownloadMetadataSignatureMismatch:
922 return "kErrorCodeDownloadMetadataSignatureMismatch";
923 case kErrorCodeDownloadOperationHashVerificationError:
924 return "kErrorCodeDownloadOperationHashVerificationError";
925 case kErrorCodeDownloadOperationExecutionError:
926 return "kErrorCodeDownloadOperationExecutionError";
927 case kErrorCodeDownloadOperationHashMismatch:
928 return "kErrorCodeDownloadOperationHashMismatch";
929 case kErrorCodeOmahaRequestEmptyResponseError:
930 return "kErrorCodeOmahaRequestEmptyResponseError";
931 case kErrorCodeOmahaRequestXMLParseError:
932 return "kErrorCodeOmahaRequestXMLParseError";
933 case kErrorCodeDownloadInvalidMetadataSize:
934 return "kErrorCodeDownloadInvalidMetadataSize";
935 case kErrorCodeDownloadInvalidMetadataSignature:
936 return "kErrorCodeDownloadInvalidMetadataSignature";
937 case kErrorCodeOmahaResponseInvalid:
938 return "kErrorCodeOmahaResponseInvalid";
939 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
940 return "kErrorCodeOmahaUpdateIgnoredPerPolicy";
941 case kErrorCodeOmahaUpdateDeferredPerPolicy:
942 return "kErrorCodeOmahaUpdateDeferredPerPolicy";
943 case kErrorCodeOmahaErrorInHTTPResponse:
944 return "kErrorCodeOmahaErrorInHTTPResponse";
945 case kErrorCodeDownloadOperationHashMissingError:
946 return "kErrorCodeDownloadOperationHashMissingError";
947 case kErrorCodeDownloadMetadataSignatureMissingError:
948 return "kErrorCodeDownloadMetadataSignatureMissingError";
949 case kErrorCodeOmahaUpdateDeferredForBackoff:
950 return "kErrorCodeOmahaUpdateDeferredForBackoff";
951 case kErrorCodePostinstallPowerwashError:
952 return "kErrorCodePostinstallPowerwashError";
953 case kErrorCodeUpdateCanceledByChannelChange:
954 return "kErrorCodeUpdateCanceledByChannelChange";
955 case kErrorCodeUmaReportedMax:
956 return "kErrorCodeUmaReportedMax";
957 case kErrorCodeOmahaRequestHTTPResponseBase:
958 return "kErrorCodeOmahaRequestHTTPResponseBase";
959 case kErrorCodeResumedFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800960 return "Resumed";
David Zeuthena99981f2013-04-29 13:42:47 -0700961 case kErrorCodeDevModeFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800962 return "DevMode";
David Zeuthena99981f2013-04-29 13:42:47 -0700963 case kErrorCodeTestImageFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800964 return "TestImage";
David Zeuthena99981f2013-04-29 13:42:47 -0700965 case kErrorCodeTestOmahaUrlFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800966 return "TestOmahaUrl";
David Zeuthena99981f2013-04-29 13:42:47 -0700967 case kErrorCodeSpecialFlags:
968 return "kErrorCodeSpecialFlags";
Don Garrett81018e02013-07-30 18:46:31 -0700969 case kErrorCodePostinstallFirmwareRONotUpdatable:
970 return "kErrorCodePostinstallFirmwareRONotUpdatable";
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800971 // Don't add a default case to let the compiler warn about newly added
972 // error codes which should be added here.
973 }
974
975 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
976}
Jay Srinivasanf0572052012-10-23 18:12:56 -0700977
Gilad Arnold30dedd82013-07-03 06:19:09 -0700978bool CreatePowerwashMarkerFile(const char* file_path) {
979 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
980 bool result = utils::WriteFile(marker_file,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700981 kPowerwashCommand,
982 strlen(kPowerwashCommand));
Gilad Arnold30dedd82013-07-03 06:19:09 -0700983 if (result) {
984 LOG(INFO) << "Created " << marker_file << " to powerwash on next reboot";
985 } else {
986 PLOG(ERROR) << "Error in creating powerwash marker file: " << marker_file;
987 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700988
989 return result;
990}
991
Gilad Arnold30dedd82013-07-03 06:19:09 -0700992bool DeletePowerwashMarkerFile(const char* file_path) {
993 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
994 const FilePath kPowerwashMarkerPath(marker_file);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700995 bool result = file_util::Delete(kPowerwashMarkerPath, false);
996
997 if (result)
998 LOG(INFO) << "Successfully deleted the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -0700999 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001000 else
1001 PLOG(ERROR) << "Could not delete the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001002 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001003
1004 return result;
1005}
1006
Chris Sosad317e402013-06-12 13:47:09 -07001007bool GetInstallDev(const std::string& boot_dev, std::string* install_dev) {
1008 TEST_AND_RETURN_FALSE(StringHasPrefix(boot_dev, "/dev/"));
Liam McLoughlin049d1652013-07-31 18:47:46 -07001009 string::iterator it;
1010 string ubiblock_prefix("/dev/ubiblock");
1011
1012 install_dev->assign(boot_dev);
1013
1014 if(StringHasPrefix(boot_dev, ubiblock_prefix)) {
1015 // UBI-based device
1016 it = install_dev->begin() + ubiblock_prefix.length();
1017 } else {
1018 // non-UBI device
1019 it = install_dev->end() - 1; // last character in string
1020 }
1021
Chris Sosad317e402013-06-12 13:47:09 -07001022 // Right now, we just switch '3' and '5' partition numbers.
Liam McLoughlin049d1652013-07-31 18:47:46 -07001023 TEST_AND_RETURN_FALSE(*it == '3' || *it == '5');
1024 *it = (*it == '3' ? '5' : '3');
1025
Chris Sosad317e402013-06-12 13:47:09 -07001026 return true;
1027}
1028
David Zeuthen8f191b22013-08-06 12:27:50 -07001029bool IsP2PAllowedForInteractiveChecks() {
1030 struct stat statbuf;
1031 return stat(kP2PAllowInteractiveMarkerFile, &statbuf) == 0;
1032}
1033
David Zeuthen27a48bc2013-08-06 12:06:29 -07001034Time TimeFromStructTimespec(struct timespec *ts) {
1035 int64 us = static_cast<int64>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
1036 static_cast<int64>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
1037 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
1038}
1039
1040gchar** StringVectorToGStrv(const vector<string> &vector) {
1041 GPtrArray *p = g_ptr_array_new();
1042 for (std::vector<string>::const_iterator i = vector.begin();
1043 i != vector.end(); ++i) {
1044 g_ptr_array_add(p, g_strdup(i->c_str()));
1045 }
1046 g_ptr_array_add(p, NULL);
1047 return reinterpret_cast<gchar**>(g_ptr_array_free(p, FALSE));
1048}
1049
1050string StringVectorToString(const vector<string> &vector) {
1051 string str = "[";
1052 for (std::vector<string>::const_iterator i = vector.begin();
1053 i != vector.end(); ++i) {
1054 if (i != vector.begin())
1055 str += ", ";
1056 str += '"';
1057 str += *i;
1058 str += '"';
1059 }
1060 str += "]";
1061 return str;
1062}
1063
David Zeuthen8f191b22013-08-06 12:27:50 -07001064string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
1065 string encoded_hash;
1066 OmahaHashCalculator::Base64Encode(payload_hash.c_str(),
1067 payload_hash.size(),
1068 &encoded_hash);
1069 return StringPrintf("cros_update_size_%zu_hash_%s",
1070 payload_size,
1071 encoded_hash.c_str());
1072}
1073
adlr@google.com3defe6a2009-12-04 20:57:17 +00001074} // namespace utils
1075
1076} // namespace chromeos_update_engine