blob: 5a1d81248324a792849e8cdac973ff692178f3c8 [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
Chris Sosa4f8ee272012-11-30 13:01:54 -080059// Cgroup container is created in update-engine's upstart script located at
60// /etc/init/update-engine.conf.
61static const char kCGroupDir[] = "/sys/fs/cgroup/cpu/update-engine";
62
Darin Petkov33d30642010-08-04 10:18:57 -070063bool IsOfficialBuild() {
Darin Petkova07586b2010-10-20 13:41:15 -070064 return !file_util::PathExists(FilePath(kDevImageMarker));
Darin Petkov33d30642010-08-04 10:18:57 -070065}
66
Darin Petkovc91dd6b2011-01-10 12:31:34 -080067bool IsNormalBootMode() {
Darin Petkov44d98d92011-03-21 16:08:11 -070068 // TODO(petkov): Convert to a library call once a crossystem library is
69 // available (crosbug.com/13291).
70 int exit_code = 0;
71 vector<string> cmd(1, "/usr/bin/crossystem");
72 cmd.push_back("devsw_boot?1");
73
74 // Assume dev mode if the dev switch is set to 1 and there was no error
75 // executing crossystem. Assume normal mode otherwise.
Darin Petkov85d02b72011-05-17 13:25:51 -070076 bool success = Subprocess::SynchronousExec(cmd, &exit_code, NULL);
Darin Petkov44d98d92011-03-21 16:08:11 -070077 bool dev_mode = success && exit_code == 0;
78 LOG_IF(INFO, dev_mode) << "Booted in dev mode.";
79 return !dev_mode;
Darin Petkovc91dd6b2011-01-10 12:31:34 -080080}
81
Darin Petkovf2065b42011-05-17 16:36:27 -070082string GetHardwareClass() {
83 // TODO(petkov): Convert to a library call once a crossystem library is
84 // available (crosbug.com/13291).
85 int exit_code = 0;
86 vector<string> cmd(1, "/usr/bin/crossystem");
87 cmd.push_back("hwid");
88
89 string hwid;
90 bool success = Subprocess::SynchronousExec(cmd, &exit_code, &hwid);
91 if (success && !exit_code) {
92 TrimWhitespaceASCII(hwid, TRIM_ALL, &hwid);
93 return hwid;
94 }
95 LOG(ERROR) << "Unable to read HWID (" << exit_code << ") " << hwid;
96 return "";
97}
98
Andrew de los Reyes970bb282009-12-09 16:34:04 -080099bool WriteFile(const char* path, const char* data, int data_len) {
100 DirectFileWriter writer;
101 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
102 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700103 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800104 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800105 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800106 return true;
107}
108
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700109bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700110 const char* c_buf = static_cast<const char*>(buf);
111 ssize_t bytes_written = 0;
112 while (bytes_written < static_cast<ssize_t>(count)) {
113 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
114 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
115 bytes_written += rc;
116 }
117 return true;
118}
119
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700120bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
121 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700122 size_t bytes_written = 0;
123 int num_attempts = 0;
124 while (bytes_written < count) {
125 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700126 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
127 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700128 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
129 if (rc < 0) {
130 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
131 << " bytes_written=" << bytes_written
132 << " count=" << count << " offset=" << offset;
133 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700134 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
135 bytes_written += rc;
136 }
137 return true;
138}
139
140bool PReadAll(int fd, void* buf, size_t count, off_t offset,
141 ssize_t* out_bytes_read) {
142 char* c_buf = static_cast<char*>(buf);
143 ssize_t bytes_read = 0;
144 while (bytes_read < static_cast<ssize_t>(count)) {
145 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
146 offset + bytes_read);
147 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
148 if (rc == 0) {
149 break;
150 }
151 bytes_read += rc;
152 }
153 *out_bytes_read = bytes_read;
154 return true;
Darin Petkov296889c2010-07-23 16:20:54 -0700155
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700156}
157
Gilad Arnold19a45f02012-07-19 12:36:10 -0700158// Append |nbytes| of content from |buf| to the vector pointed to by either
159// |vec_p| or |str_p|.
160static void AppendBytes(const char* buf, size_t nbytes,
161 std::vector<char>* vec_p) {
162 CHECK(buf);
163 CHECK(vec_p);
164 vec_p->insert(vec_p->end(), buf, buf + nbytes);
165}
166static void AppendBytes(const char* buf, size_t nbytes,
167 std::string* str_p) {
168 CHECK(buf);
169 CHECK(str_p);
170 str_p->append(buf, nbytes);
171}
172
173// Reads from an open file |fp|, appending the read content to the container
174// pointer to by |out_p|. Returns true upon successful reading all of the
175// file's content, false otherwise.
176template <class T>
177static bool Read(FILE* fp, T* out_p) {
178 CHECK(fp);
179 char buf[1024];
180 while (size_t nbytes = fread(buf, 1, sizeof(buf), fp))
181 AppendBytes(buf, nbytes, out_p);
182 return feof(fp) && !ferror(fp);
183}
184
185// Opens a file |path| for reading, then uses |append_func| to append its
186// content to a container |out_p|.
187template <class T>
188static bool ReadFileAndAppend(const std::string& path, T* out_p) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000189 FILE* fp = fopen(path.c_str(), "r");
190 if (!fp)
191 return false;
Gilad Arnold19a45f02012-07-19 12:36:10 -0700192 bool success = Read(fp, out_p);
193 return (success && !fclose(fp));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000194}
195
Gilad Arnold19a45f02012-07-19 12:36:10 -0700196// Invokes a pipe |cmd|, then uses |append_func| to append its stdout to a
197// container |out_p|.
198template <class T>
199static bool ReadPipeAndAppend(const std::string& cmd, T* out_p) {
200 FILE* fp = popen(cmd.c_str(), "r");
201 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000202 return false;
Gilad Arnold19a45f02012-07-19 12:36:10 -0700203 bool success = Read(fp, out_p);
204 return (success && pclose(fp) >= 0);
205}
206
207
208bool ReadFile(const std::string& path, std::vector<char>* out_p) {
209 return ReadFileAndAppend(path, out_p);
210}
211
212bool ReadFile(const std::string& path, std::string* out_p) {
213 return ReadFileAndAppend(path, out_p);
214}
215
216bool ReadPipe(const std::string& cmd, std::vector<char>* out_p) {
217 return ReadPipeAndAppend(cmd, out_p);
218}
219
220bool ReadPipe(const std::string& cmd, std::string* out_p) {
221 return ReadPipeAndAppend(cmd, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000222}
223
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700224off_t FileSize(const string& path) {
225 struct stat stbuf;
226 int rc = stat(path.c_str(), &stbuf);
227 CHECK_EQ(rc, 0);
228 if (rc < 0)
229 return rc;
230 return stbuf.st_size;
231}
232
adlr@google.com3defe6a2009-12-04 20:57:17 +0000233void HexDumpArray(const unsigned char* const arr, const size_t length) {
234 const unsigned char* const char_arr =
235 reinterpret_cast<const unsigned char* const>(arr);
236 LOG(INFO) << "Logging array of length: " << length;
237 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700238 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000239 const unsigned int bytes_remaining = length - i;
240 const unsigned int bytes_per_this_line = min(bytes_per_line,
241 bytes_remaining);
242 char header[100];
243 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
244 TEST_AND_RETURN(r == 13);
245 string line = header;
246 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
247 char buf[20];
248 unsigned char c = char_arr[i + j];
249 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
250 TEST_AND_RETURN(r == 3);
251 line += buf;
252 }
253 LOG(INFO) << line;
254 }
255}
256
257namespace {
258class ScopedDirCloser {
259 public:
260 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
261 ~ScopedDirCloser() {
262 if (dir_ && *dir_) {
263 int r = closedir(*dir_);
264 TEST_AND_RETURN_ERRNO(r == 0);
265 *dir_ = NULL;
266 dir_ = NULL;
267 }
268 }
269 private:
270 DIR** dir_;
271};
272} // namespace {}
273
274bool RecursiveUnlinkDir(const std::string& path) {
275 struct stat stbuf;
276 int r = lstat(path.c_str(), &stbuf);
277 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
278 if ((r < 0) && (errno == ENOENT))
279 // path request is missing. that's fine.
280 return true;
281 if (!S_ISDIR(stbuf.st_mode)) {
282 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700283 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000284 // success or path disappeared before we could unlink.
285 return true;
286 }
287 {
288 // We have a dir, unlink all children, then delete dir
289 DIR *dir = opendir(path.c_str());
290 TEST_AND_RETURN_FALSE_ERRNO(dir);
291 ScopedDirCloser dir_closer(&dir);
292 struct dirent dir_entry;
293 struct dirent *dir_entry_p;
294 int err = 0;
295 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
296 if (dir_entry_p == NULL) {
297 // end of stream reached
298 break;
299 }
300 // Skip . and ..
301 if (!strcmp(dir_entry_p->d_name, ".") ||
302 !strcmp(dir_entry_p->d_name, ".."))
303 continue;
304 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700305 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000306 }
307 TEST_AND_RETURN_FALSE(err == 0);
308 }
309 // unlink dir
310 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
311 return true;
312}
313
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700314string RootDevice(const string& partition_device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700315 FilePath device_path(partition_device);
316 if (device_path.DirName().value() != "/dev") {
317 return "";
318 }
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700319 string::const_iterator it = --partition_device.end();
320 for (; it >= partition_device.begin(); --it) {
321 if (!isdigit(*it))
322 break;
323 }
324 // Some devices contain a p before the partitions. For example:
325 // /dev/mmc0p4 should be shortened to /dev/mmc0.
326 if (*it == 'p')
327 --it;
328 return string(partition_device.begin(), it + 1);
329}
330
331string PartitionNumber(const string& partition_device) {
332 CHECK(!partition_device.empty());
333 string::const_iterator it = --partition_device.end();
334 for (; it >= partition_device.begin(); --it) {
335 if (!isdigit(*it))
336 break;
337 }
338 return string(it + 1, partition_device.end());
339}
340
Darin Petkovf74eb652010-08-04 12:08:38 -0700341string SysfsBlockDevice(const string& device) {
342 FilePath device_path(device);
343 if (device_path.DirName().value() != "/dev") {
344 return "";
345 }
346 return FilePath("/sys/block").Append(device_path.BaseName()).value();
347}
348
349bool IsRemovableDevice(const std::string& device) {
350 string sysfs_block = SysfsBlockDevice(device);
351 string removable;
352 if (sysfs_block.empty() ||
353 !file_util::ReadFileToString(FilePath(sysfs_block).Append("removable"),
354 &removable)) {
355 return false;
356 }
357 TrimWhitespaceASCII(removable, TRIM_ALL, &removable);
358 return removable == "1";
359}
360
adlr@google.com3defe6a2009-12-04 20:57:17 +0000361std::string ErrnoNumberAsString(int err) {
362 char buf[100];
363 buf[0] = '\0';
364 return strerror_r(err, buf, sizeof(buf));
365}
366
367std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
368 string ret;
369 bool last_insert_was_slash = false;
370 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
371 if (*it == '/') {
372 if (last_insert_was_slash)
373 continue;
374 last_insert_was_slash = true;
375 } else {
376 last_insert_was_slash = false;
377 }
378 ret.push_back(*it);
379 }
380 if (strip_trailing_slash && last_insert_was_slash) {
381 string::size_type last_non_slash = ret.find_last_not_of('/');
382 if (last_non_slash != string::npos) {
383 ret.resize(last_non_slash + 1);
384 } else {
385 ret = "";
386 }
387 }
388 return ret;
389}
390
391bool FileExists(const char* path) {
392 struct stat stbuf;
393 return 0 == lstat(path, &stbuf);
394}
395
Darin Petkov30291ed2010-11-12 10:23:06 -0800396bool IsSymlink(const char* path) {
397 struct stat stbuf;
398 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
399}
400
adlr@google.com3defe6a2009-12-04 20:57:17 +0000401std::string TempFilename(string path) {
402 static const string suffix("XXXXXX");
403 CHECK(StringHasSuffix(path, suffix));
404 do {
405 string new_suffix;
406 for (unsigned int i = 0; i < suffix.size(); i++) {
407 int r = rand() % (26 * 2 + 10); // [a-zA-Z0-9]
408 if (r < 26)
409 new_suffix.append(1, 'a' + r);
410 else if (r < (26 * 2))
411 new_suffix.append(1, 'A' + r - 26);
412 else
413 new_suffix.append(1, '0' + r - (26 * 2));
414 }
415 CHECK_EQ(new_suffix.size(), suffix.size());
416 path.resize(path.size() - new_suffix.size());
417 path.append(new_suffix);
418 } while (FileExists(path.c_str()));
419 return path;
420}
421
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700422bool MakeTempFile(const std::string& filename_template,
423 std::string* filename,
424 int* fd) {
425 DCHECK(filename || fd);
426 vector<char> buf(filename_template.size() + 1);
427 memcpy(&buf[0], filename_template.data(), filename_template.size());
428 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700429
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700430 int mkstemp_fd = mkstemp(&buf[0]);
431 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
432 if (filename) {
433 *filename = &buf[0];
434 }
435 if (fd) {
436 *fd = mkstemp_fd;
437 } else {
438 close(mkstemp_fd);
439 }
440 return true;
441}
442
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700443bool MakeTempDirectory(const std::string& dirname_template,
444 std::string* dirname) {
445 DCHECK(dirname);
446 vector<char> buf(dirname_template.size() + 1);
447 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
448 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700449
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700450 char* return_code = mkdtemp(&buf[0]);
451 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
452 *dirname = &buf[0];
453 return true;
454}
455
adlr@google.com3defe6a2009-12-04 20:57:17 +0000456bool StringHasSuffix(const std::string& str, const std::string& suffix) {
457 if (suffix.size() > str.size())
458 return false;
459 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
460}
461
462bool StringHasPrefix(const std::string& str, const std::string& prefix) {
463 if (prefix.size() > str.size())
464 return false;
465 return 0 == str.compare(0, prefix.size(), prefix);
466}
467
Will Drewry8f71da82010-08-30 14:07:11 -0500468const std::string BootDevice() {
469 char boot_path[PATH_MAX];
470 // Resolve the boot device path fully, including dereferencing
471 // through dm-verity.
472 int ret = rootdev(boot_path, sizeof(boot_path), true, false);
473
474 if (ret < 0) {
475 LOG(ERROR) << "rootdev failed to find the root device";
adlr@google.com3defe6a2009-12-04 20:57:17 +0000476 return "";
477 }
Will Drewry8f71da82010-08-30 14:07:11 -0500478 LOG_IF(WARNING, ret > 0) << "rootdev found a device name with no device node";
479
480 // This local variable is used to construct the return string and is not
481 // passed around after use.
482 return boot_path;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000483}
484
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700485const string BootKernelDevice(const std::string& boot_device) {
486 // Currntly this assumes the last digit of the boot device is
487 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
488 // get the kernel device.
489 string ret = boot_device;
490 if (ret.empty())
491 return ret;
492 char last_char = ret[ret.size() - 1];
493 if (last_char == '3' || last_char == '5' || last_char == '7') {
494 ret[ret.size() - 1] = last_char - 1;
495 return ret;
496 }
497 return "";
498}
499
adlr@google.com3defe6a2009-12-04 20:57:17 +0000500bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700501 const string& mountpoint,
502 unsigned long mountflags) {
503 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000504 if (rc < 0) {
505 string msg = ErrnoNumberAsString(errno);
506 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
507 << device << " on " << mountpoint;
508 return false;
509 }
510 return true;
511}
512
513bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700514 for (int num_retries = 0; ; ++num_retries) {
515 if (umount(mountpoint.c_str()) == 0)
516 break;
517
518 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
519 num_retries < kUnmountMaxNumOfRetries);
520 usleep(kUnmountRetryIntervalInMicroseconds);
521 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000522 return true;
523}
524
Darin Petkovd3f8c892010-10-12 21:38:45 -0700525bool GetFilesystemSize(const std::string& device,
526 int* out_block_count,
527 int* out_block_size) {
528 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
529 TEST_AND_RETURN_FALSE(fd >= 0);
530 ScopedFdCloser fd_closer(&fd);
531 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
532}
533
534bool GetFilesystemSizeFromFD(int fd,
535 int* out_block_count,
536 int* out_block_size) {
537 TEST_AND_RETURN_FALSE(fd >= 0);
538
539 // Determine the ext3 filesystem size by directly reading the block count and
540 // block size information from the superblock. See include/linux/ext3_fs.h for
541 // more details on the structure.
542 ssize_t kBufferSize = 16 * sizeof(uint32_t);
543 char buffer[kBufferSize];
544 const int kSuperblockOffset = 1024;
545 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
546 kBufferSize) {
547 PLOG(ERROR) << "Unable to determine file system size:";
548 return false;
549 }
550 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
551 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
552 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
553 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
554 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
555 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
556 block_count = le32toh(block_count);
557 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
558 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
559 magic = le16toh(magic);
560
561 // Sanity check the parameters.
562 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
563 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
564 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
565 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
566 int block_size = 1 << log_block_size;
567 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
568 block_size <= kExt3MaxBlockSize);
569 TEST_AND_RETURN_FALSE(block_count > 0);
570
571 if (out_block_count) {
572 *out_block_count = block_count;
573 }
574 if (out_block_size) {
575 *out_block_size = block_size;
576 }
577 return true;
578}
579
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700580bool GetBootloader(BootLoader* out_bootloader) {
581 // For now, hardcode to syslinux.
582 *out_bootloader = BootLoader_SYSLINUX;
583 return true;
584}
585
Darin Petkova0b9e772011-10-06 05:05:56 -0700586string GetAndFreeGError(GError** error) {
587 if (!*error) {
588 return "Unknown GLib error.";
589 }
590 string message =
591 base::StringPrintf("GError(%d): %s",
592 (*error)->code,
593 (*error)->message ? (*error)->message : "(unknown)");
594 g_error_free(*error);
595 *error = NULL;
596 return message;
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700597}
598
Darin Petkov296889c2010-07-23 16:20:54 -0700599bool Reboot() {
600 vector<string> command;
601 command.push_back("/sbin/shutdown");
602 command.push_back("-r");
603 command.push_back("now");
604 int rc = 0;
Darin Petkov85d02b72011-05-17 13:25:51 -0700605 Subprocess::SynchronousExec(command, &rc, NULL);
Darin Petkov296889c2010-07-23 16:20:54 -0700606 TEST_AND_RETURN_FALSE(rc == 0);
607 return true;
608}
609
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800610namespace {
611// Do the actual trigger. We do it as a main-loop callback to (try to) get a
612// consistent stack trace.
613gboolean TriggerCrashReporterUpload(void* unused) {
614 pid_t pid = fork();
615 CHECK(pid >= 0) << "fork failed"; // fork() failed. Something is very wrong.
616 if (pid == 0) {
617 // We are the child. Crash.
618 abort(); // never returns
619 }
620 // We are the parent. Wait for child to terminate.
621 pid_t result = waitpid(pid, NULL, 0);
622 LOG_IF(ERROR, result < 0) << "waitpid() failed";
623 return FALSE; // Don't call this callback again
624}
625} // namespace {}
626
627void ScheduleCrashReporterUpload() {
628 g_idle_add(&TriggerCrashReporterUpload, NULL);
629}
630
Chris Sosa4f8ee272012-11-30 13:01:54 -0800631bool SetCpuShares(CpuShares shares) {
632 string string_shares = base::IntToString(static_cast<int>(shares));
633 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
634 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
635 if(utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
636 string_shares.size())){
637 return true;
638 } else {
639 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
640 << " using " << cpu_shares_file;
641 return false;
642 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700643}
644
Chris Sosa4f8ee272012-11-30 13:01:54 -0800645int CompareCpuShares(CpuShares shares_lhs,
646 CpuShares shares_rhs) {
647 return static_cast<int>(shares_lhs) - static_cast<int>(shares_rhs);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700648}
649
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700650int FuzzInt(int value, unsigned int range) {
651 int min = value - range / 2;
652 int max = value + range - range / 2;
653 return base::RandInt(min, max);
654}
655
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800656gboolean GlibRunClosure(gpointer data) {
657 google::protobuf::Closure* callback =
658 reinterpret_cast<google::protobuf::Closure*>(data);
659 callback->Run();
660 return FALSE;
661}
662
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700663string FormatSecs(unsigned secs) {
664 return FormatTimeDelta(base::TimeDelta::FromSeconds(secs));
665}
666
667string FormatTimeDelta(base::TimeDelta delta) {
668 // Canonicalize into days, hours, minutes, seconds and microseconds.
669 unsigned days = delta.InDays();
670 delta -= base::TimeDelta::FromDays(days);
671 unsigned hours = delta.InHours();
672 delta -= base::TimeDelta::FromHours(hours);
673 unsigned mins = delta.InMinutes();
674 delta -= base::TimeDelta::FromMinutes(mins);
675 unsigned secs = delta.InSeconds();
676 delta -= base::TimeDelta::FromSeconds(secs);
677 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800678
679 // Construct and return string.
680 string str;
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700681 if (days)
682 base::StringAppendF(&str, "%ud", days);
683 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800684 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700685 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800686 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700687 base::StringAppendF(&str, "%u", secs);
688 if (usecs) {
689 int width = 6;
690 while ((usecs / 10) * 10 == usecs) {
691 usecs /= 10;
692 width--;
693 }
694 base::StringAppendF(&str, ".%0*u", width, usecs);
695 }
696 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800697 return str;
698}
699
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700700string ToString(const Time utc_time) {
701 Time::Exploded exp_time;
702 utc_time.UTCExplode(&exp_time);
703 return StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
704 exp_time.month,
705 exp_time.day_of_month,
706 exp_time.year,
707 exp_time.hour,
708 exp_time.minute,
709 exp_time.second);
710}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000711
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800712ActionExitCode GetBaseErrorCode(ActionExitCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700713 // Ignore the higher order bits in the code by applying the mask as
714 // we want the enumerations to be in the small contiguous range
Jay Srinivasanedce2832012-10-24 18:57:47 -0700715 // with values less than kActionCodeUmaReportedMax.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800716 ActionExitCode base_code = static_cast<ActionExitCode>(
717 code & kActualCodeMask);
Jay Srinivasanf0572052012-10-23 18:12:56 -0700718
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800719 // Make additional adjustments required for UMA and error classification.
720 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
721 // chromium-os:34369.
722 if (base_code >= kActionCodeOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700723 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800724 // errors into this one bucket for UMA and error classification purposes.
725 base_code = kActionCodeOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700726 }
727
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800728 return base_code;
729}
730
731
732
733void SendErrorCodeToUma(MetricsLibraryInterface* metrics_lib,
734 ActionExitCode code) {
735 string metric = utils::IsNormalBootMode() ? "Installer.NormalErrorCodes" :
736 "Installer.DevModeErrorCodes";
737
738 ActionExitCode reported_code = GetBaseErrorCode(code);
739
Jay Srinivasanedce2832012-10-24 18:57:47 -0700740 LOG(INFO) << "Sending error code " << reported_code
741 << " to UMA metric: " << metric;
742 metrics_lib->SendEnumToUMA(metric, reported_code, kActionCodeUmaReportedMax);
Jay Srinivasanf0572052012-10-23 18:12:56 -0700743}
744
745
adlr@google.com3defe6a2009-12-04 20:57:17 +0000746} // namespace utils
747
748} // namespace chromeos_update_engine