blob: e0d92447471a81bf2c751572373c619479aa3bab [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
44namespace utils {
45
Darin Petkova07586b2010-10-20 13:41:15 -070046static const char kDevImageMarker[] = "/root/.dev_mode";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070047const char* const kStatefulPartition = "/mnt/stateful_partition";
Darin Petkov2a0e6332010-09-24 14:43:41 -070048
Darin Petkov33d30642010-08-04 10:18:57 -070049bool IsOfficialBuild() {
Darin Petkova07586b2010-10-20 13:41:15 -070050 return !file_util::PathExists(FilePath(kDevImageMarker));
Darin Petkov33d30642010-08-04 10:18:57 -070051}
52
Darin Petkovc91dd6b2011-01-10 12:31:34 -080053bool IsNormalBootMode() {
Darin Petkov44d98d92011-03-21 16:08:11 -070054 // TODO(petkov): Convert to a library call once a crossystem library is
55 // available (crosbug.com/13291).
56 int exit_code = 0;
57 vector<string> cmd(1, "/usr/bin/crossystem");
58 cmd.push_back("devsw_boot?1");
59
60 // Assume dev mode if the dev switch is set to 1 and there was no error
61 // executing crossystem. Assume normal mode otherwise.
Darin Petkov85d02b72011-05-17 13:25:51 -070062 bool success = Subprocess::SynchronousExec(cmd, &exit_code, NULL);
Darin Petkov44d98d92011-03-21 16:08:11 -070063 bool dev_mode = success && exit_code == 0;
64 LOG_IF(INFO, dev_mode) << "Booted in dev mode.";
65 return !dev_mode;
Darin Petkovc91dd6b2011-01-10 12:31:34 -080066}
67
Darin Petkovf2065b42011-05-17 16:36:27 -070068string GetHardwareClass() {
69 // TODO(petkov): Convert to a library call once a crossystem library is
70 // available (crosbug.com/13291).
71 int exit_code = 0;
72 vector<string> cmd(1, "/usr/bin/crossystem");
73 cmd.push_back("hwid");
74
75 string hwid;
76 bool success = Subprocess::SynchronousExec(cmd, &exit_code, &hwid);
77 if (success && !exit_code) {
78 TrimWhitespaceASCII(hwid, TRIM_ALL, &hwid);
79 return hwid;
80 }
81 LOG(ERROR) << "Unable to read HWID (" << exit_code << ") " << hwid;
82 return "";
83}
84
Andrew de los Reyes970bb282009-12-09 16:34:04 -080085bool WriteFile(const char* path, const char* data, int data_len) {
86 DirectFileWriter writer;
87 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
88 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -070089 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -080090 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -080091 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -080092 return true;
93}
94
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070095bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070096 const char* c_buf = static_cast<const char*>(buf);
97 ssize_t bytes_written = 0;
98 while (bytes_written < static_cast<ssize_t>(count)) {
99 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
100 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
101 bytes_written += rc;
102 }
103 return true;
104}
105
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700106bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
107 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700108 size_t bytes_written = 0;
109 int num_attempts = 0;
110 while (bytes_written < count) {
111 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700112 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
113 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700114 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
115 if (rc < 0) {
116 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
117 << " bytes_written=" << bytes_written
118 << " count=" << count << " offset=" << offset;
119 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700120 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
121 bytes_written += rc;
122 }
123 return true;
124}
125
126bool PReadAll(int fd, void* buf, size_t count, off_t offset,
127 ssize_t* out_bytes_read) {
128 char* c_buf = static_cast<char*>(buf);
129 ssize_t bytes_read = 0;
130 while (bytes_read < static_cast<ssize_t>(count)) {
131 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
132 offset + bytes_read);
133 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
134 if (rc == 0) {
135 break;
136 }
137 bytes_read += rc;
138 }
139 *out_bytes_read = bytes_read;
140 return true;
Darin Petkov296889c2010-07-23 16:20:54 -0700141
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700142}
143
Gilad Arnold19a45f02012-07-19 12:36:10 -0700144// Append |nbytes| of content from |buf| to the vector pointed to by either
145// |vec_p| or |str_p|.
146static void AppendBytes(const char* buf, size_t nbytes,
147 std::vector<char>* vec_p) {
148 CHECK(buf);
149 CHECK(vec_p);
150 vec_p->insert(vec_p->end(), buf, buf + nbytes);
151}
152static void AppendBytes(const char* buf, size_t nbytes,
153 std::string* str_p) {
154 CHECK(buf);
155 CHECK(str_p);
156 str_p->append(buf, nbytes);
157}
158
159// Reads from an open file |fp|, appending the read content to the container
160// pointer to by |out_p|. Returns true upon successful reading all of the
161// file's content, false otherwise.
162template <class T>
163static bool Read(FILE* fp, T* out_p) {
164 CHECK(fp);
165 char buf[1024];
166 while (size_t nbytes = fread(buf, 1, sizeof(buf), fp))
167 AppendBytes(buf, nbytes, out_p);
168 return feof(fp) && !ferror(fp);
169}
170
171// Opens a file |path| for reading, then uses |append_func| to append its
172// content to a container |out_p|.
173template <class T>
174static bool ReadFileAndAppend(const std::string& path, T* out_p) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000175 FILE* fp = fopen(path.c_str(), "r");
176 if (!fp)
177 return false;
Gilad Arnold19a45f02012-07-19 12:36:10 -0700178 bool success = Read(fp, out_p);
179 return (success && !fclose(fp));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000180}
181
Gilad Arnold19a45f02012-07-19 12:36:10 -0700182// Invokes a pipe |cmd|, then uses |append_func| to append its stdout to a
183// container |out_p|.
184template <class T>
185static bool ReadPipeAndAppend(const std::string& cmd, T* out_p) {
186 FILE* fp = popen(cmd.c_str(), "r");
187 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000188 return false;
Gilad Arnold19a45f02012-07-19 12:36:10 -0700189 bool success = Read(fp, out_p);
190 return (success && pclose(fp) >= 0);
191}
192
193
194bool ReadFile(const std::string& path, std::vector<char>* out_p) {
195 return ReadFileAndAppend(path, out_p);
196}
197
198bool ReadFile(const std::string& path, std::string* out_p) {
199 return ReadFileAndAppend(path, out_p);
200}
201
202bool ReadPipe(const std::string& cmd, std::vector<char>* out_p) {
203 return ReadPipeAndAppend(cmd, out_p);
204}
205
206bool ReadPipe(const std::string& cmd, std::string* out_p) {
207 return ReadPipeAndAppend(cmd, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000208}
209
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700210off_t FileSize(const string& path) {
211 struct stat stbuf;
212 int rc = stat(path.c_str(), &stbuf);
213 CHECK_EQ(rc, 0);
214 if (rc < 0)
215 return rc;
216 return stbuf.st_size;
217}
218
adlr@google.com3defe6a2009-12-04 20:57:17 +0000219void HexDumpArray(const unsigned char* const arr, const size_t length) {
220 const unsigned char* const char_arr =
221 reinterpret_cast<const unsigned char* const>(arr);
222 LOG(INFO) << "Logging array of length: " << length;
223 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700224 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000225 const unsigned int bytes_remaining = length - i;
226 const unsigned int bytes_per_this_line = min(bytes_per_line,
227 bytes_remaining);
228 char header[100];
229 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
230 TEST_AND_RETURN(r == 13);
231 string line = header;
232 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
233 char buf[20];
234 unsigned char c = char_arr[i + j];
235 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
236 TEST_AND_RETURN(r == 3);
237 line += buf;
238 }
239 LOG(INFO) << line;
240 }
241}
242
243namespace {
244class ScopedDirCloser {
245 public:
246 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
247 ~ScopedDirCloser() {
248 if (dir_ && *dir_) {
249 int r = closedir(*dir_);
250 TEST_AND_RETURN_ERRNO(r == 0);
251 *dir_ = NULL;
252 dir_ = NULL;
253 }
254 }
255 private:
256 DIR** dir_;
257};
258} // namespace {}
259
260bool RecursiveUnlinkDir(const std::string& path) {
261 struct stat stbuf;
262 int r = lstat(path.c_str(), &stbuf);
263 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
264 if ((r < 0) && (errno == ENOENT))
265 // path request is missing. that's fine.
266 return true;
267 if (!S_ISDIR(stbuf.st_mode)) {
268 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700269 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000270 // success or path disappeared before we could unlink.
271 return true;
272 }
273 {
274 // We have a dir, unlink all children, then delete dir
275 DIR *dir = opendir(path.c_str());
276 TEST_AND_RETURN_FALSE_ERRNO(dir);
277 ScopedDirCloser dir_closer(&dir);
278 struct dirent dir_entry;
279 struct dirent *dir_entry_p;
280 int err = 0;
281 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
282 if (dir_entry_p == NULL) {
283 // end of stream reached
284 break;
285 }
286 // Skip . and ..
287 if (!strcmp(dir_entry_p->d_name, ".") ||
288 !strcmp(dir_entry_p->d_name, ".."))
289 continue;
290 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700291 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000292 }
293 TEST_AND_RETURN_FALSE(err == 0);
294 }
295 // unlink dir
296 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
297 return true;
298}
299
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700300string RootDevice(const string& partition_device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700301 FilePath device_path(partition_device);
302 if (device_path.DirName().value() != "/dev") {
303 return "";
304 }
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700305 string::const_iterator it = --partition_device.end();
306 for (; it >= partition_device.begin(); --it) {
307 if (!isdigit(*it))
308 break;
309 }
310 // Some devices contain a p before the partitions. For example:
311 // /dev/mmc0p4 should be shortened to /dev/mmc0.
312 if (*it == 'p')
313 --it;
314 return string(partition_device.begin(), it + 1);
315}
316
317string PartitionNumber(const string& partition_device) {
318 CHECK(!partition_device.empty());
319 string::const_iterator it = --partition_device.end();
320 for (; it >= partition_device.begin(); --it) {
321 if (!isdigit(*it))
322 break;
323 }
324 return string(it + 1, partition_device.end());
325}
326
Darin Petkovf74eb652010-08-04 12:08:38 -0700327string SysfsBlockDevice(const string& device) {
328 FilePath device_path(device);
329 if (device_path.DirName().value() != "/dev") {
330 return "";
331 }
332 return FilePath("/sys/block").Append(device_path.BaseName()).value();
333}
334
335bool IsRemovableDevice(const std::string& device) {
336 string sysfs_block = SysfsBlockDevice(device);
337 string removable;
338 if (sysfs_block.empty() ||
339 !file_util::ReadFileToString(FilePath(sysfs_block).Append("removable"),
340 &removable)) {
341 return false;
342 }
343 TrimWhitespaceASCII(removable, TRIM_ALL, &removable);
344 return removable == "1";
345}
346
adlr@google.com3defe6a2009-12-04 20:57:17 +0000347std::string ErrnoNumberAsString(int err) {
348 char buf[100];
349 buf[0] = '\0';
350 return strerror_r(err, buf, sizeof(buf));
351}
352
353std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
354 string ret;
355 bool last_insert_was_slash = false;
356 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
357 if (*it == '/') {
358 if (last_insert_was_slash)
359 continue;
360 last_insert_was_slash = true;
361 } else {
362 last_insert_was_slash = false;
363 }
364 ret.push_back(*it);
365 }
366 if (strip_trailing_slash && last_insert_was_slash) {
367 string::size_type last_non_slash = ret.find_last_not_of('/');
368 if (last_non_slash != string::npos) {
369 ret.resize(last_non_slash + 1);
370 } else {
371 ret = "";
372 }
373 }
374 return ret;
375}
376
377bool FileExists(const char* path) {
378 struct stat stbuf;
379 return 0 == lstat(path, &stbuf);
380}
381
Darin Petkov30291ed2010-11-12 10:23:06 -0800382bool IsSymlink(const char* path) {
383 struct stat stbuf;
384 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
385}
386
adlr@google.com3defe6a2009-12-04 20:57:17 +0000387std::string TempFilename(string path) {
388 static const string suffix("XXXXXX");
389 CHECK(StringHasSuffix(path, suffix));
390 do {
391 string new_suffix;
392 for (unsigned int i = 0; i < suffix.size(); i++) {
393 int r = rand() % (26 * 2 + 10); // [a-zA-Z0-9]
394 if (r < 26)
395 new_suffix.append(1, 'a' + r);
396 else if (r < (26 * 2))
397 new_suffix.append(1, 'A' + r - 26);
398 else
399 new_suffix.append(1, '0' + r - (26 * 2));
400 }
401 CHECK_EQ(new_suffix.size(), suffix.size());
402 path.resize(path.size() - new_suffix.size());
403 path.append(new_suffix);
404 } while (FileExists(path.c_str()));
405 return path;
406}
407
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700408bool MakeTempFile(const std::string& filename_template,
409 std::string* filename,
410 int* fd) {
411 DCHECK(filename || fd);
412 vector<char> buf(filename_template.size() + 1);
413 memcpy(&buf[0], filename_template.data(), filename_template.size());
414 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700415
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700416 int mkstemp_fd = mkstemp(&buf[0]);
417 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
418 if (filename) {
419 *filename = &buf[0];
420 }
421 if (fd) {
422 *fd = mkstemp_fd;
423 } else {
424 close(mkstemp_fd);
425 }
426 return true;
427}
428
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700429bool MakeTempDirectory(const std::string& dirname_template,
430 std::string* dirname) {
431 DCHECK(dirname);
432 vector<char> buf(dirname_template.size() + 1);
433 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
434 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700435
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700436 char* return_code = mkdtemp(&buf[0]);
437 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
438 *dirname = &buf[0];
439 return true;
440}
441
adlr@google.com3defe6a2009-12-04 20:57:17 +0000442bool StringHasSuffix(const std::string& str, const std::string& suffix) {
443 if (suffix.size() > str.size())
444 return false;
445 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
446}
447
448bool StringHasPrefix(const std::string& str, const std::string& prefix) {
449 if (prefix.size() > str.size())
450 return false;
451 return 0 == str.compare(0, prefix.size(), prefix);
452}
453
Will Drewry8f71da82010-08-30 14:07:11 -0500454const std::string BootDevice() {
455 char boot_path[PATH_MAX];
456 // Resolve the boot device path fully, including dereferencing
457 // through dm-verity.
458 int ret = rootdev(boot_path, sizeof(boot_path), true, false);
459
460 if (ret < 0) {
461 LOG(ERROR) << "rootdev failed to find the root device";
adlr@google.com3defe6a2009-12-04 20:57:17 +0000462 return "";
463 }
Will Drewry8f71da82010-08-30 14:07:11 -0500464 LOG_IF(WARNING, ret > 0) << "rootdev found a device name with no device node";
465
466 // This local variable is used to construct the return string and is not
467 // passed around after use.
468 return boot_path;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000469}
470
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700471const string BootKernelDevice(const std::string& boot_device) {
472 // Currntly this assumes the last digit of the boot device is
473 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
474 // get the kernel device.
475 string ret = boot_device;
476 if (ret.empty())
477 return ret;
478 char last_char = ret[ret.size() - 1];
479 if (last_char == '3' || last_char == '5' || last_char == '7') {
480 ret[ret.size() - 1] = last_char - 1;
481 return ret;
482 }
483 return "";
484}
485
adlr@google.com3defe6a2009-12-04 20:57:17 +0000486bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700487 const string& mountpoint,
488 unsigned long mountflags) {
489 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000490 if (rc < 0) {
491 string msg = ErrnoNumberAsString(errno);
492 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
493 << device << " on " << mountpoint;
494 return false;
495 }
496 return true;
497}
498
499bool UnmountFilesystem(const string& mountpoint) {
500 TEST_AND_RETURN_FALSE_ERRNO(umount(mountpoint.c_str()) == 0);
501 return true;
502}
503
Darin Petkovd3f8c892010-10-12 21:38:45 -0700504bool GetFilesystemSize(const std::string& device,
505 int* out_block_count,
506 int* out_block_size) {
507 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
508 TEST_AND_RETURN_FALSE(fd >= 0);
509 ScopedFdCloser fd_closer(&fd);
510 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
511}
512
513bool GetFilesystemSizeFromFD(int fd,
514 int* out_block_count,
515 int* out_block_size) {
516 TEST_AND_RETURN_FALSE(fd >= 0);
517
518 // Determine the ext3 filesystem size by directly reading the block count and
519 // block size information from the superblock. See include/linux/ext3_fs.h for
520 // more details on the structure.
521 ssize_t kBufferSize = 16 * sizeof(uint32_t);
522 char buffer[kBufferSize];
523 const int kSuperblockOffset = 1024;
524 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
525 kBufferSize) {
526 PLOG(ERROR) << "Unable to determine file system size:";
527 return false;
528 }
529 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
530 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
531 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
532 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
533 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
534 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
535 block_count = le32toh(block_count);
536 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
537 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
538 magic = le16toh(magic);
539
540 // Sanity check the parameters.
541 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
542 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
543 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
544 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
545 int block_size = 1 << log_block_size;
546 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
547 block_size <= kExt3MaxBlockSize);
548 TEST_AND_RETURN_FALSE(block_count > 0);
549
550 if (out_block_count) {
551 *out_block_count = block_count;
552 }
553 if (out_block_size) {
554 *out_block_size = block_size;
555 }
556 return true;
557}
558
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700559bool GetBootloader(BootLoader* out_bootloader) {
560 // For now, hardcode to syslinux.
561 *out_bootloader = BootLoader_SYSLINUX;
562 return true;
563}
564
Darin Petkova0b9e772011-10-06 05:05:56 -0700565string GetAndFreeGError(GError** error) {
566 if (!*error) {
567 return "Unknown GLib error.";
568 }
569 string message =
570 base::StringPrintf("GError(%d): %s",
571 (*error)->code,
572 (*error)->message ? (*error)->message : "(unknown)");
573 g_error_free(*error);
574 *error = NULL;
575 return message;
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700576}
577
Darin Petkov296889c2010-07-23 16:20:54 -0700578bool Reboot() {
579 vector<string> command;
580 command.push_back("/sbin/shutdown");
581 command.push_back("-r");
582 command.push_back("now");
583 int rc = 0;
Darin Petkov85d02b72011-05-17 13:25:51 -0700584 Subprocess::SynchronousExec(command, &rc, NULL);
Darin Petkov296889c2010-07-23 16:20:54 -0700585 TEST_AND_RETURN_FALSE(rc == 0);
586 return true;
587}
588
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800589namespace {
590// Do the actual trigger. We do it as a main-loop callback to (try to) get a
591// consistent stack trace.
592gboolean TriggerCrashReporterUpload(void* unused) {
593 pid_t pid = fork();
594 CHECK(pid >= 0) << "fork failed"; // fork() failed. Something is very wrong.
595 if (pid == 0) {
596 // We are the child. Crash.
597 abort(); // never returns
598 }
599 // We are the parent. Wait for child to terminate.
600 pid_t result = waitpid(pid, NULL, 0);
601 LOG_IF(ERROR, result < 0) << "waitpid() failed";
602 return FALSE; // Don't call this callback again
603}
604} // namespace {}
605
606void ScheduleCrashReporterUpload() {
607 g_idle_add(&TriggerCrashReporterUpload, NULL);
608}
609
Darin Petkovc6c135c2010-08-11 13:36:18 -0700610bool SetProcessPriority(ProcessPriority priority) {
611 int prio = static_cast<int>(priority);
612 LOG(INFO) << "Setting process priority to " << prio;
613 TEST_AND_RETURN_FALSE(setpriority(PRIO_PROCESS, 0, prio) == 0);
614 return true;
615}
616
617int ComparePriorities(ProcessPriority priority_lhs,
618 ProcessPriority priority_rhs) {
619 return static_cast<int>(priority_rhs) - static_cast<int>(priority_lhs);
620}
621
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700622int FuzzInt(int value, unsigned int range) {
623 int min = value - range / 2;
624 int max = value + range - range / 2;
625 return base::RandInt(min, max);
626}
627
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800628gboolean GlibRunClosure(gpointer data) {
629 google::protobuf::Closure* callback =
630 reinterpret_cast<google::protobuf::Closure*>(data);
631 callback->Run();
632 return FALSE;
633}
634
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700635string FormatSecs(unsigned secs) {
636 return FormatTimeDelta(base::TimeDelta::FromSeconds(secs));
637}
638
639string FormatTimeDelta(base::TimeDelta delta) {
640 // Canonicalize into days, hours, minutes, seconds and microseconds.
641 unsigned days = delta.InDays();
642 delta -= base::TimeDelta::FromDays(days);
643 unsigned hours = delta.InHours();
644 delta -= base::TimeDelta::FromHours(hours);
645 unsigned mins = delta.InMinutes();
646 delta -= base::TimeDelta::FromMinutes(mins);
647 unsigned secs = delta.InSeconds();
648 delta -= base::TimeDelta::FromSeconds(secs);
649 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800650
651 // Construct and return string.
652 string str;
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700653 if (days)
654 base::StringAppendF(&str, "%ud", days);
655 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800656 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700657 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800658 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700659 base::StringAppendF(&str, "%u", secs);
660 if (usecs) {
661 int width = 6;
662 while ((usecs / 10) * 10 == usecs) {
663 usecs /= 10;
664 width--;
665 }
666 base::StringAppendF(&str, ".%0*u", width, usecs);
667 }
668 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800669 return str;
670}
671
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700672string ToString(const Time utc_time) {
673 Time::Exploded exp_time;
674 utc_time.UTCExplode(&exp_time);
675 return StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
676 exp_time.month,
677 exp_time.day_of_month,
678 exp_time.year,
679 exp_time.hour,
680 exp_time.minute,
681 exp_time.second);
682}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000683
684} // namespace utils
685
686} // namespace chromeos_update_engine