blob: fee34393ae95d16824c300b1f6a16b1375c0bacc [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>
Darin Petkovf74eb652010-08-04 12:08:38 -070021
Darin Petkovd3f8c892010-10-12 21:38:45 -070022#include <base/eintr_wrapper.h>
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>
Will Drewry8f71da82010-08-30 14:07:11 -050026#include <base/rand_util.h>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070027#include <base/string_number_conversions.h>
Will Drewry8f71da82010-08-30 14:07:11 -050028#include <base/string_util.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040029#include <base/stringprintf.h>
Gilad Arnold8e3f1262013-01-08 14:59:54 -080030#include <glib.h>
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -080031#include <google/protobuf/stubs/common.h>
Will Drewry8f71da82010-08-30 14:07:11 -050032#include <rootdev/rootdev.h>
33
Andrew de los Reyes970bb282009-12-09 16:34:04 -080034#include "update_engine/file_writer.h"
Darin Petkov33d30642010-08-04 10:18:57 -070035#include "update_engine/omaha_request_params.h"
Darin Petkov296889c2010-07-23 16:20:54 -070036#include "update_engine/subprocess.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080037#include "update_engine/system_state.h"
38#include "update_engine/update_attempter.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000039
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070040using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080041using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000042using std::min;
43using std::string;
44using std::vector;
45
46namespace chromeos_update_engine {
47
Ben Chan77a1eba2012-10-07 22:54:55 -070048namespace {
49
50// The following constants control how UnmountFilesystem should retry if
51// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
52// one second.
53const int kUnmountMaxNumOfRetries = 5;
54const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
55
56} // namespace
57
adlr@google.com3defe6a2009-12-04 20:57:17 +000058namespace utils {
59
Darin Petkova07586b2010-10-20 13:41:15 -070060static const char kDevImageMarker[] = "/root/.dev_mode";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070061const char* const kStatefulPartition = "/mnt/stateful_partition";
Darin Petkov2a0e6332010-09-24 14:43:41 -070062
Chris Sosa4f8ee272012-11-30 13:01:54 -080063// Cgroup container is created in update-engine's upstart script located at
64// /etc/init/update-engine.conf.
65static const char kCGroupDir[] = "/sys/fs/cgroup/cpu/update-engine";
66
Darin Petkov33d30642010-08-04 10:18:57 -070067bool IsOfficialBuild() {
Darin Petkova07586b2010-10-20 13:41:15 -070068 return !file_util::PathExists(FilePath(kDevImageMarker));
Darin Petkov33d30642010-08-04 10:18:57 -070069}
70
Darin Petkovc91dd6b2011-01-10 12:31:34 -080071bool IsNormalBootMode() {
Darin Petkov44d98d92011-03-21 16:08:11 -070072 // TODO(petkov): Convert to a library call once a crossystem library is
73 // available (crosbug.com/13291).
74 int exit_code = 0;
75 vector<string> cmd(1, "/usr/bin/crossystem");
76 cmd.push_back("devsw_boot?1");
77
78 // Assume dev mode if the dev switch is set to 1 and there was no error
79 // executing crossystem. Assume normal mode otherwise.
Darin Petkov85d02b72011-05-17 13:25:51 -070080 bool success = Subprocess::SynchronousExec(cmd, &exit_code, NULL);
Darin Petkov44d98d92011-03-21 16:08:11 -070081 bool dev_mode = success && exit_code == 0;
82 LOG_IF(INFO, dev_mode) << "Booted in dev mode.";
83 return !dev_mode;
Darin Petkovc91dd6b2011-01-10 12:31:34 -080084}
85
Darin Petkovf2065b42011-05-17 16:36:27 -070086string GetHardwareClass() {
87 // TODO(petkov): Convert to a library call once a crossystem library is
88 // available (crosbug.com/13291).
89 int exit_code = 0;
90 vector<string> cmd(1, "/usr/bin/crossystem");
91 cmd.push_back("hwid");
92
93 string hwid;
94 bool success = Subprocess::SynchronousExec(cmd, &exit_code, &hwid);
95 if (success && !exit_code) {
96 TrimWhitespaceASCII(hwid, TRIM_ALL, &hwid);
97 return hwid;
98 }
99 LOG(ERROR) << "Unable to read HWID (" << exit_code << ") " << hwid;
100 return "";
101}
102
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800103bool WriteFile(const char* path, const char* data, int data_len) {
104 DirectFileWriter writer;
105 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
106 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700107 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800108 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800109 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800110 return true;
111}
112
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700113bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700114 const char* c_buf = static_cast<const char*>(buf);
115 ssize_t bytes_written = 0;
116 while (bytes_written < static_cast<ssize_t>(count)) {
117 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
118 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
119 bytes_written += rc;
120 }
121 return true;
122}
123
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700124bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
125 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700126 size_t bytes_written = 0;
127 int num_attempts = 0;
128 while (bytes_written < count) {
129 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700130 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
131 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700132 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
133 if (rc < 0) {
134 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
135 << " bytes_written=" << bytes_written
136 << " count=" << count << " offset=" << offset;
137 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700138 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
139 bytes_written += rc;
140 }
141 return true;
142}
143
144bool PReadAll(int fd, void* buf, size_t count, off_t offset,
145 ssize_t* out_bytes_read) {
146 char* c_buf = static_cast<char*>(buf);
147 ssize_t bytes_read = 0;
148 while (bytes_read < static_cast<ssize_t>(count)) {
149 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
150 offset + bytes_read);
151 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
152 if (rc == 0) {
153 break;
154 }
155 bytes_read += rc;
156 }
157 *out_bytes_read = bytes_read;
158 return true;
Darin Petkov296889c2010-07-23 16:20:54 -0700159
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700160}
161
Gilad Arnold19a45f02012-07-19 12:36:10 -0700162// Append |nbytes| of content from |buf| to the vector pointed to by either
163// |vec_p| or |str_p|.
164static void AppendBytes(const char* buf, size_t nbytes,
165 std::vector<char>* vec_p) {
166 CHECK(buf);
167 CHECK(vec_p);
168 vec_p->insert(vec_p->end(), buf, buf + nbytes);
169}
170static void AppendBytes(const char* buf, size_t nbytes,
171 std::string* str_p) {
172 CHECK(buf);
173 CHECK(str_p);
174 str_p->append(buf, nbytes);
175}
176
177// Reads from an open file |fp|, appending the read content to the container
178// pointer to by |out_p|. Returns true upon successful reading all of the
179// file's content, false otherwise.
180template <class T>
181static bool Read(FILE* fp, T* out_p) {
182 CHECK(fp);
183 char buf[1024];
184 while (size_t nbytes = fread(buf, 1, sizeof(buf), fp))
185 AppendBytes(buf, nbytes, out_p);
186 return feof(fp) && !ferror(fp);
187}
188
189// Opens a file |path| for reading, then uses |append_func| to append its
190// content to a container |out_p|.
191template <class T>
192static bool ReadFileAndAppend(const std::string& path, T* out_p) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000193 FILE* fp = fopen(path.c_str(), "r");
194 if (!fp)
195 return false;
Gilad Arnold19a45f02012-07-19 12:36:10 -0700196 bool success = Read(fp, out_p);
197 return (success && !fclose(fp));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000198}
199
Gilad Arnold19a45f02012-07-19 12:36:10 -0700200// Invokes a pipe |cmd|, then uses |append_func| to append its stdout to a
201// container |out_p|.
202template <class T>
203static bool ReadPipeAndAppend(const std::string& cmd, T* out_p) {
204 FILE* fp = popen(cmd.c_str(), "r");
205 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000206 return false;
Gilad Arnold19a45f02012-07-19 12:36:10 -0700207 bool success = Read(fp, out_p);
208 return (success && pclose(fp) >= 0);
209}
210
211
212bool ReadFile(const std::string& path, std::vector<char>* out_p) {
213 return ReadFileAndAppend(path, out_p);
214}
215
216bool ReadFile(const std::string& path, std::string* out_p) {
217 return ReadFileAndAppend(path, out_p);
218}
219
220bool ReadPipe(const std::string& cmd, std::vector<char>* out_p) {
221 return ReadPipeAndAppend(cmd, out_p);
222}
223
224bool ReadPipe(const std::string& cmd, std::string* out_p) {
225 return ReadPipeAndAppend(cmd, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000226}
227
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700228off_t FileSize(const string& path) {
229 struct stat stbuf;
230 int rc = stat(path.c_str(), &stbuf);
231 CHECK_EQ(rc, 0);
232 if (rc < 0)
233 return rc;
234 return stbuf.st_size;
235}
236
adlr@google.com3defe6a2009-12-04 20:57:17 +0000237void HexDumpArray(const unsigned char* const arr, const size_t length) {
238 const unsigned char* const char_arr =
239 reinterpret_cast<const unsigned char* const>(arr);
240 LOG(INFO) << "Logging array of length: " << length;
241 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700242 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000243 const unsigned int bytes_remaining = length - i;
244 const unsigned int bytes_per_this_line = min(bytes_per_line,
245 bytes_remaining);
246 char header[100];
247 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
248 TEST_AND_RETURN(r == 13);
249 string line = header;
250 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
251 char buf[20];
252 unsigned char c = char_arr[i + j];
253 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
254 TEST_AND_RETURN(r == 3);
255 line += buf;
256 }
257 LOG(INFO) << line;
258 }
259}
260
261namespace {
262class ScopedDirCloser {
263 public:
264 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
265 ~ScopedDirCloser() {
266 if (dir_ && *dir_) {
267 int r = closedir(*dir_);
268 TEST_AND_RETURN_ERRNO(r == 0);
269 *dir_ = NULL;
270 dir_ = NULL;
271 }
272 }
273 private:
274 DIR** dir_;
275};
276} // namespace {}
277
278bool RecursiveUnlinkDir(const std::string& path) {
279 struct stat stbuf;
280 int r = lstat(path.c_str(), &stbuf);
281 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
282 if ((r < 0) && (errno == ENOENT))
283 // path request is missing. that's fine.
284 return true;
285 if (!S_ISDIR(stbuf.st_mode)) {
286 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700287 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000288 // success or path disappeared before we could unlink.
289 return true;
290 }
291 {
292 // We have a dir, unlink all children, then delete dir
293 DIR *dir = opendir(path.c_str());
294 TEST_AND_RETURN_FALSE_ERRNO(dir);
295 ScopedDirCloser dir_closer(&dir);
296 struct dirent dir_entry;
297 struct dirent *dir_entry_p;
298 int err = 0;
299 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
300 if (dir_entry_p == NULL) {
301 // end of stream reached
302 break;
303 }
304 // Skip . and ..
305 if (!strcmp(dir_entry_p->d_name, ".") ||
306 !strcmp(dir_entry_p->d_name, ".."))
307 continue;
308 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700309 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000310 }
311 TEST_AND_RETURN_FALSE(err == 0);
312 }
313 // unlink dir
314 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
315 return true;
316}
317
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700318string RootDevice(const string& partition_device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700319 FilePath device_path(partition_device);
320 if (device_path.DirName().value() != "/dev") {
321 return "";
322 }
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700323 string::const_iterator it = --partition_device.end();
324 for (; it >= partition_device.begin(); --it) {
325 if (!isdigit(*it))
326 break;
327 }
328 // Some devices contain a p before the partitions. For example:
329 // /dev/mmc0p4 should be shortened to /dev/mmc0.
330 if (*it == 'p')
331 --it;
332 return string(partition_device.begin(), it + 1);
333}
334
335string PartitionNumber(const string& partition_device) {
336 CHECK(!partition_device.empty());
337 string::const_iterator it = --partition_device.end();
338 for (; it >= partition_device.begin(); --it) {
339 if (!isdigit(*it))
340 break;
341 }
342 return string(it + 1, partition_device.end());
343}
344
Darin Petkovf74eb652010-08-04 12:08:38 -0700345string SysfsBlockDevice(const string& device) {
346 FilePath device_path(device);
347 if (device_path.DirName().value() != "/dev") {
348 return "";
349 }
350 return FilePath("/sys/block").Append(device_path.BaseName()).value();
351}
352
353bool IsRemovableDevice(const std::string& device) {
354 string sysfs_block = SysfsBlockDevice(device);
355 string removable;
356 if (sysfs_block.empty() ||
357 !file_util::ReadFileToString(FilePath(sysfs_block).Append("removable"),
358 &removable)) {
359 return false;
360 }
361 TrimWhitespaceASCII(removable, TRIM_ALL, &removable);
362 return removable == "1";
363}
364
adlr@google.com3defe6a2009-12-04 20:57:17 +0000365std::string ErrnoNumberAsString(int err) {
366 char buf[100];
367 buf[0] = '\0';
368 return strerror_r(err, buf, sizeof(buf));
369}
370
371std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
372 string ret;
373 bool last_insert_was_slash = false;
374 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
375 if (*it == '/') {
376 if (last_insert_was_slash)
377 continue;
378 last_insert_was_slash = true;
379 } else {
380 last_insert_was_slash = false;
381 }
382 ret.push_back(*it);
383 }
384 if (strip_trailing_slash && last_insert_was_slash) {
385 string::size_type last_non_slash = ret.find_last_not_of('/');
386 if (last_non_slash != string::npos) {
387 ret.resize(last_non_slash + 1);
388 } else {
389 ret = "";
390 }
391 }
392 return ret;
393}
394
395bool FileExists(const char* path) {
396 struct stat stbuf;
397 return 0 == lstat(path, &stbuf);
398}
399
Darin Petkov30291ed2010-11-12 10:23:06 -0800400bool IsSymlink(const char* path) {
401 struct stat stbuf;
402 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
403}
404
adlr@google.com3defe6a2009-12-04 20:57:17 +0000405std::string TempFilename(string path) {
406 static const string suffix("XXXXXX");
407 CHECK(StringHasSuffix(path, suffix));
408 do {
409 string new_suffix;
410 for (unsigned int i = 0; i < suffix.size(); i++) {
411 int r = rand() % (26 * 2 + 10); // [a-zA-Z0-9]
412 if (r < 26)
413 new_suffix.append(1, 'a' + r);
414 else if (r < (26 * 2))
415 new_suffix.append(1, 'A' + r - 26);
416 else
417 new_suffix.append(1, '0' + r - (26 * 2));
418 }
419 CHECK_EQ(new_suffix.size(), suffix.size());
420 path.resize(path.size() - new_suffix.size());
421 path.append(new_suffix);
422 } while (FileExists(path.c_str()));
423 return path;
424}
425
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700426bool MakeTempFile(const std::string& filename_template,
427 std::string* filename,
428 int* fd) {
429 DCHECK(filename || fd);
430 vector<char> buf(filename_template.size() + 1);
431 memcpy(&buf[0], filename_template.data(), filename_template.size());
432 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700433
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700434 int mkstemp_fd = mkstemp(&buf[0]);
435 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
436 if (filename) {
437 *filename = &buf[0];
438 }
439 if (fd) {
440 *fd = mkstemp_fd;
441 } else {
442 close(mkstemp_fd);
443 }
444 return true;
445}
446
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700447bool MakeTempDirectory(const std::string& dirname_template,
448 std::string* dirname) {
449 DCHECK(dirname);
450 vector<char> buf(dirname_template.size() + 1);
451 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
452 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700453
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700454 char* return_code = mkdtemp(&buf[0]);
455 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
456 *dirname = &buf[0];
457 return true;
458}
459
adlr@google.com3defe6a2009-12-04 20:57:17 +0000460bool StringHasSuffix(const std::string& str, const std::string& suffix) {
461 if (suffix.size() > str.size())
462 return false;
463 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
464}
465
466bool StringHasPrefix(const std::string& str, const std::string& prefix) {
467 if (prefix.size() > str.size())
468 return false;
469 return 0 == str.compare(0, prefix.size(), prefix);
470}
471
Will Drewry8f71da82010-08-30 14:07:11 -0500472const std::string BootDevice() {
473 char boot_path[PATH_MAX];
474 // Resolve the boot device path fully, including dereferencing
475 // through dm-verity.
476 int ret = rootdev(boot_path, sizeof(boot_path), true, false);
477
478 if (ret < 0) {
479 LOG(ERROR) << "rootdev failed to find the root device";
adlr@google.com3defe6a2009-12-04 20:57:17 +0000480 return "";
481 }
Will Drewry8f71da82010-08-30 14:07:11 -0500482 LOG_IF(WARNING, ret > 0) << "rootdev found a device name with no device node";
483
484 // This local variable is used to construct the return string and is not
485 // passed around after use.
486 return boot_path;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000487}
488
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700489const string BootKernelDevice(const std::string& boot_device) {
490 // Currntly this assumes the last digit of the boot device is
491 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
492 // get the kernel device.
493 string ret = boot_device;
494 if (ret.empty())
495 return ret;
496 char last_char = ret[ret.size() - 1];
497 if (last_char == '3' || last_char == '5' || last_char == '7') {
498 ret[ret.size() - 1] = last_char - 1;
499 return ret;
500 }
501 return "";
502}
503
adlr@google.com3defe6a2009-12-04 20:57:17 +0000504bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700505 const string& mountpoint,
506 unsigned long mountflags) {
507 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000508 if (rc < 0) {
509 string msg = ErrnoNumberAsString(errno);
510 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
511 << device << " on " << mountpoint;
512 return false;
513 }
514 return true;
515}
516
517bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700518 for (int num_retries = 0; ; ++num_retries) {
519 if (umount(mountpoint.c_str()) == 0)
520 break;
521
522 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
523 num_retries < kUnmountMaxNumOfRetries);
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800524 g_usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700525 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000526 return true;
527}
528
Darin Petkovd3f8c892010-10-12 21:38:45 -0700529bool GetFilesystemSize(const std::string& device,
530 int* out_block_count,
531 int* out_block_size) {
532 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
533 TEST_AND_RETURN_FALSE(fd >= 0);
534 ScopedFdCloser fd_closer(&fd);
535 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
536}
537
538bool GetFilesystemSizeFromFD(int fd,
539 int* out_block_count,
540 int* out_block_size) {
541 TEST_AND_RETURN_FALSE(fd >= 0);
542
543 // Determine the ext3 filesystem size by directly reading the block count and
544 // block size information from the superblock. See include/linux/ext3_fs.h for
545 // more details on the structure.
546 ssize_t kBufferSize = 16 * sizeof(uint32_t);
547 char buffer[kBufferSize];
548 const int kSuperblockOffset = 1024;
549 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
550 kBufferSize) {
551 PLOG(ERROR) << "Unable to determine file system size:";
552 return false;
553 }
554 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
555 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
556 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
557 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
558 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
559 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
560 block_count = le32toh(block_count);
561 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
562 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
563 magic = le16toh(magic);
564
565 // Sanity check the parameters.
566 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
567 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
568 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
569 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
570 int block_size = 1 << log_block_size;
571 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
572 block_size <= kExt3MaxBlockSize);
573 TEST_AND_RETURN_FALSE(block_count > 0);
574
575 if (out_block_count) {
576 *out_block_count = block_count;
577 }
578 if (out_block_size) {
579 *out_block_size = block_size;
580 }
581 return true;
582}
583
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700584bool GetBootloader(BootLoader* out_bootloader) {
585 // For now, hardcode to syslinux.
586 *out_bootloader = BootLoader_SYSLINUX;
587 return true;
588}
589
Darin Petkova0b9e772011-10-06 05:05:56 -0700590string GetAndFreeGError(GError** error) {
591 if (!*error) {
592 return "Unknown GLib error.";
593 }
594 string message =
595 base::StringPrintf("GError(%d): %s",
596 (*error)->code,
597 (*error)->message ? (*error)->message : "(unknown)");
598 g_error_free(*error);
599 *error = NULL;
600 return message;
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700601}
602
Darin Petkov296889c2010-07-23 16:20:54 -0700603bool Reboot() {
604 vector<string> command;
605 command.push_back("/sbin/shutdown");
606 command.push_back("-r");
607 command.push_back("now");
608 int rc = 0;
Darin Petkov85d02b72011-05-17 13:25:51 -0700609 Subprocess::SynchronousExec(command, &rc, NULL);
Darin Petkov296889c2010-07-23 16:20:54 -0700610 TEST_AND_RETURN_FALSE(rc == 0);
611 return true;
612}
613
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800614namespace {
615// Do the actual trigger. We do it as a main-loop callback to (try to) get a
616// consistent stack trace.
617gboolean TriggerCrashReporterUpload(void* unused) {
618 pid_t pid = fork();
619 CHECK(pid >= 0) << "fork failed"; // fork() failed. Something is very wrong.
620 if (pid == 0) {
621 // We are the child. Crash.
622 abort(); // never returns
623 }
624 // We are the parent. Wait for child to terminate.
625 pid_t result = waitpid(pid, NULL, 0);
626 LOG_IF(ERROR, result < 0) << "waitpid() failed";
627 return FALSE; // Don't call this callback again
628}
629} // namespace {}
630
631void ScheduleCrashReporterUpload() {
632 g_idle_add(&TriggerCrashReporterUpload, NULL);
633}
634
Chris Sosa4f8ee272012-11-30 13:01:54 -0800635bool SetCpuShares(CpuShares shares) {
636 string string_shares = base::IntToString(static_cast<int>(shares));
637 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
638 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
639 if(utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
640 string_shares.size())){
641 return true;
642 } else {
643 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
644 << " using " << cpu_shares_file;
645 return false;
646 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700647}
648
Chris Sosa4f8ee272012-11-30 13:01:54 -0800649int CompareCpuShares(CpuShares shares_lhs,
650 CpuShares shares_rhs) {
651 return static_cast<int>(shares_lhs) - static_cast<int>(shares_rhs);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700652}
653
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700654int FuzzInt(int value, unsigned int range) {
655 int min = value - range / 2;
656 int max = value + range - range / 2;
657 return base::RandInt(min, max);
658}
659
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800660gboolean GlibRunClosure(gpointer data) {
661 google::protobuf::Closure* callback =
662 reinterpret_cast<google::protobuf::Closure*>(data);
663 callback->Run();
664 return FALSE;
665}
666
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700667string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800668 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700669}
670
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800671string FormatTimeDelta(TimeDelta delta) {
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700672 // Canonicalize into days, hours, minutes, seconds and microseconds.
673 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800674 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700675 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800676 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700677 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800678 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700679 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800680 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700681 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800682
683 // Construct and return string.
684 string str;
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700685 if (days)
686 base::StringAppendF(&str, "%ud", days);
687 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800688 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700689 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800690 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700691 base::StringAppendF(&str, "%u", secs);
692 if (usecs) {
693 int width = 6;
694 while ((usecs / 10) * 10 == usecs) {
695 usecs /= 10;
696 width--;
697 }
698 base::StringAppendF(&str, ".%0*u", width, usecs);
699 }
700 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800701 return str;
702}
703
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700704string ToString(const Time utc_time) {
705 Time::Exploded exp_time;
706 utc_time.UTCExplode(&exp_time);
707 return StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
708 exp_time.month,
709 exp_time.day_of_month,
710 exp_time.year,
711 exp_time.hour,
712 exp_time.minute,
713 exp_time.second);
714}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000715
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800716ActionExitCode GetBaseErrorCode(ActionExitCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700717 // Ignore the higher order bits in the code by applying the mask as
718 // we want the enumerations to be in the small contiguous range
Jay Srinivasanedce2832012-10-24 18:57:47 -0700719 // with values less than kActionCodeUmaReportedMax.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800720 ActionExitCode base_code = static_cast<ActionExitCode>(code & ~kSpecialFlags);
Jay Srinivasanf0572052012-10-23 18:12:56 -0700721
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800722 // Make additional adjustments required for UMA and error classification.
723 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
724 // chromium-os:34369.
725 if (base_code >= kActionCodeOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700726 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800727 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800728 LOG(INFO) << "Converting error code " << base_code
729 << " to kActionCodeOmahaErrorInHTTPResponse";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800730 base_code = kActionCodeOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700731 }
732
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800733 return base_code;
734}
735
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800736// Returns a printable version of the various flags denoted in the higher order
737// bits of the given code. Returns an empty string if none of those bits are
738// set.
739string GetFlagNames(uint32_t code) {
740 uint32_t flags = code & kSpecialFlags;
741 string flag_names;
742 string separator = "";
743 for(size_t i = 0; i < sizeof(flags) * 8; i++) {
744 uint32_t flag = flags & (1 << i);
745 if (flag) {
746 flag_names += separator + CodeToString(static_cast<ActionExitCode>(flag));
747 separator = ", ";
748 }
749 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800750
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800751 return flag_names;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700752}
753
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800754void SendErrorCodeToUma(SystemState* system_state, ActionExitCode code) {
755 if (!system_state)
756 return;
757
758 ActionExitCode uma_error_code = GetBaseErrorCode(code);
759
760 // If the code doesn't have flags computed already, compute them now based on
761 // the state of the current update attempt.
762 uint32_t flags = code & kSpecialFlags;
763 if (!flags)
764 flags = system_state->update_attempter()->GetErrorCodeFlags();
765
766 // Determine the UMA bucket depending on the flags. But, ignore the resumed
767 // flag, as it's perfectly normal for production devices to resume their
768 // downloads and so we want to record those cases also in NormalErrorCodes
769 // bucket.
770 string metric = (flags & ~kActionCodeResumedFlag) ?
771 "Installer.DevModeErrorCodes" : "Installer.NormalErrorCodes";
772
773 LOG(INFO) << "Sending error code " << uma_error_code
774 << " (" << CodeToString(uma_error_code) << ")"
775 << " to UMA metric: " << metric
776 << ". Flags = " << (flags ? GetFlagNames(flags) : "None");
777
778 system_state->metrics_lib()->SendEnumToUMA(metric,
779 uma_error_code,
780 kActionCodeUmaReportedMax);
781}
782
783string CodeToString(ActionExitCode code) {
784 // If the given code has both parts (i.e. the error code part and the flags
785 // part) then strip off the flags part since the switch statement below
786 // has case statements only for the base error code or a single flag but
787 // doesn't support any combinations of those.
788 if ((code & kSpecialFlags) && (code & ~kSpecialFlags))
789 code = static_cast<ActionExitCode>(code & ~kSpecialFlags);
790 switch (code) {
791 case kActionCodeSuccess: return "kActionCodeSuccess";
792 case kActionCodeError: return "kActionCodeError";
793 case kActionCodeOmahaRequestError: return "kActionCodeOmahaRequestError";
794 case kActionCodeOmahaResponseHandlerError:
795 return "kActionCodeOmahaResponseHandlerError";
796 case kActionCodeFilesystemCopierError:
797 return "kActionCodeFilesystemCopierError";
798 case kActionCodePostinstallRunnerError:
799 return "kActionCodePostinstallRunnerError";
800 case kActionCodeSetBootableFlagError:
801 return "kActionCodeSetBootableFlagError";
802 case kActionCodeInstallDeviceOpenError:
803 return "kActionCodeInstallDeviceOpenError";
804 case kActionCodeKernelDeviceOpenError:
805 return "kActionCodeKernelDeviceOpenError";
806 case kActionCodeDownloadTransferError:
807 return "kActionCodeDownloadTransferError";
808 case kActionCodePayloadHashMismatchError:
809 return "kActionCodePayloadHashMismatchError";
810 case kActionCodePayloadSizeMismatchError:
811 return "kActionCodePayloadSizeMismatchError";
812 case kActionCodeDownloadPayloadVerificationError:
813 return "kActionCodeDownloadPayloadVerificationError";
814 case kActionCodeDownloadNewPartitionInfoError:
815 return "kActionCodeDownloadNewPartitionInfoError";
816 case kActionCodeDownloadWriteError:
817 return "kActionCodeDownloadWriteError";
818 case kActionCodeNewRootfsVerificationError:
819 return "kActionCodeNewRootfsVerificationError";
820 case kActionCodeNewKernelVerificationError:
821 return "kActionCodeNewKernelVerificationError";
822 case kActionCodeSignedDeltaPayloadExpectedError:
823 return "kActionCodeSignedDeltaPayloadExpectedError";
824 case kActionCodeDownloadPayloadPubKeyVerificationError:
825 return "kActionCodeDownloadPayloadPubKeyVerificationError";
826 case kActionCodePostinstallBootedFromFirmwareB:
827 return "kActionCodePostinstallBootedFromFirmwareB";
828 case kActionCodeDownloadStateInitializationError:
829 return "kActionCodeDownloadStateInitializationError";
830 case kActionCodeDownloadInvalidMetadataMagicString:
831 return "kActionCodeDownloadInvalidMetadataMagicString";
832 case kActionCodeDownloadSignatureMissingInManifest:
833 return "kActionCodeDownloadSignatureMissingInManifest";
834 case kActionCodeDownloadManifestParseError:
835 return "kActionCodeDownloadManifestParseError";
836 case kActionCodeDownloadMetadataSignatureError:
837 return "kActionCodeDownloadMetadataSignatureError";
838 case kActionCodeDownloadMetadataSignatureVerificationError:
839 return "kActionCodeDownloadMetadataSignatureVerificationError";
840 case kActionCodeDownloadMetadataSignatureMismatch:
841 return "kActionCodeDownloadMetadataSignatureMismatch";
842 case kActionCodeDownloadOperationHashVerificationError:
843 return "kActionCodeDownloadOperationHashVerificationError";
844 case kActionCodeDownloadOperationExecutionError:
845 return "kActionCodeDownloadOperationExecutionError";
846 case kActionCodeDownloadOperationHashMismatch:
847 return "kActionCodeDownloadOperationHashMismatch";
848 case kActionCodeOmahaRequestEmptyResponseError:
849 return "kActionCodeOmahaRequestEmptyResponseError";
850 case kActionCodeOmahaRequestXMLParseError:
851 return "kActionCodeOmahaRequestXMLParseError";
852 case kActionCodeDownloadInvalidMetadataSize:
853 return "kActionCodeDownloadInvalidMetadataSize";
854 case kActionCodeDownloadInvalidMetadataSignature:
855 return "kActionCodeDownloadInvalidMetadataSignature";
856 case kActionCodeOmahaResponseInvalid:
857 return "kActionCodeOmahaResponseInvalid";
858 case kActionCodeOmahaUpdateIgnoredPerPolicy:
859 return "kActionCodeOmahaUpdateIgnoredPerPolicy";
860 case kActionCodeOmahaUpdateDeferredPerPolicy:
861 return "kActionCodeOmahaUpdateDeferredPerPolicy";
862 case kActionCodeOmahaErrorInHTTPResponse:
863 return "kActionCodeOmahaErrorInHTTPResponse";
864 case kActionCodeDownloadOperationHashMissingError:
865 return "kActionCodeDownloadOperationHashMissingError";
866 case kActionCodeDownloadMetadataSignatureMissingError:
867 return "kActionCodeDownloadMetadataSignatureMissingError";
868 case kActionCodeOmahaUpdateDeferredForBackoff:
869 return "kActionCodeOmahaUpdateDeferredForBackoff";
870 case kActionCodeUmaReportedMax:
871 return "kActionCodeUmaReportedMax";
872 case kActionCodeOmahaRequestHTTPResponseBase:
873 return "kActionCodeOmahaRequestHTTPResponseBase";
874 case kActionCodeResumedFlag:
875 return "Resumed";
876 case kActionCodeDevModeFlag:
877 return "DevMode";
878 case kActionCodeTestImageFlag:
879 return "TestImage";
880 case kActionCodeTestOmahaUrlFlag:
881 return "TestOmahaUrl";
882 case kSpecialFlags:
883 return "kSpecialFlags";
884 // Don't add a default case to let the compiler warn about newly added
885 // error codes which should be added here.
886 }
887
888 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
889}
Jay Srinivasanf0572052012-10-23 18:12:56 -0700890
adlr@google.com3defe6a2009-12-04 20:57:17 +0000891} // namespace utils
892
893} // namespace chromeos_update_engine