blob: 1e87262c27416476d7714faf31fcd8287463a181 [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"
Darin Petkov33d30642010-08-04 10:18:57 -070034#include "update_engine/omaha_request_params.h"
Darin Petkov296889c2010-07-23 16:20:54 -070035#include "update_engine/subprocess.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000036
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070037using base::Time;
adlr@google.com3defe6a2009-12-04 20:57:17 +000038using std::min;
39using std::string;
40using std::vector;
41
42namespace chromeos_update_engine {
43
Ben Chan77a1eba2012-10-07 22:54:55 -070044namespace {
45
46// The following constants control how UnmountFilesystem should retry if
47// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
48// one second.
49const int kUnmountMaxNumOfRetries = 5;
50const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
51
52} // namespace
53
adlr@google.com3defe6a2009-12-04 20:57:17 +000054namespace utils {
55
Darin Petkova07586b2010-10-20 13:41:15 -070056static const char kDevImageMarker[] = "/root/.dev_mode";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070057const char* const kStatefulPartition = "/mnt/stateful_partition";
Darin Petkov2a0e6332010-09-24 14:43:41 -070058
Darin Petkov33d30642010-08-04 10:18:57 -070059bool IsOfficialBuild() {
Darin Petkova07586b2010-10-20 13:41:15 -070060 return !file_util::PathExists(FilePath(kDevImageMarker));
Darin Petkov33d30642010-08-04 10:18:57 -070061}
62
Darin Petkovc91dd6b2011-01-10 12:31:34 -080063bool IsNormalBootMode() {
Darin Petkov44d98d92011-03-21 16:08:11 -070064 // TODO(petkov): Convert to a library call once a crossystem library is
65 // available (crosbug.com/13291).
66 int exit_code = 0;
67 vector<string> cmd(1, "/usr/bin/crossystem");
68 cmd.push_back("devsw_boot?1");
69
70 // Assume dev mode if the dev switch is set to 1 and there was no error
71 // executing crossystem. Assume normal mode otherwise.
Darin Petkov85d02b72011-05-17 13:25:51 -070072 bool success = Subprocess::SynchronousExec(cmd, &exit_code, NULL);
Darin Petkov44d98d92011-03-21 16:08:11 -070073 bool dev_mode = success && exit_code == 0;
74 LOG_IF(INFO, dev_mode) << "Booted in dev mode.";
75 return !dev_mode;
Darin Petkovc91dd6b2011-01-10 12:31:34 -080076}
77
Darin Petkovf2065b42011-05-17 16:36:27 -070078string GetHardwareClass() {
79 // TODO(petkov): Convert to a library call once a crossystem library is
80 // available (crosbug.com/13291).
81 int exit_code = 0;
82 vector<string> cmd(1, "/usr/bin/crossystem");
83 cmd.push_back("hwid");
84
85 string hwid;
86 bool success = Subprocess::SynchronousExec(cmd, &exit_code, &hwid);
87 if (success && !exit_code) {
88 TrimWhitespaceASCII(hwid, TRIM_ALL, &hwid);
89 return hwid;
90 }
91 LOG(ERROR) << "Unable to read HWID (" << exit_code << ") " << hwid;
92 return "";
93}
94
Andrew de los Reyes970bb282009-12-09 16:34:04 -080095bool WriteFile(const char* path, const char* data, int data_len) {
96 DirectFileWriter writer;
97 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
98 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -070099 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800100 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800101 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800102 return true;
103}
104
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700105bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700106 const char* c_buf = static_cast<const char*>(buf);
107 ssize_t bytes_written = 0;
108 while (bytes_written < static_cast<ssize_t>(count)) {
109 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
110 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
111 bytes_written += rc;
112 }
113 return true;
114}
115
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700116bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
117 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700118 size_t bytes_written = 0;
119 int num_attempts = 0;
120 while (bytes_written < count) {
121 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700122 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
123 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700124 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
125 if (rc < 0) {
126 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
127 << " bytes_written=" << bytes_written
128 << " count=" << count << " offset=" << offset;
129 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700130 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
131 bytes_written += rc;
132 }
133 return true;
134}
135
136bool PReadAll(int fd, void* buf, size_t count, off_t offset,
137 ssize_t* out_bytes_read) {
138 char* c_buf = static_cast<char*>(buf);
139 ssize_t bytes_read = 0;
140 while (bytes_read < static_cast<ssize_t>(count)) {
141 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
142 offset + bytes_read);
143 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
144 if (rc == 0) {
145 break;
146 }
147 bytes_read += rc;
148 }
149 *out_bytes_read = bytes_read;
150 return true;
Darin Petkov296889c2010-07-23 16:20:54 -0700151
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700152}
153
Gilad Arnold19a45f02012-07-19 12:36:10 -0700154// Append |nbytes| of content from |buf| to the vector pointed to by either
155// |vec_p| or |str_p|.
156static void AppendBytes(const char* buf, size_t nbytes,
157 std::vector<char>* vec_p) {
158 CHECK(buf);
159 CHECK(vec_p);
160 vec_p->insert(vec_p->end(), buf, buf + nbytes);
161}
162static void AppendBytes(const char* buf, size_t nbytes,
163 std::string* str_p) {
164 CHECK(buf);
165 CHECK(str_p);
166 str_p->append(buf, nbytes);
167}
168
169// Reads from an open file |fp|, appending the read content to the container
170// pointer to by |out_p|. Returns true upon successful reading all of the
171// file's content, false otherwise.
172template <class T>
173static bool Read(FILE* fp, T* out_p) {
174 CHECK(fp);
175 char buf[1024];
176 while (size_t nbytes = fread(buf, 1, sizeof(buf), fp))
177 AppendBytes(buf, nbytes, out_p);
178 return feof(fp) && !ferror(fp);
179}
180
181// Opens a file |path| for reading, then uses |append_func| to append its
182// content to a container |out_p|.
183template <class T>
184static bool ReadFileAndAppend(const std::string& path, T* out_p) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000185 FILE* fp = fopen(path.c_str(), "r");
186 if (!fp)
187 return false;
Gilad Arnold19a45f02012-07-19 12:36:10 -0700188 bool success = Read(fp, out_p);
189 return (success && !fclose(fp));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000190}
191
Gilad Arnold19a45f02012-07-19 12:36:10 -0700192// Invokes a pipe |cmd|, then uses |append_func| to append its stdout to a
193// container |out_p|.
194template <class T>
195static bool ReadPipeAndAppend(const std::string& cmd, T* out_p) {
196 FILE* fp = popen(cmd.c_str(), "r");
197 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000198 return false;
Gilad Arnold19a45f02012-07-19 12:36:10 -0700199 bool success = Read(fp, out_p);
200 return (success && pclose(fp) >= 0);
201}
202
203
204bool ReadFile(const std::string& path, std::vector<char>* out_p) {
205 return ReadFileAndAppend(path, out_p);
206}
207
208bool ReadFile(const std::string& path, std::string* out_p) {
209 return ReadFileAndAppend(path, out_p);
210}
211
212bool ReadPipe(const std::string& cmd, std::vector<char>* out_p) {
213 return ReadPipeAndAppend(cmd, out_p);
214}
215
216bool ReadPipe(const std::string& cmd, std::string* out_p) {
217 return ReadPipeAndAppend(cmd, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000218}
219
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700220off_t FileSize(const string& path) {
221 struct stat stbuf;
222 int rc = stat(path.c_str(), &stbuf);
223 CHECK_EQ(rc, 0);
224 if (rc < 0)
225 return rc;
226 return stbuf.st_size;
227}
228
adlr@google.com3defe6a2009-12-04 20:57:17 +0000229void HexDumpArray(const unsigned char* const arr, const size_t length) {
230 const unsigned char* const char_arr =
231 reinterpret_cast<const unsigned char* const>(arr);
232 LOG(INFO) << "Logging array of length: " << length;
233 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700234 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000235 const unsigned int bytes_remaining = length - i;
236 const unsigned int bytes_per_this_line = min(bytes_per_line,
237 bytes_remaining);
238 char header[100];
239 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
240 TEST_AND_RETURN(r == 13);
241 string line = header;
242 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
243 char buf[20];
244 unsigned char c = char_arr[i + j];
245 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
246 TEST_AND_RETURN(r == 3);
247 line += buf;
248 }
249 LOG(INFO) << line;
250 }
251}
252
253namespace {
254class ScopedDirCloser {
255 public:
256 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
257 ~ScopedDirCloser() {
258 if (dir_ && *dir_) {
259 int r = closedir(*dir_);
260 TEST_AND_RETURN_ERRNO(r == 0);
261 *dir_ = NULL;
262 dir_ = NULL;
263 }
264 }
265 private:
266 DIR** dir_;
267};
268} // namespace {}
269
270bool RecursiveUnlinkDir(const std::string& path) {
271 struct stat stbuf;
272 int r = lstat(path.c_str(), &stbuf);
273 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
274 if ((r < 0) && (errno == ENOENT))
275 // path request is missing. that's fine.
276 return true;
277 if (!S_ISDIR(stbuf.st_mode)) {
278 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700279 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000280 // success or path disappeared before we could unlink.
281 return true;
282 }
283 {
284 // We have a dir, unlink all children, then delete dir
285 DIR *dir = opendir(path.c_str());
286 TEST_AND_RETURN_FALSE_ERRNO(dir);
287 ScopedDirCloser dir_closer(&dir);
288 struct dirent dir_entry;
289 struct dirent *dir_entry_p;
290 int err = 0;
291 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
292 if (dir_entry_p == NULL) {
293 // end of stream reached
294 break;
295 }
296 // Skip . and ..
297 if (!strcmp(dir_entry_p->d_name, ".") ||
298 !strcmp(dir_entry_p->d_name, ".."))
299 continue;
300 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700301 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000302 }
303 TEST_AND_RETURN_FALSE(err == 0);
304 }
305 // unlink dir
306 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
307 return true;
308}
309
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700310string RootDevice(const string& partition_device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700311 FilePath device_path(partition_device);
312 if (device_path.DirName().value() != "/dev") {
313 return "";
314 }
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700315 string::const_iterator it = --partition_device.end();
316 for (; it >= partition_device.begin(); --it) {
317 if (!isdigit(*it))
318 break;
319 }
320 // Some devices contain a p before the partitions. For example:
321 // /dev/mmc0p4 should be shortened to /dev/mmc0.
322 if (*it == 'p')
323 --it;
324 return string(partition_device.begin(), it + 1);
325}
326
327string PartitionNumber(const string& partition_device) {
328 CHECK(!partition_device.empty());
329 string::const_iterator it = --partition_device.end();
330 for (; it >= partition_device.begin(); --it) {
331 if (!isdigit(*it))
332 break;
333 }
334 return string(it + 1, partition_device.end());
335}
336
Darin Petkovf74eb652010-08-04 12:08:38 -0700337string SysfsBlockDevice(const string& device) {
338 FilePath device_path(device);
339 if (device_path.DirName().value() != "/dev") {
340 return "";
341 }
342 return FilePath("/sys/block").Append(device_path.BaseName()).value();
343}
344
345bool IsRemovableDevice(const std::string& device) {
346 string sysfs_block = SysfsBlockDevice(device);
347 string removable;
348 if (sysfs_block.empty() ||
349 !file_util::ReadFileToString(FilePath(sysfs_block).Append("removable"),
350 &removable)) {
351 return false;
352 }
353 TrimWhitespaceASCII(removable, TRIM_ALL, &removable);
354 return removable == "1";
355}
356
adlr@google.com3defe6a2009-12-04 20:57:17 +0000357std::string ErrnoNumberAsString(int err) {
358 char buf[100];
359 buf[0] = '\0';
360 return strerror_r(err, buf, sizeof(buf));
361}
362
363std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
364 string ret;
365 bool last_insert_was_slash = false;
366 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
367 if (*it == '/') {
368 if (last_insert_was_slash)
369 continue;
370 last_insert_was_slash = true;
371 } else {
372 last_insert_was_slash = false;
373 }
374 ret.push_back(*it);
375 }
376 if (strip_trailing_slash && last_insert_was_slash) {
377 string::size_type last_non_slash = ret.find_last_not_of('/');
378 if (last_non_slash != string::npos) {
379 ret.resize(last_non_slash + 1);
380 } else {
381 ret = "";
382 }
383 }
384 return ret;
385}
386
387bool FileExists(const char* path) {
388 struct stat stbuf;
389 return 0 == lstat(path, &stbuf);
390}
391
Darin Petkov30291ed2010-11-12 10:23:06 -0800392bool IsSymlink(const char* path) {
393 struct stat stbuf;
394 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
395}
396
adlr@google.com3defe6a2009-12-04 20:57:17 +0000397std::string TempFilename(string path) {
398 static const string suffix("XXXXXX");
399 CHECK(StringHasSuffix(path, suffix));
400 do {
401 string new_suffix;
402 for (unsigned int i = 0; i < suffix.size(); i++) {
403 int r = rand() % (26 * 2 + 10); // [a-zA-Z0-9]
404 if (r < 26)
405 new_suffix.append(1, 'a' + r);
406 else if (r < (26 * 2))
407 new_suffix.append(1, 'A' + r - 26);
408 else
409 new_suffix.append(1, '0' + r - (26 * 2));
410 }
411 CHECK_EQ(new_suffix.size(), suffix.size());
412 path.resize(path.size() - new_suffix.size());
413 path.append(new_suffix);
414 } while (FileExists(path.c_str()));
415 return path;
416}
417
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700418bool MakeTempFile(const std::string& filename_template,
419 std::string* filename,
420 int* fd) {
421 DCHECK(filename || fd);
422 vector<char> buf(filename_template.size() + 1);
423 memcpy(&buf[0], filename_template.data(), filename_template.size());
424 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700425
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700426 int mkstemp_fd = mkstemp(&buf[0]);
427 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
428 if (filename) {
429 *filename = &buf[0];
430 }
431 if (fd) {
432 *fd = mkstemp_fd;
433 } else {
434 close(mkstemp_fd);
435 }
436 return true;
437}
438
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700439bool MakeTempDirectory(const std::string& dirname_template,
440 std::string* dirname) {
441 DCHECK(dirname);
442 vector<char> buf(dirname_template.size() + 1);
443 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
444 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700445
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700446 char* return_code = mkdtemp(&buf[0]);
447 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
448 *dirname = &buf[0];
449 return true;
450}
451
adlr@google.com3defe6a2009-12-04 20:57:17 +0000452bool StringHasSuffix(const std::string& str, const std::string& suffix) {
453 if (suffix.size() > str.size())
454 return false;
455 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
456}
457
458bool StringHasPrefix(const std::string& str, const std::string& prefix) {
459 if (prefix.size() > str.size())
460 return false;
461 return 0 == str.compare(0, prefix.size(), prefix);
462}
463
Will Drewry8f71da82010-08-30 14:07:11 -0500464const std::string BootDevice() {
465 char boot_path[PATH_MAX];
466 // Resolve the boot device path fully, including dereferencing
467 // through dm-verity.
468 int ret = rootdev(boot_path, sizeof(boot_path), true, false);
469
470 if (ret < 0) {
471 LOG(ERROR) << "rootdev failed to find the root device";
adlr@google.com3defe6a2009-12-04 20:57:17 +0000472 return "";
473 }
Will Drewry8f71da82010-08-30 14:07:11 -0500474 LOG_IF(WARNING, ret > 0) << "rootdev found a device name with no device node";
475
476 // This local variable is used to construct the return string and is not
477 // passed around after use.
478 return boot_path;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000479}
480
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700481const string BootKernelDevice(const std::string& boot_device) {
482 // Currntly this assumes the last digit of the boot device is
483 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
484 // get the kernel device.
485 string ret = boot_device;
486 if (ret.empty())
487 return ret;
488 char last_char = ret[ret.size() - 1];
489 if (last_char == '3' || last_char == '5' || last_char == '7') {
490 ret[ret.size() - 1] = last_char - 1;
491 return ret;
492 }
493 return "";
494}
495
adlr@google.com3defe6a2009-12-04 20:57:17 +0000496bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700497 const string& mountpoint,
498 unsigned long mountflags) {
499 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000500 if (rc < 0) {
501 string msg = ErrnoNumberAsString(errno);
502 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
503 << device << " on " << mountpoint;
504 return false;
505 }
506 return true;
507}
508
509bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700510 for (int num_retries = 0; ; ++num_retries) {
511 if (umount(mountpoint.c_str()) == 0)
512 break;
513
514 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
515 num_retries < kUnmountMaxNumOfRetries);
516 usleep(kUnmountRetryIntervalInMicroseconds);
517 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000518 return true;
519}
520
Darin Petkovd3f8c892010-10-12 21:38:45 -0700521bool GetFilesystemSize(const std::string& device,
522 int* out_block_count,
523 int* out_block_size) {
524 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
525 TEST_AND_RETURN_FALSE(fd >= 0);
526 ScopedFdCloser fd_closer(&fd);
527 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
528}
529
530bool GetFilesystemSizeFromFD(int fd,
531 int* out_block_count,
532 int* out_block_size) {
533 TEST_AND_RETURN_FALSE(fd >= 0);
534
535 // Determine the ext3 filesystem size by directly reading the block count and
536 // block size information from the superblock. See include/linux/ext3_fs.h for
537 // more details on the structure.
538 ssize_t kBufferSize = 16 * sizeof(uint32_t);
539 char buffer[kBufferSize];
540 const int kSuperblockOffset = 1024;
541 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
542 kBufferSize) {
543 PLOG(ERROR) << "Unable to determine file system size:";
544 return false;
545 }
546 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
547 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
548 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
549 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
550 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
551 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
552 block_count = le32toh(block_count);
553 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
554 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
555 magic = le16toh(magic);
556
557 // Sanity check the parameters.
558 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
559 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
560 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
561 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
562 int block_size = 1 << log_block_size;
563 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
564 block_size <= kExt3MaxBlockSize);
565 TEST_AND_RETURN_FALSE(block_count > 0);
566
567 if (out_block_count) {
568 *out_block_count = block_count;
569 }
570 if (out_block_size) {
571 *out_block_size = block_size;
572 }
573 return true;
574}
575
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700576bool GetBootloader(BootLoader* out_bootloader) {
577 // For now, hardcode to syslinux.
578 *out_bootloader = BootLoader_SYSLINUX;
579 return true;
580}
581
Darin Petkova0b9e772011-10-06 05:05:56 -0700582string GetAndFreeGError(GError** error) {
583 if (!*error) {
584 return "Unknown GLib error.";
585 }
586 string message =
587 base::StringPrintf("GError(%d): %s",
588 (*error)->code,
589 (*error)->message ? (*error)->message : "(unknown)");
590 g_error_free(*error);
591 *error = NULL;
592 return message;
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700593}
594
Darin Petkov296889c2010-07-23 16:20:54 -0700595bool Reboot() {
596 vector<string> command;
597 command.push_back("/sbin/shutdown");
598 command.push_back("-r");
599 command.push_back("now");
600 int rc = 0;
Darin Petkov85d02b72011-05-17 13:25:51 -0700601 Subprocess::SynchronousExec(command, &rc, NULL);
Darin Petkov296889c2010-07-23 16:20:54 -0700602 TEST_AND_RETURN_FALSE(rc == 0);
603 return true;
604}
605
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800606namespace {
607// Do the actual trigger. We do it as a main-loop callback to (try to) get a
608// consistent stack trace.
609gboolean TriggerCrashReporterUpload(void* unused) {
610 pid_t pid = fork();
611 CHECK(pid >= 0) << "fork failed"; // fork() failed. Something is very wrong.
612 if (pid == 0) {
613 // We are the child. Crash.
614 abort(); // never returns
615 }
616 // We are the parent. Wait for child to terminate.
617 pid_t result = waitpid(pid, NULL, 0);
618 LOG_IF(ERROR, result < 0) << "waitpid() failed";
619 return FALSE; // Don't call this callback again
620}
621} // namespace {}
622
623void ScheduleCrashReporterUpload() {
624 g_idle_add(&TriggerCrashReporterUpload, NULL);
625}
626
Darin Petkovc6c135c2010-08-11 13:36:18 -0700627bool SetProcessPriority(ProcessPriority priority) {
628 int prio = static_cast<int>(priority);
629 LOG(INFO) << "Setting process priority to " << prio;
630 TEST_AND_RETURN_FALSE(setpriority(PRIO_PROCESS, 0, prio) == 0);
631 return true;
632}
633
634int ComparePriorities(ProcessPriority priority_lhs,
635 ProcessPriority priority_rhs) {
636 return static_cast<int>(priority_rhs) - static_cast<int>(priority_lhs);
637}
638
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700639int FuzzInt(int value, unsigned int range) {
640 int min = value - range / 2;
641 int max = value + range - range / 2;
642 return base::RandInt(min, max);
643}
644
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800645gboolean GlibRunClosure(gpointer data) {
646 google::protobuf::Closure* callback =
647 reinterpret_cast<google::protobuf::Closure*>(data);
648 callback->Run();
649 return FALSE;
650}
651
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700652string FormatSecs(unsigned secs) {
653 return FormatTimeDelta(base::TimeDelta::FromSeconds(secs));
654}
655
656string FormatTimeDelta(base::TimeDelta delta) {
657 // Canonicalize into days, hours, minutes, seconds and microseconds.
658 unsigned days = delta.InDays();
659 delta -= base::TimeDelta::FromDays(days);
660 unsigned hours = delta.InHours();
661 delta -= base::TimeDelta::FromHours(hours);
662 unsigned mins = delta.InMinutes();
663 delta -= base::TimeDelta::FromMinutes(mins);
664 unsigned secs = delta.InSeconds();
665 delta -= base::TimeDelta::FromSeconds(secs);
666 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800667
668 // Construct and return string.
669 string str;
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700670 if (days)
671 base::StringAppendF(&str, "%ud", days);
672 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800673 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700674 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800675 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700676 base::StringAppendF(&str, "%u", secs);
677 if (usecs) {
678 int width = 6;
679 while ((usecs / 10) * 10 == usecs) {
680 usecs /= 10;
681 width--;
682 }
683 base::StringAppendF(&str, ".%0*u", width, usecs);
684 }
685 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800686 return str;
687}
688
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700689string ToString(const Time utc_time) {
690 Time::Exploded exp_time;
691 utc_time.UTCExplode(&exp_time);
692 return StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
693 exp_time.month,
694 exp_time.day_of_month,
695 exp_time.year,
696 exp_time.hour,
697 exp_time.minute,
698 exp_time.second);
699}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000700
701} // namespace utils
702
703} // namespace chromeos_update_engine