blob: 134ad80a116d17713a92f39cf090414859382854 [file] [log] [blame]
Darin Petkov296889c2010-07-23 16:20:54 -07001// Copyright (c) 2009 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>
11#include <dirent.h>
12#include <errno.h>
Andrew de los Reyes970bb282009-12-09 16:34:04 -080013#include <fcntl.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000014#include <stdio.h>
15#include <stdlib.h>
16#include <string.h>
17#include <unistd.h>
Darin Petkovf74eb652010-08-04 12:08:38 -070018
adlr@google.com3defe6a2009-12-04 20:57:17 +000019#include <algorithm>
Darin Petkovf74eb652010-08-04 12:08:38 -070020
21#include "base/file_path.h"
22#include "base/file_util.h"
23#include "base/string_util.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000024#include "chromeos/obsolete_logging.h"
Andrew de los Reyes970bb282009-12-09 16:34:04 -080025#include "update_engine/file_writer.h"
Darin Petkov33d30642010-08-04 10:18:57 -070026#include "update_engine/omaha_request_params.h"
Darin Petkov296889c2010-07-23 16:20:54 -070027#include "update_engine/subprocess.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000028
29using std::min;
30using std::string;
31using std::vector;
32
33namespace chromeos_update_engine {
34
35namespace utils {
36
Darin Petkov33d30642010-08-04 10:18:57 -070037bool IsOfficialBuild() {
38 OmahaRequestDeviceParams params;
39 if (!params.Init("", "")) {
40 return true;
41 }
42 return params.app_track != "buildbot-build" &&
43 params.app_track != "developer-build";
44}
45
Andrew de los Reyes970bb282009-12-09 16:34:04 -080046bool WriteFile(const char* path, const char* data, int data_len) {
47 DirectFileWriter writer;
48 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
49 O_WRONLY | O_CREAT | O_TRUNC,
50 0666));
51 ScopedFileWriterCloser closer(&writer);
52 TEST_AND_RETURN_FALSE_ERRNO(data_len == writer.Write(data, data_len));
53 return true;
54}
55
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070056bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070057 const char* c_buf = static_cast<const char*>(buf);
58 ssize_t bytes_written = 0;
59 while (bytes_written < static_cast<ssize_t>(count)) {
60 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
61 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
62 bytes_written += rc;
63 }
64 return true;
65}
66
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070067bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
68 const char* c_buf = static_cast<const char*>(buf);
69 ssize_t bytes_written = 0;
70 while (bytes_written < static_cast<ssize_t>(count)) {
71 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
72 offset + bytes_written);
73 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
74 bytes_written += rc;
75 }
76 return true;
77}
78
79bool PReadAll(int fd, void* buf, size_t count, off_t offset,
80 ssize_t* out_bytes_read) {
81 char* c_buf = static_cast<char*>(buf);
82 ssize_t bytes_read = 0;
83 while (bytes_read < static_cast<ssize_t>(count)) {
84 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
85 offset + bytes_read);
86 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
87 if (rc == 0) {
88 break;
89 }
90 bytes_read += rc;
91 }
92 *out_bytes_read = bytes_read;
93 return true;
Darin Petkov296889c2010-07-23 16:20:54 -070094
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070095}
96
adlr@google.com3defe6a2009-12-04 20:57:17 +000097bool ReadFile(const std::string& path, std::vector<char>* out) {
98 CHECK(out);
99 FILE* fp = fopen(path.c_str(), "r");
100 if (!fp)
101 return false;
102 const size_t kChunkSize = 1024;
103 size_t read_size;
104 do {
105 char buf[kChunkSize];
106 read_size = fread(buf, 1, kChunkSize, fp);
107 if (read_size == 0)
108 break;
109 out->insert(out->end(), buf, buf + read_size);
110 } while (read_size == kChunkSize);
111 bool success = !ferror(fp);
112 TEST_AND_RETURN_FALSE_ERRNO(fclose(fp) == 0);
113 return success;
114}
115
116bool ReadFileToString(const std::string& path, std::string* out) {
117 vector<char> data;
118 bool success = ReadFile(path, &data);
119 if (!success) {
120 return false;
121 }
122 (*out) = string(&data[0], data.size());
123 return true;
124}
125
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700126off_t FileSize(const string& path) {
127 struct stat stbuf;
128 int rc = stat(path.c_str(), &stbuf);
129 CHECK_EQ(rc, 0);
130 if (rc < 0)
131 return rc;
132 return stbuf.st_size;
133}
134
adlr@google.com3defe6a2009-12-04 20:57:17 +0000135void HexDumpArray(const unsigned char* const arr, const size_t length) {
136 const unsigned char* const char_arr =
137 reinterpret_cast<const unsigned char* const>(arr);
138 LOG(INFO) << "Logging array of length: " << length;
139 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700140 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000141 const unsigned int bytes_remaining = length - i;
142 const unsigned int bytes_per_this_line = min(bytes_per_line,
143 bytes_remaining);
144 char header[100];
145 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
146 TEST_AND_RETURN(r == 13);
147 string line = header;
148 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
149 char buf[20];
150 unsigned char c = char_arr[i + j];
151 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
152 TEST_AND_RETURN(r == 3);
153 line += buf;
154 }
155 LOG(INFO) << line;
156 }
157}
158
159namespace {
160class ScopedDirCloser {
161 public:
162 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
163 ~ScopedDirCloser() {
164 if (dir_ && *dir_) {
165 int r = closedir(*dir_);
166 TEST_AND_RETURN_ERRNO(r == 0);
167 *dir_ = NULL;
168 dir_ = NULL;
169 }
170 }
171 private:
172 DIR** dir_;
173};
174} // namespace {}
175
176bool RecursiveUnlinkDir(const std::string& path) {
177 struct stat stbuf;
178 int r = lstat(path.c_str(), &stbuf);
179 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
180 if ((r < 0) && (errno == ENOENT))
181 // path request is missing. that's fine.
182 return true;
183 if (!S_ISDIR(stbuf.st_mode)) {
184 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700185 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000186 // success or path disappeared before we could unlink.
187 return true;
188 }
189 {
190 // We have a dir, unlink all children, then delete dir
191 DIR *dir = opendir(path.c_str());
192 TEST_AND_RETURN_FALSE_ERRNO(dir);
193 ScopedDirCloser dir_closer(&dir);
194 struct dirent dir_entry;
195 struct dirent *dir_entry_p;
196 int err = 0;
197 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
198 if (dir_entry_p == NULL) {
199 // end of stream reached
200 break;
201 }
202 // Skip . and ..
203 if (!strcmp(dir_entry_p->d_name, ".") ||
204 !strcmp(dir_entry_p->d_name, ".."))
205 continue;
206 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700207 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000208 }
209 TEST_AND_RETURN_FALSE(err == 0);
210 }
211 // unlink dir
212 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
213 return true;
214}
215
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700216string RootDevice(const string& partition_device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700217 FilePath device_path(partition_device);
218 if (device_path.DirName().value() != "/dev") {
219 return "";
220 }
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700221 string::const_iterator it = --partition_device.end();
222 for (; it >= partition_device.begin(); --it) {
223 if (!isdigit(*it))
224 break;
225 }
226 // Some devices contain a p before the partitions. For example:
227 // /dev/mmc0p4 should be shortened to /dev/mmc0.
228 if (*it == 'p')
229 --it;
230 return string(partition_device.begin(), it + 1);
231}
232
233string PartitionNumber(const string& partition_device) {
234 CHECK(!partition_device.empty());
235 string::const_iterator it = --partition_device.end();
236 for (; it >= partition_device.begin(); --it) {
237 if (!isdigit(*it))
238 break;
239 }
240 return string(it + 1, partition_device.end());
241}
242
Darin Petkovf74eb652010-08-04 12:08:38 -0700243string SysfsBlockDevice(const string& device) {
244 FilePath device_path(device);
245 if (device_path.DirName().value() != "/dev") {
246 return "";
247 }
248 return FilePath("/sys/block").Append(device_path.BaseName()).value();
249}
250
251bool IsRemovableDevice(const std::string& device) {
252 string sysfs_block = SysfsBlockDevice(device);
253 string removable;
254 if (sysfs_block.empty() ||
255 !file_util::ReadFileToString(FilePath(sysfs_block).Append("removable"),
256 &removable)) {
257 return false;
258 }
259 TrimWhitespaceASCII(removable, TRIM_ALL, &removable);
260 return removable == "1";
261}
262
adlr@google.com3defe6a2009-12-04 20:57:17 +0000263std::string ErrnoNumberAsString(int err) {
264 char buf[100];
265 buf[0] = '\0';
266 return strerror_r(err, buf, sizeof(buf));
267}
268
269std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
270 string ret;
271 bool last_insert_was_slash = false;
272 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
273 if (*it == '/') {
274 if (last_insert_was_slash)
275 continue;
276 last_insert_was_slash = true;
277 } else {
278 last_insert_was_slash = false;
279 }
280 ret.push_back(*it);
281 }
282 if (strip_trailing_slash && last_insert_was_slash) {
283 string::size_type last_non_slash = ret.find_last_not_of('/');
284 if (last_non_slash != string::npos) {
285 ret.resize(last_non_slash + 1);
286 } else {
287 ret = "";
288 }
289 }
290 return ret;
291}
292
293bool FileExists(const char* path) {
294 struct stat stbuf;
295 return 0 == lstat(path, &stbuf);
296}
297
298std::string TempFilename(string path) {
299 static const string suffix("XXXXXX");
300 CHECK(StringHasSuffix(path, suffix));
301 do {
302 string new_suffix;
303 for (unsigned int i = 0; i < suffix.size(); i++) {
304 int r = rand() % (26 * 2 + 10); // [a-zA-Z0-9]
305 if (r < 26)
306 new_suffix.append(1, 'a' + r);
307 else if (r < (26 * 2))
308 new_suffix.append(1, 'A' + r - 26);
309 else
310 new_suffix.append(1, '0' + r - (26 * 2));
311 }
312 CHECK_EQ(new_suffix.size(), suffix.size());
313 path.resize(path.size() - new_suffix.size());
314 path.append(new_suffix);
315 } while (FileExists(path.c_str()));
316 return path;
317}
318
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700319bool MakeTempFile(const std::string& filename_template,
320 std::string* filename,
321 int* fd) {
322 DCHECK(filename || fd);
323 vector<char> buf(filename_template.size() + 1);
324 memcpy(&buf[0], filename_template.data(), filename_template.size());
325 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700326
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700327 int mkstemp_fd = mkstemp(&buf[0]);
328 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
329 if (filename) {
330 *filename = &buf[0];
331 }
332 if (fd) {
333 *fd = mkstemp_fd;
334 } else {
335 close(mkstemp_fd);
336 }
337 return true;
338}
339
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700340bool MakeTempDirectory(const std::string& dirname_template,
341 std::string* dirname) {
342 DCHECK(dirname);
343 vector<char> buf(dirname_template.size() + 1);
344 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
345 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700346
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700347 char* return_code = mkdtemp(&buf[0]);
348 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
349 *dirname = &buf[0];
350 return true;
351}
352
adlr@google.com3defe6a2009-12-04 20:57:17 +0000353bool StringHasSuffix(const std::string& str, const std::string& suffix) {
354 if (suffix.size() > str.size())
355 return false;
356 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
357}
358
359bool StringHasPrefix(const std::string& str, const std::string& prefix) {
360 if (prefix.size() > str.size())
361 return false;
362 return 0 == str.compare(0, prefix.size(), prefix);
363}
364
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700365const string BootDevice() {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000366 string proc_cmdline;
367 if (!ReadFileToString("/proc/cmdline", &proc_cmdline))
368 return "";
369 // look for "root=" in the command line
370 string::size_type pos = 0;
371 if (!StringHasPrefix(proc_cmdline, "root=")) {
372 pos = proc_cmdline.find(" root=") + 1;
373 }
374 if (pos == string::npos) {
375 // can't find root=
376 return "";
377 }
378 // at this point, pos is the point in the string where "root=" starts
379 string ret;
380 pos += strlen("root="); // advance to the device name itself
381 while (pos < proc_cmdline.size()) {
382 char c = proc_cmdline[pos];
383 if (c == ' ')
384 break;
385 ret += c;
386 pos++;
387 }
388 return ret;
389 // TODO(adlr): use findfs to figure out UUID= or LABEL= filesystems
390}
391
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700392const string BootKernelDevice(const std::string& boot_device) {
393 // Currntly this assumes the last digit of the boot device is
394 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
395 // get the kernel device.
396 string ret = boot_device;
397 if (ret.empty())
398 return ret;
399 char last_char = ret[ret.size() - 1];
400 if (last_char == '3' || last_char == '5' || last_char == '7') {
401 ret[ret.size() - 1] = last_char - 1;
402 return ret;
403 }
404 return "";
405}
406
adlr@google.com3defe6a2009-12-04 20:57:17 +0000407bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700408 const string& mountpoint,
409 unsigned long mountflags) {
410 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000411 if (rc < 0) {
412 string msg = ErrnoNumberAsString(errno);
413 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
414 << device << " on " << mountpoint;
415 return false;
416 }
417 return true;
418}
419
420bool UnmountFilesystem(const string& mountpoint) {
421 TEST_AND_RETURN_FALSE_ERRNO(umount(mountpoint.c_str()) == 0);
422 return true;
423}
424
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700425bool GetBootloader(BootLoader* out_bootloader) {
426 // For now, hardcode to syslinux.
427 *out_bootloader = BootLoader_SYSLINUX;
428 return true;
429}
430
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700431const char* GetGErrorMessage(const GError* error) {
432 if (!error)
433 return "Unknown error.";
434 return error->message;
435}
436
Darin Petkov296889c2010-07-23 16:20:54 -0700437bool Reboot() {
438 vector<string> command;
439 command.push_back("/sbin/shutdown");
440 command.push_back("-r");
441 command.push_back("now");
442 int rc = 0;
443 Subprocess::SynchronousExec(command, &rc);
444 TEST_AND_RETURN_FALSE(rc == 0);
445 return true;
446}
447
Darin Petkovc6c135c2010-08-11 13:36:18 -0700448bool SetProcessPriority(ProcessPriority priority) {
449 int prio = static_cast<int>(priority);
450 LOG(INFO) << "Setting process priority to " << prio;
451 TEST_AND_RETURN_FALSE(setpriority(PRIO_PROCESS, 0, prio) == 0);
452 return true;
453}
454
455int ComparePriorities(ProcessPriority priority_lhs,
456 ProcessPriority priority_rhs) {
457 return static_cast<int>(priority_rhs) - static_cast<int>(priority_lhs);
458}
459
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800460const char* const kStatefulPartition = "/mnt/stateful_partition";
adlr@google.com3defe6a2009-12-04 20:57:17 +0000461
462} // namespace utils
463
464} // namespace chromeos_update_engine