blob: e5d7290fdd870a743858f0303979992067f5edef [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>
Gilad Arnold8e3f1262013-01-08 14:59:54 -080030#include <glib.h>
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -080031#include <google/protobuf/stubs/common.h>
Will Drewry8f71da82010-08-30 14:07:11 -050032#include <rootdev/rootdev.h>
33
Andrew de los Reyes970bb282009-12-09 16:34:04 -080034#include "update_engine/file_writer.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;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080039using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000040using std::min;
41using std::string;
42using std::vector;
43
44namespace chromeos_update_engine {
45
Ben Chan77a1eba2012-10-07 22:54:55 -070046namespace {
47
48// The following constants control how UnmountFilesystem should retry if
49// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
50// one second.
51const int kUnmountMaxNumOfRetries = 5;
52const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
53
54} // namespace
55
adlr@google.com3defe6a2009-12-04 20:57:17 +000056namespace utils {
57
Darin Petkova07586b2010-10-20 13:41:15 -070058static const char kDevImageMarker[] = "/root/.dev_mode";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070059const char* const kStatefulPartition = "/mnt/stateful_partition";
Darin Petkov2a0e6332010-09-24 14:43:41 -070060
Chris Sosa4f8ee272012-11-30 13:01:54 -080061// Cgroup container is created in update-engine's upstart script located at
62// /etc/init/update-engine.conf.
63static const char kCGroupDir[] = "/sys/fs/cgroup/cpu/update-engine";
64
Darin Petkov33d30642010-08-04 10:18:57 -070065bool IsOfficialBuild() {
Darin Petkova07586b2010-10-20 13:41:15 -070066 return !file_util::PathExists(FilePath(kDevImageMarker));
Darin Petkov33d30642010-08-04 10:18:57 -070067}
68
Darin Petkovc91dd6b2011-01-10 12:31:34 -080069bool IsNormalBootMode() {
Darin Petkov44d98d92011-03-21 16:08:11 -070070 // TODO(petkov): Convert to a library call once a crossystem library is
71 // available (crosbug.com/13291).
72 int exit_code = 0;
73 vector<string> cmd(1, "/usr/bin/crossystem");
74 cmd.push_back("devsw_boot?1");
75
76 // Assume dev mode if the dev switch is set to 1 and there was no error
77 // executing crossystem. Assume normal mode otherwise.
Darin Petkov85d02b72011-05-17 13:25:51 -070078 bool success = Subprocess::SynchronousExec(cmd, &exit_code, NULL);
Darin Petkov44d98d92011-03-21 16:08:11 -070079 bool dev_mode = success && exit_code == 0;
80 LOG_IF(INFO, dev_mode) << "Booted in dev mode.";
81 return !dev_mode;
Darin Petkovc91dd6b2011-01-10 12:31:34 -080082}
83
Darin Petkovf2065b42011-05-17 16:36:27 -070084string GetHardwareClass() {
85 // TODO(petkov): Convert to a library call once a crossystem library is
86 // available (crosbug.com/13291).
87 int exit_code = 0;
88 vector<string> cmd(1, "/usr/bin/crossystem");
89 cmd.push_back("hwid");
90
91 string hwid;
92 bool success = Subprocess::SynchronousExec(cmd, &exit_code, &hwid);
93 if (success && !exit_code) {
94 TrimWhitespaceASCII(hwid, TRIM_ALL, &hwid);
95 return hwid;
96 }
97 LOG(ERROR) << "Unable to read HWID (" << exit_code << ") " << hwid;
98 return "";
99}
100
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800101bool WriteFile(const char* path, const char* data, int data_len) {
102 DirectFileWriter writer;
103 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
104 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700105 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800106 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800107 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800108 return true;
109}
110
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700111bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700112 const char* c_buf = static_cast<const char*>(buf);
113 ssize_t bytes_written = 0;
114 while (bytes_written < static_cast<ssize_t>(count)) {
115 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
116 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
117 bytes_written += rc;
118 }
119 return true;
120}
121
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700122bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
123 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700124 size_t bytes_written = 0;
125 int num_attempts = 0;
126 while (bytes_written < count) {
127 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700128 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
129 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700130 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
131 if (rc < 0) {
132 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
133 << " bytes_written=" << bytes_written
134 << " count=" << count << " offset=" << offset;
135 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700136 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
137 bytes_written += rc;
138 }
139 return true;
140}
141
142bool PReadAll(int fd, void* buf, size_t count, off_t offset,
143 ssize_t* out_bytes_read) {
144 char* c_buf = static_cast<char*>(buf);
145 ssize_t bytes_read = 0;
146 while (bytes_read < static_cast<ssize_t>(count)) {
147 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
148 offset + bytes_read);
149 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
150 if (rc == 0) {
151 break;
152 }
153 bytes_read += rc;
154 }
155 *out_bytes_read = bytes_read;
156 return true;
Darin Petkov296889c2010-07-23 16:20:54 -0700157
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700158}
159
Gilad Arnold19a45f02012-07-19 12:36:10 -0700160// Append |nbytes| of content from |buf| to the vector pointed to by either
161// |vec_p| or |str_p|.
162static void AppendBytes(const char* buf, size_t nbytes,
163 std::vector<char>* vec_p) {
164 CHECK(buf);
165 CHECK(vec_p);
166 vec_p->insert(vec_p->end(), buf, buf + nbytes);
167}
168static void AppendBytes(const char* buf, size_t nbytes,
169 std::string* str_p) {
170 CHECK(buf);
171 CHECK(str_p);
172 str_p->append(buf, nbytes);
173}
174
175// Reads from an open file |fp|, appending the read content to the container
176// pointer to by |out_p|. Returns true upon successful reading all of the
177// file's content, false otherwise.
178template <class T>
179static bool Read(FILE* fp, T* out_p) {
180 CHECK(fp);
181 char buf[1024];
182 while (size_t nbytes = fread(buf, 1, sizeof(buf), fp))
183 AppendBytes(buf, nbytes, out_p);
184 return feof(fp) && !ferror(fp);
185}
186
187// Opens a file |path| for reading, then uses |append_func| to append its
188// content to a container |out_p|.
189template <class T>
190static bool ReadFileAndAppend(const std::string& path, T* out_p) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000191 FILE* fp = fopen(path.c_str(), "r");
192 if (!fp)
193 return false;
Gilad Arnold19a45f02012-07-19 12:36:10 -0700194 bool success = Read(fp, out_p);
195 return (success && !fclose(fp));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000196}
197
Gilad Arnold19a45f02012-07-19 12:36:10 -0700198// Invokes a pipe |cmd|, then uses |append_func| to append its stdout to a
199// container |out_p|.
200template <class T>
201static bool ReadPipeAndAppend(const std::string& cmd, T* out_p) {
202 FILE* fp = popen(cmd.c_str(), "r");
203 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000204 return false;
Gilad Arnold19a45f02012-07-19 12:36:10 -0700205 bool success = Read(fp, out_p);
206 return (success && pclose(fp) >= 0);
207}
208
209
210bool ReadFile(const std::string& path, std::vector<char>* out_p) {
211 return ReadFileAndAppend(path, out_p);
212}
213
214bool ReadFile(const std::string& path, std::string* out_p) {
215 return ReadFileAndAppend(path, out_p);
216}
217
218bool ReadPipe(const std::string& cmd, std::vector<char>* out_p) {
219 return ReadPipeAndAppend(cmd, out_p);
220}
221
222bool ReadPipe(const std::string& cmd, std::string* out_p) {
223 return ReadPipeAndAppend(cmd, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000224}
225
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700226off_t FileSize(const string& path) {
227 struct stat stbuf;
228 int rc = stat(path.c_str(), &stbuf);
229 CHECK_EQ(rc, 0);
230 if (rc < 0)
231 return rc;
232 return stbuf.st_size;
233}
234
adlr@google.com3defe6a2009-12-04 20:57:17 +0000235void HexDumpArray(const unsigned char* const arr, const size_t length) {
236 const unsigned char* const char_arr =
237 reinterpret_cast<const unsigned char* const>(arr);
238 LOG(INFO) << "Logging array of length: " << length;
239 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700240 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000241 const unsigned int bytes_remaining = length - i;
242 const unsigned int bytes_per_this_line = min(bytes_per_line,
243 bytes_remaining);
244 char header[100];
245 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
246 TEST_AND_RETURN(r == 13);
247 string line = header;
248 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
249 char buf[20];
250 unsigned char c = char_arr[i + j];
251 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
252 TEST_AND_RETURN(r == 3);
253 line += buf;
254 }
255 LOG(INFO) << line;
256 }
257}
258
259namespace {
260class ScopedDirCloser {
261 public:
262 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
263 ~ScopedDirCloser() {
264 if (dir_ && *dir_) {
265 int r = closedir(*dir_);
266 TEST_AND_RETURN_ERRNO(r == 0);
267 *dir_ = NULL;
268 dir_ = NULL;
269 }
270 }
271 private:
272 DIR** dir_;
273};
274} // namespace {}
275
276bool RecursiveUnlinkDir(const std::string& path) {
277 struct stat stbuf;
278 int r = lstat(path.c_str(), &stbuf);
279 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
280 if ((r < 0) && (errno == ENOENT))
281 // path request is missing. that's fine.
282 return true;
283 if (!S_ISDIR(stbuf.st_mode)) {
284 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700285 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000286 // success or path disappeared before we could unlink.
287 return true;
288 }
289 {
290 // We have a dir, unlink all children, then delete dir
291 DIR *dir = opendir(path.c_str());
292 TEST_AND_RETURN_FALSE_ERRNO(dir);
293 ScopedDirCloser dir_closer(&dir);
294 struct dirent dir_entry;
295 struct dirent *dir_entry_p;
296 int err = 0;
297 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
298 if (dir_entry_p == NULL) {
299 // end of stream reached
300 break;
301 }
302 // Skip . and ..
303 if (!strcmp(dir_entry_p->d_name, ".") ||
304 !strcmp(dir_entry_p->d_name, ".."))
305 continue;
306 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700307 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000308 }
309 TEST_AND_RETURN_FALSE(err == 0);
310 }
311 // unlink dir
312 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
313 return true;
314}
315
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700316string RootDevice(const string& partition_device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700317 FilePath device_path(partition_device);
318 if (device_path.DirName().value() != "/dev") {
319 return "";
320 }
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700321 string::const_iterator it = --partition_device.end();
322 for (; it >= partition_device.begin(); --it) {
323 if (!isdigit(*it))
324 break;
325 }
326 // Some devices contain a p before the partitions. For example:
327 // /dev/mmc0p4 should be shortened to /dev/mmc0.
328 if (*it == 'p')
329 --it;
330 return string(partition_device.begin(), it + 1);
331}
332
333string PartitionNumber(const string& partition_device) {
334 CHECK(!partition_device.empty());
335 string::const_iterator it = --partition_device.end();
336 for (; it >= partition_device.begin(); --it) {
337 if (!isdigit(*it))
338 break;
339 }
340 return string(it + 1, partition_device.end());
341}
342
Darin Petkovf74eb652010-08-04 12:08:38 -0700343string SysfsBlockDevice(const string& device) {
344 FilePath device_path(device);
345 if (device_path.DirName().value() != "/dev") {
346 return "";
347 }
348 return FilePath("/sys/block").Append(device_path.BaseName()).value();
349}
350
351bool IsRemovableDevice(const std::string& device) {
352 string sysfs_block = SysfsBlockDevice(device);
353 string removable;
354 if (sysfs_block.empty() ||
355 !file_util::ReadFileToString(FilePath(sysfs_block).Append("removable"),
356 &removable)) {
357 return false;
358 }
359 TrimWhitespaceASCII(removable, TRIM_ALL, &removable);
360 return removable == "1";
361}
362
adlr@google.com3defe6a2009-12-04 20:57:17 +0000363std::string ErrnoNumberAsString(int err) {
364 char buf[100];
365 buf[0] = '\0';
366 return strerror_r(err, buf, sizeof(buf));
367}
368
369std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
370 string ret;
371 bool last_insert_was_slash = false;
372 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
373 if (*it == '/') {
374 if (last_insert_was_slash)
375 continue;
376 last_insert_was_slash = true;
377 } else {
378 last_insert_was_slash = false;
379 }
380 ret.push_back(*it);
381 }
382 if (strip_trailing_slash && last_insert_was_slash) {
383 string::size_type last_non_slash = ret.find_last_not_of('/');
384 if (last_non_slash != string::npos) {
385 ret.resize(last_non_slash + 1);
386 } else {
387 ret = "";
388 }
389 }
390 return ret;
391}
392
393bool FileExists(const char* path) {
394 struct stat stbuf;
395 return 0 == lstat(path, &stbuf);
396}
397
Darin Petkov30291ed2010-11-12 10:23:06 -0800398bool IsSymlink(const char* path) {
399 struct stat stbuf;
400 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
401}
402
adlr@google.com3defe6a2009-12-04 20:57:17 +0000403std::string TempFilename(string path) {
404 static const string suffix("XXXXXX");
405 CHECK(StringHasSuffix(path, suffix));
406 do {
407 string new_suffix;
408 for (unsigned int i = 0; i < suffix.size(); i++) {
409 int r = rand() % (26 * 2 + 10); // [a-zA-Z0-9]
410 if (r < 26)
411 new_suffix.append(1, 'a' + r);
412 else if (r < (26 * 2))
413 new_suffix.append(1, 'A' + r - 26);
414 else
415 new_suffix.append(1, '0' + r - (26 * 2));
416 }
417 CHECK_EQ(new_suffix.size(), suffix.size());
418 path.resize(path.size() - new_suffix.size());
419 path.append(new_suffix);
420 } while (FileExists(path.c_str()));
421 return path;
422}
423
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700424bool MakeTempFile(const std::string& filename_template,
425 std::string* filename,
426 int* fd) {
427 DCHECK(filename || fd);
428 vector<char> buf(filename_template.size() + 1);
429 memcpy(&buf[0], filename_template.data(), filename_template.size());
430 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700431
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700432 int mkstemp_fd = mkstemp(&buf[0]);
433 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
434 if (filename) {
435 *filename = &buf[0];
436 }
437 if (fd) {
438 *fd = mkstemp_fd;
439 } else {
440 close(mkstemp_fd);
441 }
442 return true;
443}
444
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700445bool MakeTempDirectory(const std::string& dirname_template,
446 std::string* dirname) {
447 DCHECK(dirname);
448 vector<char> buf(dirname_template.size() + 1);
449 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
450 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700451
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700452 char* return_code = mkdtemp(&buf[0]);
453 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
454 *dirname = &buf[0];
455 return true;
456}
457
adlr@google.com3defe6a2009-12-04 20:57:17 +0000458bool StringHasSuffix(const std::string& str, const std::string& suffix) {
459 if (suffix.size() > str.size())
460 return false;
461 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
462}
463
464bool StringHasPrefix(const std::string& str, const std::string& prefix) {
465 if (prefix.size() > str.size())
466 return false;
467 return 0 == str.compare(0, prefix.size(), prefix);
468}
469
Will Drewry8f71da82010-08-30 14:07:11 -0500470const std::string BootDevice() {
471 char boot_path[PATH_MAX];
472 // Resolve the boot device path fully, including dereferencing
473 // through dm-verity.
474 int ret = rootdev(boot_path, sizeof(boot_path), true, false);
475
476 if (ret < 0) {
477 LOG(ERROR) << "rootdev failed to find the root device";
adlr@google.com3defe6a2009-12-04 20:57:17 +0000478 return "";
479 }
Will Drewry8f71da82010-08-30 14:07:11 -0500480 LOG_IF(WARNING, ret > 0) << "rootdev found a device name with no device node";
481
482 // This local variable is used to construct the return string and is not
483 // passed around after use.
484 return boot_path;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000485}
486
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700487const string BootKernelDevice(const std::string& boot_device) {
488 // Currntly this assumes the last digit of the boot device is
489 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
490 // get the kernel device.
491 string ret = boot_device;
492 if (ret.empty())
493 return ret;
494 char last_char = ret[ret.size() - 1];
495 if (last_char == '3' || last_char == '5' || last_char == '7') {
496 ret[ret.size() - 1] = last_char - 1;
497 return ret;
498 }
499 return "";
500}
501
adlr@google.com3defe6a2009-12-04 20:57:17 +0000502bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700503 const string& mountpoint,
504 unsigned long mountflags) {
505 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000506 if (rc < 0) {
507 string msg = ErrnoNumberAsString(errno);
508 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
509 << device << " on " << mountpoint;
510 return false;
511 }
512 return true;
513}
514
515bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700516 for (int num_retries = 0; ; ++num_retries) {
517 if (umount(mountpoint.c_str()) == 0)
518 break;
519
520 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
521 num_retries < kUnmountMaxNumOfRetries);
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800522 g_usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700523 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000524 return true;
525}
526
Darin Petkovd3f8c892010-10-12 21:38:45 -0700527bool GetFilesystemSize(const std::string& device,
528 int* out_block_count,
529 int* out_block_size) {
530 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
531 TEST_AND_RETURN_FALSE(fd >= 0);
532 ScopedFdCloser fd_closer(&fd);
533 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
534}
535
536bool GetFilesystemSizeFromFD(int fd,
537 int* out_block_count,
538 int* out_block_size) {
539 TEST_AND_RETURN_FALSE(fd >= 0);
540
541 // Determine the ext3 filesystem size by directly reading the block count and
542 // block size information from the superblock. See include/linux/ext3_fs.h for
543 // more details on the structure.
544 ssize_t kBufferSize = 16 * sizeof(uint32_t);
545 char buffer[kBufferSize];
546 const int kSuperblockOffset = 1024;
547 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
548 kBufferSize) {
549 PLOG(ERROR) << "Unable to determine file system size:";
550 return false;
551 }
552 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
553 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
554 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
555 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
556 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
557 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
558 block_count = le32toh(block_count);
559 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
560 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
561 magic = le16toh(magic);
562
563 // Sanity check the parameters.
564 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
565 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
566 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
567 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
568 int block_size = 1 << log_block_size;
569 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
570 block_size <= kExt3MaxBlockSize);
571 TEST_AND_RETURN_FALSE(block_count > 0);
572
573 if (out_block_count) {
574 *out_block_count = block_count;
575 }
576 if (out_block_size) {
577 *out_block_size = block_size;
578 }
579 return true;
580}
581
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700582bool GetBootloader(BootLoader* out_bootloader) {
583 // For now, hardcode to syslinux.
584 *out_bootloader = BootLoader_SYSLINUX;
585 return true;
586}
587
Darin Petkova0b9e772011-10-06 05:05:56 -0700588string GetAndFreeGError(GError** error) {
589 if (!*error) {
590 return "Unknown GLib error.";
591 }
592 string message =
593 base::StringPrintf("GError(%d): %s",
594 (*error)->code,
595 (*error)->message ? (*error)->message : "(unknown)");
596 g_error_free(*error);
597 *error = NULL;
598 return message;
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700599}
600
Darin Petkov296889c2010-07-23 16:20:54 -0700601bool Reboot() {
602 vector<string> command;
603 command.push_back("/sbin/shutdown");
604 command.push_back("-r");
605 command.push_back("now");
606 int rc = 0;
Darin Petkov85d02b72011-05-17 13:25:51 -0700607 Subprocess::SynchronousExec(command, &rc, NULL);
Darin Petkov296889c2010-07-23 16:20:54 -0700608 TEST_AND_RETURN_FALSE(rc == 0);
609 return true;
610}
611
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800612namespace {
613// Do the actual trigger. We do it as a main-loop callback to (try to) get a
614// consistent stack trace.
615gboolean TriggerCrashReporterUpload(void* unused) {
616 pid_t pid = fork();
617 CHECK(pid >= 0) << "fork failed"; // fork() failed. Something is very wrong.
618 if (pid == 0) {
619 // We are the child. Crash.
620 abort(); // never returns
621 }
622 // We are the parent. Wait for child to terminate.
623 pid_t result = waitpid(pid, NULL, 0);
624 LOG_IF(ERROR, result < 0) << "waitpid() failed";
625 return FALSE; // Don't call this callback again
626}
627} // namespace {}
628
629void ScheduleCrashReporterUpload() {
630 g_idle_add(&TriggerCrashReporterUpload, NULL);
631}
632
Chris Sosa4f8ee272012-11-30 13:01:54 -0800633bool SetCpuShares(CpuShares shares) {
634 string string_shares = base::IntToString(static_cast<int>(shares));
635 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
636 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
637 if(utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
638 string_shares.size())){
639 return true;
640 } else {
641 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
642 << " using " << cpu_shares_file;
643 return false;
644 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700645}
646
Chris Sosa4f8ee272012-11-30 13:01:54 -0800647int CompareCpuShares(CpuShares shares_lhs,
648 CpuShares shares_rhs) {
649 return static_cast<int>(shares_lhs) - static_cast<int>(shares_rhs);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700650}
651
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700652int FuzzInt(int value, unsigned int range) {
653 int min = value - range / 2;
654 int max = value + range - range / 2;
655 return base::RandInt(min, max);
656}
657
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800658gboolean GlibRunClosure(gpointer data) {
659 google::protobuf::Closure* callback =
660 reinterpret_cast<google::protobuf::Closure*>(data);
661 callback->Run();
662 return FALSE;
663}
664
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700665string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800666 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700667}
668
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800669string FormatTimeDelta(TimeDelta delta) {
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700670 // Canonicalize into days, hours, minutes, seconds and microseconds.
671 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800672 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700673 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800674 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700675 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800676 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700677 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800678 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700679 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800680
681 // Construct and return string.
682 string str;
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700683 if (days)
684 base::StringAppendF(&str, "%ud", days);
685 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800686 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700687 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800688 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700689 base::StringAppendF(&str, "%u", secs);
690 if (usecs) {
691 int width = 6;
692 while ((usecs / 10) * 10 == usecs) {
693 usecs /= 10;
694 width--;
695 }
696 base::StringAppendF(&str, ".%0*u", width, usecs);
697 }
698 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800699 return str;
700}
701
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700702string ToString(const Time utc_time) {
703 Time::Exploded exp_time;
704 utc_time.UTCExplode(&exp_time);
705 return StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
706 exp_time.month,
707 exp_time.day_of_month,
708 exp_time.year,
709 exp_time.hour,
710 exp_time.minute,
711 exp_time.second);
712}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000713
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800714ActionExitCode GetBaseErrorCode(ActionExitCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700715 // Ignore the higher order bits in the code by applying the mask as
716 // we want the enumerations to be in the small contiguous range
Jay Srinivasanedce2832012-10-24 18:57:47 -0700717 // with values less than kActionCodeUmaReportedMax.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800718 ActionExitCode base_code = static_cast<ActionExitCode>(
719 code & kActualCodeMask);
Jay Srinivasanf0572052012-10-23 18:12:56 -0700720
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800721 // Make additional adjustments required for UMA and error classification.
722 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
723 // chromium-os:34369.
724 if (base_code >= kActionCodeOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700725 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800726 // errors into this one bucket for UMA and error classification purposes.
727 base_code = kActionCodeOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700728 }
729
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800730 return base_code;
731}
732
733
734
735void SendErrorCodeToUma(MetricsLibraryInterface* metrics_lib,
736 ActionExitCode code) {
737 string metric = utils::IsNormalBootMode() ? "Installer.NormalErrorCodes" :
738 "Installer.DevModeErrorCodes";
739
740 ActionExitCode reported_code = GetBaseErrorCode(code);
741
Jay Srinivasanedce2832012-10-24 18:57:47 -0700742 LOG(INFO) << "Sending error code " << reported_code
743 << " to UMA metric: " << metric;
744 metrics_lib->SendEnumToUMA(metric, reported_code, kActionCodeUmaReportedMax);
Jay Srinivasanf0572052012-10-23 18:12:56 -0700745}
746
747
adlr@google.com3defe6a2009-12-04 20:57:17 +0000748} // namespace utils
749
750} // namespace chromeos_update_engine