blob: 6e14f2288b8ed126bc54e5a47ef72d8bf07be243 [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>
David Zeuthen9a017f22013-04-11 16:10:26 -070018#include <time.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000019#include <unistd.h>
Darin Petkovf74eb652010-08-04 12:08:38 -070020
adlr@google.com3defe6a2009-12-04 20:57:17 +000021#include <algorithm>
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>
Will Drewry8f71da82010-08-30 14:07:11 -050029#include <base/string_util.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040030#include <base/stringprintf.h>
Gilad Arnold8e3f1262013-01-08 14:59:54 -080031#include <glib.h>
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -080032#include <google/protobuf/stubs/common.h>
Will Drewry8f71da82010-08-30 14:07:11 -050033#include <rootdev/rootdev.h>
34
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;
45using std::string;
46using std::vector;
47
48namespace chromeos_update_engine {
49
Ben Chan77a1eba2012-10-07 22:54:55 -070050namespace {
51
52// The following constants control how UnmountFilesystem should retry if
53// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
54// one second.
55const int kUnmountMaxNumOfRetries = 5;
56const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Ben Chan77a1eba2012-10-07 22:54:55 -070057} // namespace
58
adlr@google.com3defe6a2009-12-04 20:57:17 +000059namespace utils {
60
Darin Petkova07586b2010-10-20 13:41:15 -070061static const char kDevImageMarker[] = "/root/.dev_mode";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070062const char* const kStatefulPartition = "/mnt/stateful_partition";
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
Darin Petkovf2065b42011-05-17 16:36:27 -070087string GetHardwareClass() {
88 // TODO(petkov): Convert to a library call once a crossystem library is
89 // available (crosbug.com/13291).
90 int exit_code = 0;
91 vector<string> cmd(1, "/usr/bin/crossystem");
92 cmd.push_back("hwid");
93
94 string hwid;
95 bool success = Subprocess::SynchronousExec(cmd, &exit_code, &hwid);
96 if (success && !exit_code) {
97 TrimWhitespaceASCII(hwid, TRIM_ALL, &hwid);
98 return hwid;
99 }
100 LOG(ERROR) << "Unable to read HWID (" << exit_code << ") " << hwid;
101 return "";
102}
103
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800104bool WriteFile(const char* path, const char* data, int data_len) {
105 DirectFileWriter writer;
106 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
107 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700108 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800109 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800110 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800111 return true;
112}
113
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700114bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700115 const char* c_buf = static_cast<const char*>(buf);
116 ssize_t bytes_written = 0;
117 while (bytes_written < static_cast<ssize_t>(count)) {
118 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
119 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
120 bytes_written += rc;
121 }
122 return true;
123}
124
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700125bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
126 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700127 size_t bytes_written = 0;
128 int num_attempts = 0;
129 while (bytes_written < count) {
130 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700131 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
132 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700133 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
134 if (rc < 0) {
135 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
136 << " bytes_written=" << bytes_written
137 << " count=" << count << " offset=" << offset;
138 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700139 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
140 bytes_written += rc;
141 }
142 return true;
143}
144
145bool PReadAll(int fd, void* buf, size_t count, off_t offset,
146 ssize_t* out_bytes_read) {
147 char* c_buf = static_cast<char*>(buf);
148 ssize_t bytes_read = 0;
149 while (bytes_read < static_cast<ssize_t>(count)) {
150 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
151 offset + bytes_read);
152 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
153 if (rc == 0) {
154 break;
155 }
156 bytes_read += rc;
157 }
158 *out_bytes_read = bytes_read;
159 return true;
Darin Petkov296889c2010-07-23 16:20:54 -0700160
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700161}
162
Gilad Arnold19a45f02012-07-19 12:36:10 -0700163// Append |nbytes| of content from |buf| to the vector pointed to by either
164// |vec_p| or |str_p|.
165static void AppendBytes(const char* buf, size_t nbytes,
166 std::vector<char>* vec_p) {
167 CHECK(buf);
168 CHECK(vec_p);
169 vec_p->insert(vec_p->end(), buf, buf + nbytes);
170}
171static void AppendBytes(const char* buf, size_t nbytes,
172 std::string* str_p) {
173 CHECK(buf);
174 CHECK(str_p);
175 str_p->append(buf, nbytes);
176}
177
178// Reads from an open file |fp|, appending the read content to the container
179// pointer to by |out_p|. Returns true upon successful reading all of the
180// file's content, false otherwise.
181template <class T>
182static bool Read(FILE* fp, T* out_p) {
183 CHECK(fp);
184 char buf[1024];
185 while (size_t nbytes = fread(buf, 1, sizeof(buf), fp))
186 AppendBytes(buf, nbytes, out_p);
187 return feof(fp) && !ferror(fp);
188}
189
190// Opens a file |path| for reading, then uses |append_func| to append its
191// content to a container |out_p|.
192template <class T>
193static bool ReadFileAndAppend(const std::string& path, T* out_p) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000194 FILE* fp = fopen(path.c_str(), "r");
195 if (!fp)
196 return false;
Gilad Arnold19a45f02012-07-19 12:36:10 -0700197 bool success = Read(fp, out_p);
198 return (success && !fclose(fp));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000199}
200
Gilad Arnold19a45f02012-07-19 12:36:10 -0700201// Invokes a pipe |cmd|, then uses |append_func| to append its stdout to a
202// container |out_p|.
203template <class T>
204static bool ReadPipeAndAppend(const std::string& cmd, T* out_p) {
205 FILE* fp = popen(cmd.c_str(), "r");
206 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000207 return false;
Gilad Arnold19a45f02012-07-19 12:36:10 -0700208 bool success = Read(fp, out_p);
209 return (success && pclose(fp) >= 0);
210}
211
212
213bool ReadFile(const std::string& path, std::vector<char>* out_p) {
214 return ReadFileAndAppend(path, out_p);
215}
216
217bool ReadFile(const std::string& path, std::string* out_p) {
218 return ReadFileAndAppend(path, out_p);
219}
220
221bool ReadPipe(const std::string& cmd, std::vector<char>* out_p) {
222 return ReadPipeAndAppend(cmd, out_p);
223}
224
225bool ReadPipe(const std::string& cmd, std::string* out_p) {
226 return ReadPipeAndAppend(cmd, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000227}
228
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700229off_t FileSize(const string& path) {
230 struct stat stbuf;
231 int rc = stat(path.c_str(), &stbuf);
232 CHECK_EQ(rc, 0);
233 if (rc < 0)
234 return rc;
235 return stbuf.st_size;
236}
237
adlr@google.com3defe6a2009-12-04 20:57:17 +0000238void HexDumpArray(const unsigned char* const arr, const size_t length) {
239 const unsigned char* const char_arr =
240 reinterpret_cast<const unsigned char* const>(arr);
241 LOG(INFO) << "Logging array of length: " << length;
242 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700243 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000244 const unsigned int bytes_remaining = length - i;
245 const unsigned int bytes_per_this_line = min(bytes_per_line,
246 bytes_remaining);
247 char header[100];
248 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
249 TEST_AND_RETURN(r == 13);
250 string line = header;
251 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
252 char buf[20];
253 unsigned char c = char_arr[i + j];
254 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
255 TEST_AND_RETURN(r == 3);
256 line += buf;
257 }
258 LOG(INFO) << line;
259 }
260}
261
262namespace {
263class ScopedDirCloser {
264 public:
265 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
266 ~ScopedDirCloser() {
267 if (dir_ && *dir_) {
268 int r = closedir(*dir_);
269 TEST_AND_RETURN_ERRNO(r == 0);
270 *dir_ = NULL;
271 dir_ = NULL;
272 }
273 }
274 private:
275 DIR** dir_;
276};
277} // namespace {}
278
279bool RecursiveUnlinkDir(const std::string& path) {
280 struct stat stbuf;
281 int r = lstat(path.c_str(), &stbuf);
282 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
283 if ((r < 0) && (errno == ENOENT))
284 // path request is missing. that's fine.
285 return true;
286 if (!S_ISDIR(stbuf.st_mode)) {
287 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700288 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000289 // success or path disappeared before we could unlink.
290 return true;
291 }
292 {
293 // We have a dir, unlink all children, then delete dir
294 DIR *dir = opendir(path.c_str());
295 TEST_AND_RETURN_FALSE_ERRNO(dir);
296 ScopedDirCloser dir_closer(&dir);
297 struct dirent dir_entry;
298 struct dirent *dir_entry_p;
299 int err = 0;
300 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
301 if (dir_entry_p == NULL) {
302 // end of stream reached
303 break;
304 }
305 // Skip . and ..
306 if (!strcmp(dir_entry_p->d_name, ".") ||
307 !strcmp(dir_entry_p->d_name, ".."))
308 continue;
309 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700310 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000311 }
312 TEST_AND_RETURN_FALSE(err == 0);
313 }
314 // unlink dir
315 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
316 return true;
317}
318
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700319string RootDevice(const string& partition_device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700320 FilePath device_path(partition_device);
321 if (device_path.DirName().value() != "/dev") {
322 return "";
323 }
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700324 string::const_iterator it = --partition_device.end();
325 for (; it >= partition_device.begin(); --it) {
326 if (!isdigit(*it))
327 break;
328 }
329 // Some devices contain a p before the partitions. For example:
330 // /dev/mmc0p4 should be shortened to /dev/mmc0.
331 if (*it == 'p')
332 --it;
333 return string(partition_device.begin(), it + 1);
334}
335
336string PartitionNumber(const string& partition_device) {
337 CHECK(!partition_device.empty());
338 string::const_iterator it = --partition_device.end();
339 for (; it >= partition_device.begin(); --it) {
340 if (!isdigit(*it))
341 break;
342 }
343 return string(it + 1, partition_device.end());
344}
345
Darin Petkovf74eb652010-08-04 12:08:38 -0700346string SysfsBlockDevice(const string& device) {
347 FilePath device_path(device);
348 if (device_path.DirName().value() != "/dev") {
349 return "";
350 }
351 return FilePath("/sys/block").Append(device_path.BaseName()).value();
352}
353
354bool IsRemovableDevice(const std::string& device) {
355 string sysfs_block = SysfsBlockDevice(device);
356 string removable;
357 if (sysfs_block.empty() ||
358 !file_util::ReadFileToString(FilePath(sysfs_block).Append("removable"),
359 &removable)) {
360 return false;
361 }
362 TrimWhitespaceASCII(removable, TRIM_ALL, &removable);
363 return removable == "1";
364}
365
adlr@google.com3defe6a2009-12-04 20:57:17 +0000366std::string ErrnoNumberAsString(int err) {
367 char buf[100];
368 buf[0] = '\0';
369 return strerror_r(err, buf, sizeof(buf));
370}
371
372std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
373 string ret;
374 bool last_insert_was_slash = false;
375 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
376 if (*it == '/') {
377 if (last_insert_was_slash)
378 continue;
379 last_insert_was_slash = true;
380 } else {
381 last_insert_was_slash = false;
382 }
383 ret.push_back(*it);
384 }
385 if (strip_trailing_slash && last_insert_was_slash) {
386 string::size_type last_non_slash = ret.find_last_not_of('/');
387 if (last_non_slash != string::npos) {
388 ret.resize(last_non_slash + 1);
389 } else {
390 ret = "";
391 }
392 }
393 return ret;
394}
395
396bool FileExists(const char* path) {
397 struct stat stbuf;
398 return 0 == lstat(path, &stbuf);
399}
400
Darin Petkov30291ed2010-11-12 10:23:06 -0800401bool IsSymlink(const char* path) {
402 struct stat stbuf;
403 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
404}
405
adlr@google.com3defe6a2009-12-04 20:57:17 +0000406std::string TempFilename(string path) {
407 static const string suffix("XXXXXX");
408 CHECK(StringHasSuffix(path, suffix));
409 do {
410 string new_suffix;
411 for (unsigned int i = 0; i < suffix.size(); i++) {
412 int r = rand() % (26 * 2 + 10); // [a-zA-Z0-9]
413 if (r < 26)
414 new_suffix.append(1, 'a' + r);
415 else if (r < (26 * 2))
416 new_suffix.append(1, 'A' + r - 26);
417 else
418 new_suffix.append(1, '0' + r - (26 * 2));
419 }
420 CHECK_EQ(new_suffix.size(), suffix.size());
421 path.resize(path.size() - new_suffix.size());
422 path.append(new_suffix);
423 } while (FileExists(path.c_str()));
424 return path;
425}
426
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700427bool MakeTempFile(const std::string& filename_template,
428 std::string* filename,
429 int* fd) {
430 DCHECK(filename || fd);
431 vector<char> buf(filename_template.size() + 1);
432 memcpy(&buf[0], filename_template.data(), filename_template.size());
433 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700434
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700435 int mkstemp_fd = mkstemp(&buf[0]);
436 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
437 if (filename) {
438 *filename = &buf[0];
439 }
440 if (fd) {
441 *fd = mkstemp_fd;
442 } else {
443 close(mkstemp_fd);
444 }
445 return true;
446}
447
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700448bool MakeTempDirectory(const std::string& dirname_template,
449 std::string* dirname) {
450 DCHECK(dirname);
451 vector<char> buf(dirname_template.size() + 1);
452 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
453 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700454
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700455 char* return_code = mkdtemp(&buf[0]);
456 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
457 *dirname = &buf[0];
458 return true;
459}
460
adlr@google.com3defe6a2009-12-04 20:57:17 +0000461bool StringHasSuffix(const std::string& str, const std::string& suffix) {
462 if (suffix.size() > str.size())
463 return false;
464 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
465}
466
467bool StringHasPrefix(const std::string& str, const std::string& prefix) {
468 if (prefix.size() > str.size())
469 return false;
470 return 0 == str.compare(0, prefix.size(), prefix);
471}
472
Will Drewry8f71da82010-08-30 14:07:11 -0500473const std::string BootDevice() {
474 char boot_path[PATH_MAX];
475 // Resolve the boot device path fully, including dereferencing
476 // through dm-verity.
477 int ret = rootdev(boot_path, sizeof(boot_path), true, false);
478
479 if (ret < 0) {
480 LOG(ERROR) << "rootdev failed to find the root device";
adlr@google.com3defe6a2009-12-04 20:57:17 +0000481 return "";
482 }
Will Drewry8f71da82010-08-30 14:07:11 -0500483 LOG_IF(WARNING, ret > 0) << "rootdev found a device name with no device node";
484
485 // This local variable is used to construct the return string and is not
486 // passed around after use.
487 return boot_path;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000488}
489
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700490const string BootKernelDevice(const std::string& boot_device) {
491 // Currntly this assumes the last digit of the boot device is
492 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
493 // get the kernel device.
494 string ret = boot_device;
495 if (ret.empty())
496 return ret;
497 char last_char = ret[ret.size() - 1];
498 if (last_char == '3' || last_char == '5' || last_char == '7') {
499 ret[ret.size() - 1] = last_char - 1;
500 return ret;
501 }
502 return "";
503}
504
adlr@google.com3defe6a2009-12-04 20:57:17 +0000505bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700506 const string& mountpoint,
507 unsigned long mountflags) {
508 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000509 if (rc < 0) {
510 string msg = ErrnoNumberAsString(errno);
511 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
512 << device << " on " << mountpoint;
513 return false;
514 }
515 return true;
516}
517
518bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700519 for (int num_retries = 0; ; ++num_retries) {
520 if (umount(mountpoint.c_str()) == 0)
521 break;
522
523 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
524 num_retries < kUnmountMaxNumOfRetries);
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800525 g_usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700526 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000527 return true;
528}
529
Darin Petkovd3f8c892010-10-12 21:38:45 -0700530bool GetFilesystemSize(const std::string& device,
531 int* out_block_count,
532 int* out_block_size) {
533 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
534 TEST_AND_RETURN_FALSE(fd >= 0);
535 ScopedFdCloser fd_closer(&fd);
536 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
537}
538
539bool GetFilesystemSizeFromFD(int fd,
540 int* out_block_count,
541 int* out_block_size) {
542 TEST_AND_RETURN_FALSE(fd >= 0);
543
544 // Determine the ext3 filesystem size by directly reading the block count and
545 // block size information from the superblock. See include/linux/ext3_fs.h for
546 // more details on the structure.
547 ssize_t kBufferSize = 16 * sizeof(uint32_t);
548 char buffer[kBufferSize];
549 const int kSuperblockOffset = 1024;
550 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
551 kBufferSize) {
552 PLOG(ERROR) << "Unable to determine file system size:";
553 return false;
554 }
555 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
556 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
557 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
558 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
559 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
560 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
561 block_count = le32toh(block_count);
562 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
563 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
564 magic = le16toh(magic);
565
566 // Sanity check the parameters.
567 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
568 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
569 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
570 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
571 int block_size = 1 << log_block_size;
572 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
573 block_size <= kExt3MaxBlockSize);
574 TEST_AND_RETURN_FALSE(block_count > 0);
575
576 if (out_block_count) {
577 *out_block_count = block_count;
578 }
579 if (out_block_size) {
580 *out_block_size = block_size;
581 }
582 return true;
583}
584
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700585bool GetBootloader(BootLoader* out_bootloader) {
586 // For now, hardcode to syslinux.
587 *out_bootloader = BootLoader_SYSLINUX;
588 return true;
589}
590
Darin Petkova0b9e772011-10-06 05:05:56 -0700591string GetAndFreeGError(GError** error) {
592 if (!*error) {
593 return "Unknown GLib error.";
594 }
595 string message =
596 base::StringPrintf("GError(%d): %s",
597 (*error)->code,
598 (*error)->message ? (*error)->message : "(unknown)");
599 g_error_free(*error);
600 *error = NULL;
601 return message;
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700602}
603
Darin Petkov296889c2010-07-23 16:20:54 -0700604bool Reboot() {
605 vector<string> command;
606 command.push_back("/sbin/shutdown");
607 command.push_back("-r");
608 command.push_back("now");
609 int rc = 0;
Darin Petkov85d02b72011-05-17 13:25:51 -0700610 Subprocess::SynchronousExec(command, &rc, NULL);
Darin Petkov296889c2010-07-23 16:20:54 -0700611 TEST_AND_RETURN_FALSE(rc == 0);
612 return true;
613}
614
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800615namespace {
616// Do the actual trigger. We do it as a main-loop callback to (try to) get a
617// consistent stack trace.
618gboolean TriggerCrashReporterUpload(void* unused) {
619 pid_t pid = fork();
620 CHECK(pid >= 0) << "fork failed"; // fork() failed. Something is very wrong.
621 if (pid == 0) {
622 // We are the child. Crash.
623 abort(); // never returns
624 }
625 // We are the parent. Wait for child to terminate.
626 pid_t result = waitpid(pid, NULL, 0);
627 LOG_IF(ERROR, result < 0) << "waitpid() failed";
628 return FALSE; // Don't call this callback again
629}
630} // namespace {}
631
632void ScheduleCrashReporterUpload() {
633 g_idle_add(&TriggerCrashReporterUpload, NULL);
634}
635
Chris Sosa4f8ee272012-11-30 13:01:54 -0800636bool SetCpuShares(CpuShares shares) {
637 string string_shares = base::IntToString(static_cast<int>(shares));
638 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
639 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
640 if(utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
641 string_shares.size())){
642 return true;
643 } else {
644 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
645 << " using " << cpu_shares_file;
646 return false;
647 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700648}
649
Chris Sosa4f8ee272012-11-30 13:01:54 -0800650int CompareCpuShares(CpuShares shares_lhs,
651 CpuShares shares_rhs) {
652 return static_cast<int>(shares_lhs) - static_cast<int>(shares_rhs);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700653}
654
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700655int FuzzInt(int value, unsigned int range) {
656 int min = value - range / 2;
657 int max = value + range - range / 2;
658 return base::RandInt(min, max);
659}
660
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800661gboolean GlibRunClosure(gpointer data) {
662 google::protobuf::Closure* callback =
663 reinterpret_cast<google::protobuf::Closure*>(data);
664 callback->Run();
665 return FALSE;
666}
667
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700668string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800669 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700670}
671
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800672string FormatTimeDelta(TimeDelta delta) {
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700673 // Canonicalize into days, hours, minutes, seconds and microseconds.
674 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800675 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700676 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800677 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700678 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800679 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700680 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800681 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700682 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800683
684 // Construct and return string.
685 string str;
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700686 if (days)
687 base::StringAppendF(&str, "%ud", days);
688 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800689 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700690 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800691 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700692 base::StringAppendF(&str, "%u", secs);
693 if (usecs) {
694 int width = 6;
695 while ((usecs / 10) * 10 == usecs) {
696 usecs /= 10;
697 width--;
698 }
699 base::StringAppendF(&str, ".%0*u", width, usecs);
700 }
701 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800702 return str;
703}
704
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700705string ToString(const Time utc_time) {
706 Time::Exploded exp_time;
707 utc_time.UTCExplode(&exp_time);
708 return StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
709 exp_time.month,
710 exp_time.day_of_month,
711 exp_time.year,
712 exp_time.hour,
713 exp_time.minute,
714 exp_time.second);
715}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000716
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700717string ToString(bool b) {
718 return (b ? "true" : "false");
719}
720
Jay Srinivasan19409b72013-04-12 19:23:36 -0700721std::string ToString(DownloadSource source) {
722 switch (source) {
723 case kDownloadSourceHttpsServer: return "HttpsServer";
724 case kDownloadSourceHttpServer: return "HttpServer";
725 case kNumDownloadSources: return "Unknown";
726 // Don't add a default case to let the compiler warn about newly added
727 // download sources which should be added here.
728 }
729
730 return "Unknown";
731}
732
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800733ActionExitCode GetBaseErrorCode(ActionExitCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700734 // Ignore the higher order bits in the code by applying the mask as
735 // we want the enumerations to be in the small contiguous range
Jay Srinivasanedce2832012-10-24 18:57:47 -0700736 // with values less than kActionCodeUmaReportedMax.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800737 ActionExitCode base_code = static_cast<ActionExitCode>(code & ~kSpecialFlags);
Jay Srinivasanf0572052012-10-23 18:12:56 -0700738
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800739 // Make additional adjustments required for UMA and error classification.
740 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
741 // chromium-os:34369.
742 if (base_code >= kActionCodeOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700743 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800744 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800745 LOG(INFO) << "Converting error code " << base_code
746 << " to kActionCodeOmahaErrorInHTTPResponse";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800747 base_code = kActionCodeOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700748 }
749
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800750 return base_code;
751}
752
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800753// Returns a printable version of the various flags denoted in the higher order
754// bits of the given code. Returns an empty string if none of those bits are
755// set.
756string GetFlagNames(uint32_t code) {
757 uint32_t flags = code & kSpecialFlags;
758 string flag_names;
759 string separator = "";
760 for(size_t i = 0; i < sizeof(flags) * 8; i++) {
761 uint32_t flag = flags & (1 << i);
762 if (flag) {
763 flag_names += separator + CodeToString(static_cast<ActionExitCode>(flag));
764 separator = ", ";
765 }
766 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800767
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800768 return flag_names;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700769}
770
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800771void SendErrorCodeToUma(SystemState* system_state, ActionExitCode code) {
772 if (!system_state)
773 return;
774
775 ActionExitCode uma_error_code = GetBaseErrorCode(code);
776
777 // If the code doesn't have flags computed already, compute them now based on
778 // the state of the current update attempt.
779 uint32_t flags = code & kSpecialFlags;
780 if (!flags)
781 flags = system_state->update_attempter()->GetErrorCodeFlags();
782
783 // Determine the UMA bucket depending on the flags. But, ignore the resumed
784 // flag, as it's perfectly normal for production devices to resume their
785 // downloads and so we want to record those cases also in NormalErrorCodes
786 // bucket.
787 string metric = (flags & ~kActionCodeResumedFlag) ?
788 "Installer.DevModeErrorCodes" : "Installer.NormalErrorCodes";
789
790 LOG(INFO) << "Sending error code " << uma_error_code
791 << " (" << CodeToString(uma_error_code) << ")"
792 << " to UMA metric: " << metric
793 << ". Flags = " << (flags ? GetFlagNames(flags) : "None");
794
795 system_state->metrics_lib()->SendEnumToUMA(metric,
796 uma_error_code,
797 kActionCodeUmaReportedMax);
798}
799
800string CodeToString(ActionExitCode code) {
801 // If the given code has both parts (i.e. the error code part and the flags
802 // part) then strip off the flags part since the switch statement below
803 // has case statements only for the base error code or a single flag but
804 // doesn't support any combinations of those.
805 if ((code & kSpecialFlags) && (code & ~kSpecialFlags))
806 code = static_cast<ActionExitCode>(code & ~kSpecialFlags);
807 switch (code) {
808 case kActionCodeSuccess: return "kActionCodeSuccess";
809 case kActionCodeError: return "kActionCodeError";
810 case kActionCodeOmahaRequestError: return "kActionCodeOmahaRequestError";
811 case kActionCodeOmahaResponseHandlerError:
812 return "kActionCodeOmahaResponseHandlerError";
813 case kActionCodeFilesystemCopierError:
814 return "kActionCodeFilesystemCopierError";
815 case kActionCodePostinstallRunnerError:
816 return "kActionCodePostinstallRunnerError";
817 case kActionCodeSetBootableFlagError:
818 return "kActionCodeSetBootableFlagError";
819 case kActionCodeInstallDeviceOpenError:
820 return "kActionCodeInstallDeviceOpenError";
821 case kActionCodeKernelDeviceOpenError:
822 return "kActionCodeKernelDeviceOpenError";
823 case kActionCodeDownloadTransferError:
824 return "kActionCodeDownloadTransferError";
825 case kActionCodePayloadHashMismatchError:
826 return "kActionCodePayloadHashMismatchError";
827 case kActionCodePayloadSizeMismatchError:
828 return "kActionCodePayloadSizeMismatchError";
829 case kActionCodeDownloadPayloadVerificationError:
830 return "kActionCodeDownloadPayloadVerificationError";
831 case kActionCodeDownloadNewPartitionInfoError:
832 return "kActionCodeDownloadNewPartitionInfoError";
833 case kActionCodeDownloadWriteError:
834 return "kActionCodeDownloadWriteError";
835 case kActionCodeNewRootfsVerificationError:
836 return "kActionCodeNewRootfsVerificationError";
837 case kActionCodeNewKernelVerificationError:
838 return "kActionCodeNewKernelVerificationError";
839 case kActionCodeSignedDeltaPayloadExpectedError:
840 return "kActionCodeSignedDeltaPayloadExpectedError";
841 case kActionCodeDownloadPayloadPubKeyVerificationError:
842 return "kActionCodeDownloadPayloadPubKeyVerificationError";
843 case kActionCodePostinstallBootedFromFirmwareB:
844 return "kActionCodePostinstallBootedFromFirmwareB";
845 case kActionCodeDownloadStateInitializationError:
846 return "kActionCodeDownloadStateInitializationError";
847 case kActionCodeDownloadInvalidMetadataMagicString:
848 return "kActionCodeDownloadInvalidMetadataMagicString";
849 case kActionCodeDownloadSignatureMissingInManifest:
850 return "kActionCodeDownloadSignatureMissingInManifest";
851 case kActionCodeDownloadManifestParseError:
852 return "kActionCodeDownloadManifestParseError";
853 case kActionCodeDownloadMetadataSignatureError:
854 return "kActionCodeDownloadMetadataSignatureError";
855 case kActionCodeDownloadMetadataSignatureVerificationError:
856 return "kActionCodeDownloadMetadataSignatureVerificationError";
857 case kActionCodeDownloadMetadataSignatureMismatch:
858 return "kActionCodeDownloadMetadataSignatureMismatch";
859 case kActionCodeDownloadOperationHashVerificationError:
860 return "kActionCodeDownloadOperationHashVerificationError";
861 case kActionCodeDownloadOperationExecutionError:
862 return "kActionCodeDownloadOperationExecutionError";
863 case kActionCodeDownloadOperationHashMismatch:
864 return "kActionCodeDownloadOperationHashMismatch";
865 case kActionCodeOmahaRequestEmptyResponseError:
866 return "kActionCodeOmahaRequestEmptyResponseError";
867 case kActionCodeOmahaRequestXMLParseError:
868 return "kActionCodeOmahaRequestXMLParseError";
869 case kActionCodeDownloadInvalidMetadataSize:
870 return "kActionCodeDownloadInvalidMetadataSize";
871 case kActionCodeDownloadInvalidMetadataSignature:
872 return "kActionCodeDownloadInvalidMetadataSignature";
873 case kActionCodeOmahaResponseInvalid:
874 return "kActionCodeOmahaResponseInvalid";
875 case kActionCodeOmahaUpdateIgnoredPerPolicy:
876 return "kActionCodeOmahaUpdateIgnoredPerPolicy";
877 case kActionCodeOmahaUpdateDeferredPerPolicy:
878 return "kActionCodeOmahaUpdateDeferredPerPolicy";
879 case kActionCodeOmahaErrorInHTTPResponse:
880 return "kActionCodeOmahaErrorInHTTPResponse";
881 case kActionCodeDownloadOperationHashMissingError:
882 return "kActionCodeDownloadOperationHashMissingError";
883 case kActionCodeDownloadMetadataSignatureMissingError:
884 return "kActionCodeDownloadMetadataSignatureMissingError";
885 case kActionCodeOmahaUpdateDeferredForBackoff:
886 return "kActionCodeOmahaUpdateDeferredForBackoff";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700887 case kActionCodePostinstallPowerwashError:
888 return "kActionCodePostinstallPowerwashError";
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700889 case kActionCodeUpdateCanceledByChannelChange:
890 return "kActionCodeUpdateCanceledByChannelChange";
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800891 case kActionCodeUmaReportedMax:
892 return "kActionCodeUmaReportedMax";
893 case kActionCodeOmahaRequestHTTPResponseBase:
894 return "kActionCodeOmahaRequestHTTPResponseBase";
895 case kActionCodeResumedFlag:
896 return "Resumed";
897 case kActionCodeDevModeFlag:
898 return "DevMode";
899 case kActionCodeTestImageFlag:
900 return "TestImage";
901 case kActionCodeTestOmahaUrlFlag:
902 return "TestOmahaUrl";
903 case kSpecialFlags:
904 return "kSpecialFlags";
905 // Don't add a default case to let the compiler warn about newly added
906 // error codes which should be added here.
907 }
908
909 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
910}
Jay Srinivasanf0572052012-10-23 18:12:56 -0700911
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700912bool CreatePowerwashMarkerFile() {
913 bool result = utils::WriteFile(kPowerwashMarkerFile,
914 kPowerwashCommand,
915 strlen(kPowerwashCommand));
916 if (result)
917 LOG(INFO) << "Created " << kPowerwashMarkerFile
918 << " to powerwash on next reboot";
919 else
920 PLOG(ERROR) << "Error in creating powerwash marker file: "
921 << kPowerwashMarkerFile;
922
923 return result;
924}
925
926bool DeletePowerwashMarkerFile() {
927 const FilePath kPowerwashMarkerPath(kPowerwashMarkerFile);
928 bool result = file_util::Delete(kPowerwashMarkerPath, false);
929
930 if (result)
931 LOG(INFO) << "Successfully deleted the powerwash marker file : "
932 << kPowerwashMarkerFile;
933 else
934 PLOG(ERROR) << "Could not delete the powerwash marker file : "
935 << kPowerwashMarkerFile;
936
937 return result;
938}
939
David Zeuthen9a017f22013-04-11 16:10:26 -0700940
941Time GetMonotonicTime() {
942 struct timespec now_ts;
943 if (clock_gettime(CLOCK_MONOTONIC_RAW, &now_ts) != 0) {
944 // Avoid logging this as an error as call-sites may call this very
945 // often and we don't want to fill up the disk...
946 return Time();
947 }
948 struct timeval now_tv;
949 now_tv.tv_sec = now_ts.tv_sec;
950 now_tv.tv_usec = now_ts.tv_nsec/Time::kNanosecondsPerMicrosecond;
951 return Time::FromTimeVal(now_tv);
952}
953
adlr@google.com3defe6a2009-12-04 20:57:17 +0000954} // namespace utils
955
956} // namespace chromeos_update_engine