blob: 1165db5554a46bef565e1b5657be5dc374733d24 [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>
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -080030#include <google/protobuf/stubs/common.h>
Will Drewry8f71da82010-08-30 14:07:11 -050031#include <rootdev/rootdev.h>
32
Andrew de los Reyes970bb282009-12-09 16:34:04 -080033#include "update_engine/file_writer.h"
Jay Srinivasanf0572052012-10-23 18:12:56 -070034#include "update_engine/install_plan.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"
adlr@google.com3defe6a2009-12-04 20:57:17 +000037
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070038using base::Time;
adlr@google.com3defe6a2009-12-04 20:57:17 +000039using std::min;
40using std::string;
41using std::vector;
42
43namespace chromeos_update_engine {
44
Ben Chan77a1eba2012-10-07 22:54:55 -070045namespace {
46
47// The following constants control how UnmountFilesystem should retry if
48// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
49// one second.
50const int kUnmountMaxNumOfRetries = 5;
51const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
52
53} // namespace
54
adlr@google.com3defe6a2009-12-04 20:57:17 +000055namespace utils {
56
Darin Petkova07586b2010-10-20 13:41:15 -070057static const char kDevImageMarker[] = "/root/.dev_mode";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070058const char* const kStatefulPartition = "/mnt/stateful_partition";
Darin Petkov2a0e6332010-09-24 14:43:41 -070059
Darin Petkov33d30642010-08-04 10:18:57 -070060bool IsOfficialBuild() {
Darin Petkova07586b2010-10-20 13:41:15 -070061 return !file_util::PathExists(FilePath(kDevImageMarker));
Darin Petkov33d30642010-08-04 10:18:57 -070062}
63
Darin Petkovc91dd6b2011-01-10 12:31:34 -080064bool IsNormalBootMode() {
Darin Petkov44d98d92011-03-21 16:08:11 -070065 // TODO(petkov): Convert to a library call once a crossystem library is
66 // available (crosbug.com/13291).
67 int exit_code = 0;
68 vector<string> cmd(1, "/usr/bin/crossystem");
69 cmd.push_back("devsw_boot?1");
70
71 // Assume dev mode if the dev switch is set to 1 and there was no error
72 // executing crossystem. Assume normal mode otherwise.
Darin Petkov85d02b72011-05-17 13:25:51 -070073 bool success = Subprocess::SynchronousExec(cmd, &exit_code, NULL);
Darin Petkov44d98d92011-03-21 16:08:11 -070074 bool dev_mode = success && exit_code == 0;
75 LOG_IF(INFO, dev_mode) << "Booted in dev mode.";
76 return !dev_mode;
Darin Petkovc91dd6b2011-01-10 12:31:34 -080077}
78
Darin Petkovf2065b42011-05-17 16:36:27 -070079string GetHardwareClass() {
80 // TODO(petkov): Convert to a library call once a crossystem library is
81 // available (crosbug.com/13291).
82 int exit_code = 0;
83 vector<string> cmd(1, "/usr/bin/crossystem");
84 cmd.push_back("hwid");
85
86 string hwid;
87 bool success = Subprocess::SynchronousExec(cmd, &exit_code, &hwid);
88 if (success && !exit_code) {
89 TrimWhitespaceASCII(hwid, TRIM_ALL, &hwid);
90 return hwid;
91 }
92 LOG(ERROR) << "Unable to read HWID (" << exit_code << ") " << hwid;
93 return "";
94}
95
Andrew de los Reyes970bb282009-12-09 16:34:04 -080096bool WriteFile(const char* path, const char* data, int data_len) {
97 DirectFileWriter writer;
98 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
99 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700100 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800101 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800102 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800103 return true;
104}
105
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700106bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700107 const char* c_buf = static_cast<const char*>(buf);
108 ssize_t bytes_written = 0;
109 while (bytes_written < static_cast<ssize_t>(count)) {
110 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
111 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
112 bytes_written += rc;
113 }
114 return true;
115}
116
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700117bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
118 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700119 size_t bytes_written = 0;
120 int num_attempts = 0;
121 while (bytes_written < count) {
122 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700123 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
124 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700125 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
126 if (rc < 0) {
127 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
128 << " bytes_written=" << bytes_written
129 << " count=" << count << " offset=" << offset;
130 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700131 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
132 bytes_written += rc;
133 }
134 return true;
135}
136
137bool PReadAll(int fd, void* buf, size_t count, off_t offset,
138 ssize_t* out_bytes_read) {
139 char* c_buf = static_cast<char*>(buf);
140 ssize_t bytes_read = 0;
141 while (bytes_read < static_cast<ssize_t>(count)) {
142 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
143 offset + bytes_read);
144 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
145 if (rc == 0) {
146 break;
147 }
148 bytes_read += rc;
149 }
150 *out_bytes_read = bytes_read;
151 return true;
Darin Petkov296889c2010-07-23 16:20:54 -0700152
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700153}
154
Gilad Arnold19a45f02012-07-19 12:36:10 -0700155// Append |nbytes| of content from |buf| to the vector pointed to by either
156// |vec_p| or |str_p|.
157static void AppendBytes(const char* buf, size_t nbytes,
158 std::vector<char>* vec_p) {
159 CHECK(buf);
160 CHECK(vec_p);
161 vec_p->insert(vec_p->end(), buf, buf + nbytes);
162}
163static void AppendBytes(const char* buf, size_t nbytes,
164 std::string* str_p) {
165 CHECK(buf);
166 CHECK(str_p);
167 str_p->append(buf, nbytes);
168}
169
170// Reads from an open file |fp|, appending the read content to the container
171// pointer to by |out_p|. Returns true upon successful reading all of the
172// file's content, false otherwise.
173template <class T>
174static bool Read(FILE* fp, T* out_p) {
175 CHECK(fp);
176 char buf[1024];
177 while (size_t nbytes = fread(buf, 1, sizeof(buf), fp))
178 AppendBytes(buf, nbytes, out_p);
179 return feof(fp) && !ferror(fp);
180}
181
182// Opens a file |path| for reading, then uses |append_func| to append its
183// content to a container |out_p|.
184template <class T>
185static bool ReadFileAndAppend(const std::string& path, T* out_p) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000186 FILE* fp = fopen(path.c_str(), "r");
187 if (!fp)
188 return false;
Gilad Arnold19a45f02012-07-19 12:36:10 -0700189 bool success = Read(fp, out_p);
190 return (success && !fclose(fp));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000191}
192
Gilad Arnold19a45f02012-07-19 12:36:10 -0700193// Invokes a pipe |cmd|, then uses |append_func| to append its stdout to a
194// container |out_p|.
195template <class T>
196static bool ReadPipeAndAppend(const std::string& cmd, T* out_p) {
197 FILE* fp = popen(cmd.c_str(), "r");
198 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000199 return false;
Gilad Arnold19a45f02012-07-19 12:36:10 -0700200 bool success = Read(fp, out_p);
201 return (success && pclose(fp) >= 0);
202}
203
204
205bool ReadFile(const std::string& path, std::vector<char>* out_p) {
206 return ReadFileAndAppend(path, out_p);
207}
208
209bool ReadFile(const std::string& path, std::string* out_p) {
210 return ReadFileAndAppend(path, out_p);
211}
212
213bool ReadPipe(const std::string& cmd, std::vector<char>* out_p) {
214 return ReadPipeAndAppend(cmd, out_p);
215}
216
217bool ReadPipe(const std::string& cmd, std::string* out_p) {
218 return ReadPipeAndAppend(cmd, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000219}
220
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700221off_t FileSize(const string& path) {
222 struct stat stbuf;
223 int rc = stat(path.c_str(), &stbuf);
224 CHECK_EQ(rc, 0);
225 if (rc < 0)
226 return rc;
227 return stbuf.st_size;
228}
229
adlr@google.com3defe6a2009-12-04 20:57:17 +0000230void HexDumpArray(const unsigned char* const arr, const size_t length) {
231 const unsigned char* const char_arr =
232 reinterpret_cast<const unsigned char* const>(arr);
233 LOG(INFO) << "Logging array of length: " << length;
234 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700235 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000236 const unsigned int bytes_remaining = length - i;
237 const unsigned int bytes_per_this_line = min(bytes_per_line,
238 bytes_remaining);
239 char header[100];
240 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
241 TEST_AND_RETURN(r == 13);
242 string line = header;
243 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
244 char buf[20];
245 unsigned char c = char_arr[i + j];
246 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
247 TEST_AND_RETURN(r == 3);
248 line += buf;
249 }
250 LOG(INFO) << line;
251 }
252}
253
254namespace {
255class ScopedDirCloser {
256 public:
257 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
258 ~ScopedDirCloser() {
259 if (dir_ && *dir_) {
260 int r = closedir(*dir_);
261 TEST_AND_RETURN_ERRNO(r == 0);
262 *dir_ = NULL;
263 dir_ = NULL;
264 }
265 }
266 private:
267 DIR** dir_;
268};
269} // namespace {}
270
271bool RecursiveUnlinkDir(const std::string& path) {
272 struct stat stbuf;
273 int r = lstat(path.c_str(), &stbuf);
274 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
275 if ((r < 0) && (errno == ENOENT))
276 // path request is missing. that's fine.
277 return true;
278 if (!S_ISDIR(stbuf.st_mode)) {
279 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700280 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000281 // success or path disappeared before we could unlink.
282 return true;
283 }
284 {
285 // We have a dir, unlink all children, then delete dir
286 DIR *dir = opendir(path.c_str());
287 TEST_AND_RETURN_FALSE_ERRNO(dir);
288 ScopedDirCloser dir_closer(&dir);
289 struct dirent dir_entry;
290 struct dirent *dir_entry_p;
291 int err = 0;
292 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
293 if (dir_entry_p == NULL) {
294 // end of stream reached
295 break;
296 }
297 // Skip . and ..
298 if (!strcmp(dir_entry_p->d_name, ".") ||
299 !strcmp(dir_entry_p->d_name, ".."))
300 continue;
301 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700302 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000303 }
304 TEST_AND_RETURN_FALSE(err == 0);
305 }
306 // unlink dir
307 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
308 return true;
309}
310
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700311string RootDevice(const string& partition_device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700312 FilePath device_path(partition_device);
313 if (device_path.DirName().value() != "/dev") {
314 return "";
315 }
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700316 string::const_iterator it = --partition_device.end();
317 for (; it >= partition_device.begin(); --it) {
318 if (!isdigit(*it))
319 break;
320 }
321 // Some devices contain a p before the partitions. For example:
322 // /dev/mmc0p4 should be shortened to /dev/mmc0.
323 if (*it == 'p')
324 --it;
325 return string(partition_device.begin(), it + 1);
326}
327
328string PartitionNumber(const string& partition_device) {
329 CHECK(!partition_device.empty());
330 string::const_iterator it = --partition_device.end();
331 for (; it >= partition_device.begin(); --it) {
332 if (!isdigit(*it))
333 break;
334 }
335 return string(it + 1, partition_device.end());
336}
337
Darin Petkovf74eb652010-08-04 12:08:38 -0700338string SysfsBlockDevice(const string& device) {
339 FilePath device_path(device);
340 if (device_path.DirName().value() != "/dev") {
341 return "";
342 }
343 return FilePath("/sys/block").Append(device_path.BaseName()).value();
344}
345
346bool IsRemovableDevice(const std::string& device) {
347 string sysfs_block = SysfsBlockDevice(device);
348 string removable;
349 if (sysfs_block.empty() ||
350 !file_util::ReadFileToString(FilePath(sysfs_block).Append("removable"),
351 &removable)) {
352 return false;
353 }
354 TrimWhitespaceASCII(removable, TRIM_ALL, &removable);
355 return removable == "1";
356}
357
adlr@google.com3defe6a2009-12-04 20:57:17 +0000358std::string ErrnoNumberAsString(int err) {
359 char buf[100];
360 buf[0] = '\0';
361 return strerror_r(err, buf, sizeof(buf));
362}
363
364std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
365 string ret;
366 bool last_insert_was_slash = false;
367 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
368 if (*it == '/') {
369 if (last_insert_was_slash)
370 continue;
371 last_insert_was_slash = true;
372 } else {
373 last_insert_was_slash = false;
374 }
375 ret.push_back(*it);
376 }
377 if (strip_trailing_slash && last_insert_was_slash) {
378 string::size_type last_non_slash = ret.find_last_not_of('/');
379 if (last_non_slash != string::npos) {
380 ret.resize(last_non_slash + 1);
381 } else {
382 ret = "";
383 }
384 }
385 return ret;
386}
387
388bool FileExists(const char* path) {
389 struct stat stbuf;
390 return 0 == lstat(path, &stbuf);
391}
392
Darin Petkov30291ed2010-11-12 10:23:06 -0800393bool IsSymlink(const char* path) {
394 struct stat stbuf;
395 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
396}
397
adlr@google.com3defe6a2009-12-04 20:57:17 +0000398std::string TempFilename(string path) {
399 static const string suffix("XXXXXX");
400 CHECK(StringHasSuffix(path, suffix));
401 do {
402 string new_suffix;
403 for (unsigned int i = 0; i < suffix.size(); i++) {
404 int r = rand() % (26 * 2 + 10); // [a-zA-Z0-9]
405 if (r < 26)
406 new_suffix.append(1, 'a' + r);
407 else if (r < (26 * 2))
408 new_suffix.append(1, 'A' + r - 26);
409 else
410 new_suffix.append(1, '0' + r - (26 * 2));
411 }
412 CHECK_EQ(new_suffix.size(), suffix.size());
413 path.resize(path.size() - new_suffix.size());
414 path.append(new_suffix);
415 } while (FileExists(path.c_str()));
416 return path;
417}
418
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700419bool MakeTempFile(const std::string& filename_template,
420 std::string* filename,
421 int* fd) {
422 DCHECK(filename || fd);
423 vector<char> buf(filename_template.size() + 1);
424 memcpy(&buf[0], filename_template.data(), filename_template.size());
425 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700426
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700427 int mkstemp_fd = mkstemp(&buf[0]);
428 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
429 if (filename) {
430 *filename = &buf[0];
431 }
432 if (fd) {
433 *fd = mkstemp_fd;
434 } else {
435 close(mkstemp_fd);
436 }
437 return true;
438}
439
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700440bool MakeTempDirectory(const std::string& dirname_template,
441 std::string* dirname) {
442 DCHECK(dirname);
443 vector<char> buf(dirname_template.size() + 1);
444 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
445 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700446
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700447 char* return_code = mkdtemp(&buf[0]);
448 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
449 *dirname = &buf[0];
450 return true;
451}
452
adlr@google.com3defe6a2009-12-04 20:57:17 +0000453bool StringHasSuffix(const std::string& str, const std::string& suffix) {
454 if (suffix.size() > str.size())
455 return false;
456 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
457}
458
459bool StringHasPrefix(const std::string& str, const std::string& prefix) {
460 if (prefix.size() > str.size())
461 return false;
462 return 0 == str.compare(0, prefix.size(), prefix);
463}
464
Will Drewry8f71da82010-08-30 14:07:11 -0500465const std::string BootDevice() {
466 char boot_path[PATH_MAX];
467 // Resolve the boot device path fully, including dereferencing
468 // through dm-verity.
469 int ret = rootdev(boot_path, sizeof(boot_path), true, false);
470
471 if (ret < 0) {
472 LOG(ERROR) << "rootdev failed to find the root device";
adlr@google.com3defe6a2009-12-04 20:57:17 +0000473 return "";
474 }
Will Drewry8f71da82010-08-30 14:07:11 -0500475 LOG_IF(WARNING, ret > 0) << "rootdev found a device name with no device node";
476
477 // This local variable is used to construct the return string and is not
478 // passed around after use.
479 return boot_path;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000480}
481
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700482const string BootKernelDevice(const std::string& boot_device) {
483 // Currntly this assumes the last digit of the boot device is
484 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
485 // get the kernel device.
486 string ret = boot_device;
487 if (ret.empty())
488 return ret;
489 char last_char = ret[ret.size() - 1];
490 if (last_char == '3' || last_char == '5' || last_char == '7') {
491 ret[ret.size() - 1] = last_char - 1;
492 return ret;
493 }
494 return "";
495}
496
adlr@google.com3defe6a2009-12-04 20:57:17 +0000497bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700498 const string& mountpoint,
499 unsigned long mountflags) {
500 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000501 if (rc < 0) {
502 string msg = ErrnoNumberAsString(errno);
503 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
504 << device << " on " << mountpoint;
505 return false;
506 }
507 return true;
508}
509
510bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700511 for (int num_retries = 0; ; ++num_retries) {
512 if (umount(mountpoint.c_str()) == 0)
513 break;
514
515 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
516 num_retries < kUnmountMaxNumOfRetries);
517 usleep(kUnmountRetryIntervalInMicroseconds);
518 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000519 return true;
520}
521
Darin Petkovd3f8c892010-10-12 21:38:45 -0700522bool GetFilesystemSize(const std::string& device,
523 int* out_block_count,
524 int* out_block_size) {
525 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
526 TEST_AND_RETURN_FALSE(fd >= 0);
527 ScopedFdCloser fd_closer(&fd);
528 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
529}
530
531bool GetFilesystemSizeFromFD(int fd,
532 int* out_block_count,
533 int* out_block_size) {
534 TEST_AND_RETURN_FALSE(fd >= 0);
535
536 // Determine the ext3 filesystem size by directly reading the block count and
537 // block size information from the superblock. See include/linux/ext3_fs.h for
538 // more details on the structure.
539 ssize_t kBufferSize = 16 * sizeof(uint32_t);
540 char buffer[kBufferSize];
541 const int kSuperblockOffset = 1024;
542 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
543 kBufferSize) {
544 PLOG(ERROR) << "Unable to determine file system size:";
545 return false;
546 }
547 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
548 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
549 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
550 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
551 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
552 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
553 block_count = le32toh(block_count);
554 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
555 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
556 magic = le16toh(magic);
557
558 // Sanity check the parameters.
559 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
560 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
561 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
562 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
563 int block_size = 1 << log_block_size;
564 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
565 block_size <= kExt3MaxBlockSize);
566 TEST_AND_RETURN_FALSE(block_count > 0);
567
568 if (out_block_count) {
569 *out_block_count = block_count;
570 }
571 if (out_block_size) {
572 *out_block_size = block_size;
573 }
574 return true;
575}
576
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700577bool GetBootloader(BootLoader* out_bootloader) {
578 // For now, hardcode to syslinux.
579 *out_bootloader = BootLoader_SYSLINUX;
580 return true;
581}
582
Darin Petkova0b9e772011-10-06 05:05:56 -0700583string GetAndFreeGError(GError** error) {
584 if (!*error) {
585 return "Unknown GLib error.";
586 }
587 string message =
588 base::StringPrintf("GError(%d): %s",
589 (*error)->code,
590 (*error)->message ? (*error)->message : "(unknown)");
591 g_error_free(*error);
592 *error = NULL;
593 return message;
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700594}
595
Darin Petkov296889c2010-07-23 16:20:54 -0700596bool Reboot() {
597 vector<string> command;
598 command.push_back("/sbin/shutdown");
599 command.push_back("-r");
600 command.push_back("now");
601 int rc = 0;
Darin Petkov85d02b72011-05-17 13:25:51 -0700602 Subprocess::SynchronousExec(command, &rc, NULL);
Darin Petkov296889c2010-07-23 16:20:54 -0700603 TEST_AND_RETURN_FALSE(rc == 0);
604 return true;
605}
606
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800607namespace {
608// Do the actual trigger. We do it as a main-loop callback to (try to) get a
609// consistent stack trace.
610gboolean TriggerCrashReporterUpload(void* unused) {
611 pid_t pid = fork();
612 CHECK(pid >= 0) << "fork failed"; // fork() failed. Something is very wrong.
613 if (pid == 0) {
614 // We are the child. Crash.
615 abort(); // never returns
616 }
617 // We are the parent. Wait for child to terminate.
618 pid_t result = waitpid(pid, NULL, 0);
619 LOG_IF(ERROR, result < 0) << "waitpid() failed";
620 return FALSE; // Don't call this callback again
621}
622} // namespace {}
623
624void ScheduleCrashReporterUpload() {
625 g_idle_add(&TriggerCrashReporterUpload, NULL);
626}
627
Darin Petkovc6c135c2010-08-11 13:36:18 -0700628bool SetProcessPriority(ProcessPriority priority) {
629 int prio = static_cast<int>(priority);
630 LOG(INFO) << "Setting process priority to " << prio;
631 TEST_AND_RETURN_FALSE(setpriority(PRIO_PROCESS, 0, prio) == 0);
632 return true;
633}
634
635int ComparePriorities(ProcessPriority priority_lhs,
636 ProcessPriority priority_rhs) {
637 return static_cast<int>(priority_rhs) - static_cast<int>(priority_lhs);
638}
639
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700640int FuzzInt(int value, unsigned int range) {
641 int min = value - range / 2;
642 int max = value + range - range / 2;
643 return base::RandInt(min, max);
644}
645
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800646gboolean GlibRunClosure(gpointer data) {
647 google::protobuf::Closure* callback =
648 reinterpret_cast<google::protobuf::Closure*>(data);
649 callback->Run();
650 return FALSE;
651}
652
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700653string FormatSecs(unsigned secs) {
654 return FormatTimeDelta(base::TimeDelta::FromSeconds(secs));
655}
656
657string FormatTimeDelta(base::TimeDelta delta) {
658 // Canonicalize into days, hours, minutes, seconds and microseconds.
659 unsigned days = delta.InDays();
660 delta -= base::TimeDelta::FromDays(days);
661 unsigned hours = delta.InHours();
662 delta -= base::TimeDelta::FromHours(hours);
663 unsigned mins = delta.InMinutes();
664 delta -= base::TimeDelta::FromMinutes(mins);
665 unsigned secs = delta.InSeconds();
666 delta -= base::TimeDelta::FromSeconds(secs);
667 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800668
669 // Construct and return string.
670 string str;
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700671 if (days)
672 base::StringAppendF(&str, "%ud", days);
673 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800674 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700675 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800676 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700677 base::StringAppendF(&str, "%u", secs);
678 if (usecs) {
679 int width = 6;
680 while ((usecs / 10) * 10 == usecs) {
681 usecs /= 10;
682 width--;
683 }
684 base::StringAppendF(&str, ".%0*u", width, usecs);
685 }
686 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800687 return str;
688}
689
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700690string ToString(const Time utc_time) {
691 Time::Exploded exp_time;
692 utc_time.UTCExplode(&exp_time);
693 return StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
694 exp_time.month,
695 exp_time.day_of_month,
696 exp_time.year,
697 exp_time.hour,
698 exp_time.minute,
699 exp_time.second);
700}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000701
Jay Srinivasanf0572052012-10-23 18:12:56 -0700702void SendErrorCodeToUMA(MetricsLibraryInterface* metrics_lib,
703 ActionExitCode code)
704{
705 string metric = utils::IsNormalBootMode() ? "UpdateEngine.NormalErrorCodes" :
706 "UpdateEngine.DevModeErrorCodes";
707
708 // Ignore the higher order bits in the code by applying the mask as
709 // we want the enumerations to be in the small contiguous range
710 // with values less than kNumBucketsForUMAMetrics.
711 int actual_code = code & kActualCodeMask;
712
713 // Make additional adjustments required for UMA.
714 if (actual_code >= kActionCodeOmahaRequestHTTPResponseBase) {
715 // Since we want to keep the enums to a small value, aggregate all HTTP
716 // errors into this one bucket for UMA purposes.
717 actual_code = kActionCodeOmahaErrorInHTTPResponse;
718 }
719
720 LOG(INFO) << "Sending " << actual_code << " to UMA metric: " << metric;
721 metrics_lib->SendEnumToUMA(metric, actual_code, kNumBucketsForUMAMetrics);
722}
723
724
adlr@google.com3defe6a2009-12-04 20:57:17 +0000725} // namespace utils
726
727} // namespace chromeos_update_engine