blob: 7f05ffbcfa9e22e664d17bdac21ce7ff167b4ea7 [file] [log] [blame]
adlr@google.com3defe6a2009-12-04 20:57:17 +00001// Copyright (c) 2009 The Chromium Authors. All rights reserved.
2// 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"
6#include <sys/mount.h>
7#include <sys/stat.h>
8#include <sys/types.h>
9#include <dirent.h>
10#include <errno.h>
Andrew de los Reyes970bb282009-12-09 16:34:04 -080011#include <fcntl.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000012#include <stdio.h>
13#include <stdlib.h>
14#include <string.h>
15#include <unistd.h>
16#include <algorithm>
17#include "chromeos/obsolete_logging.h"
Andrew de los Reyes970bb282009-12-09 16:34:04 -080018#include "update_engine/file_writer.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000019
20using std::min;
21using std::string;
22using std::vector;
23
24namespace chromeos_update_engine {
25
26namespace utils {
27
Andrew de los Reyes970bb282009-12-09 16:34:04 -080028bool WriteFile(const char* path, const char* data, int data_len) {
29 DirectFileWriter writer;
30 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
31 O_WRONLY | O_CREAT | O_TRUNC,
32 0666));
33 ScopedFileWriterCloser closer(&writer);
34 TEST_AND_RETURN_FALSE_ERRNO(data_len == writer.Write(data, data_len));
35 return true;
36}
37
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070038bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070039 const char* c_buf = static_cast<const char*>(buf);
40 ssize_t bytes_written = 0;
41 while (bytes_written < static_cast<ssize_t>(count)) {
42 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
43 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
44 bytes_written += rc;
45 }
46 return true;
47}
48
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070049bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
50 const char* c_buf = static_cast<const char*>(buf);
51 ssize_t bytes_written = 0;
52 while (bytes_written < static_cast<ssize_t>(count)) {
53 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
54 offset + bytes_written);
55 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
56 bytes_written += rc;
57 }
58 return true;
59}
60
61bool PReadAll(int fd, void* buf, size_t count, off_t offset,
62 ssize_t* out_bytes_read) {
63 char* c_buf = static_cast<char*>(buf);
64 ssize_t bytes_read = 0;
65 while (bytes_read < static_cast<ssize_t>(count)) {
66 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
67 offset + bytes_read);
68 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
69 if (rc == 0) {
70 break;
71 }
72 bytes_read += rc;
73 }
74 *out_bytes_read = bytes_read;
75 return true;
76
77}
78
adlr@google.com3defe6a2009-12-04 20:57:17 +000079bool ReadFile(const std::string& path, std::vector<char>* out) {
80 CHECK(out);
81 FILE* fp = fopen(path.c_str(), "r");
82 if (!fp)
83 return false;
84 const size_t kChunkSize = 1024;
85 size_t read_size;
86 do {
87 char buf[kChunkSize];
88 read_size = fread(buf, 1, kChunkSize, fp);
89 if (read_size == 0)
90 break;
91 out->insert(out->end(), buf, buf + read_size);
92 } while (read_size == kChunkSize);
93 bool success = !ferror(fp);
94 TEST_AND_RETURN_FALSE_ERRNO(fclose(fp) == 0);
95 return success;
96}
97
98bool ReadFileToString(const std::string& path, std::string* out) {
99 vector<char> data;
100 bool success = ReadFile(path, &data);
101 if (!success) {
102 return false;
103 }
104 (*out) = string(&data[0], data.size());
105 return true;
106}
107
108void HexDumpArray(const unsigned char* const arr, const size_t length) {
109 const unsigned char* const char_arr =
110 reinterpret_cast<const unsigned char* const>(arr);
111 LOG(INFO) << "Logging array of length: " << length;
112 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700113 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000114 const unsigned int bytes_remaining = length - i;
115 const unsigned int bytes_per_this_line = min(bytes_per_line,
116 bytes_remaining);
117 char header[100];
118 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
119 TEST_AND_RETURN(r == 13);
120 string line = header;
121 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
122 char buf[20];
123 unsigned char c = char_arr[i + j];
124 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
125 TEST_AND_RETURN(r == 3);
126 line += buf;
127 }
128 LOG(INFO) << line;
129 }
130}
131
132namespace {
133class ScopedDirCloser {
134 public:
135 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
136 ~ScopedDirCloser() {
137 if (dir_ && *dir_) {
138 int r = closedir(*dir_);
139 TEST_AND_RETURN_ERRNO(r == 0);
140 *dir_ = NULL;
141 dir_ = NULL;
142 }
143 }
144 private:
145 DIR** dir_;
146};
147} // namespace {}
148
149bool RecursiveUnlinkDir(const std::string& path) {
150 struct stat stbuf;
151 int r = lstat(path.c_str(), &stbuf);
152 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
153 if ((r < 0) && (errno == ENOENT))
154 // path request is missing. that's fine.
155 return true;
156 if (!S_ISDIR(stbuf.st_mode)) {
157 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700158 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000159 // success or path disappeared before we could unlink.
160 return true;
161 }
162 {
163 // We have a dir, unlink all children, then delete dir
164 DIR *dir = opendir(path.c_str());
165 TEST_AND_RETURN_FALSE_ERRNO(dir);
166 ScopedDirCloser dir_closer(&dir);
167 struct dirent dir_entry;
168 struct dirent *dir_entry_p;
169 int err = 0;
170 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
171 if (dir_entry_p == NULL) {
172 // end of stream reached
173 break;
174 }
175 // Skip . and ..
176 if (!strcmp(dir_entry_p->d_name, ".") ||
177 !strcmp(dir_entry_p->d_name, ".."))
178 continue;
179 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700180 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000181 }
182 TEST_AND_RETURN_FALSE(err == 0);
183 }
184 // unlink dir
185 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
186 return true;
187}
188
189std::string ErrnoNumberAsString(int err) {
190 char buf[100];
191 buf[0] = '\0';
192 return strerror_r(err, buf, sizeof(buf));
193}
194
195std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
196 string ret;
197 bool last_insert_was_slash = false;
198 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
199 if (*it == '/') {
200 if (last_insert_was_slash)
201 continue;
202 last_insert_was_slash = true;
203 } else {
204 last_insert_was_slash = false;
205 }
206 ret.push_back(*it);
207 }
208 if (strip_trailing_slash && last_insert_was_slash) {
209 string::size_type last_non_slash = ret.find_last_not_of('/');
210 if (last_non_slash != string::npos) {
211 ret.resize(last_non_slash + 1);
212 } else {
213 ret = "";
214 }
215 }
216 return ret;
217}
218
219bool FileExists(const char* path) {
220 struct stat stbuf;
221 return 0 == lstat(path, &stbuf);
222}
223
224std::string TempFilename(string path) {
225 static const string suffix("XXXXXX");
226 CHECK(StringHasSuffix(path, suffix));
227 do {
228 string new_suffix;
229 for (unsigned int i = 0; i < suffix.size(); i++) {
230 int r = rand() % (26 * 2 + 10); // [a-zA-Z0-9]
231 if (r < 26)
232 new_suffix.append(1, 'a' + r);
233 else if (r < (26 * 2))
234 new_suffix.append(1, 'A' + r - 26);
235 else
236 new_suffix.append(1, '0' + r - (26 * 2));
237 }
238 CHECK_EQ(new_suffix.size(), suffix.size());
239 path.resize(path.size() - new_suffix.size());
240 path.append(new_suffix);
241 } while (FileExists(path.c_str()));
242 return path;
243}
244
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700245bool MakeTempFile(const std::string& filename_template,
246 std::string* filename,
247 int* fd) {
248 DCHECK(filename || fd);
249 vector<char> buf(filename_template.size() + 1);
250 memcpy(&buf[0], filename_template.data(), filename_template.size());
251 buf[filename_template.size()] = '\0';
252
253 int mkstemp_fd = mkstemp(&buf[0]);
254 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
255 if (filename) {
256 *filename = &buf[0];
257 }
258 if (fd) {
259 *fd = mkstemp_fd;
260 } else {
261 close(mkstemp_fd);
262 }
263 return true;
264}
265
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700266bool MakeTempDirectory(const std::string& dirname_template,
267 std::string* dirname) {
268 DCHECK(dirname);
269 vector<char> buf(dirname_template.size() + 1);
270 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
271 buf[dirname_template.size()] = '\0';
272
273 char* return_code = mkdtemp(&buf[0]);
274 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
275 *dirname = &buf[0];
276 return true;
277}
278
adlr@google.com3defe6a2009-12-04 20:57:17 +0000279bool StringHasSuffix(const std::string& str, const std::string& suffix) {
280 if (suffix.size() > str.size())
281 return false;
282 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
283}
284
285bool StringHasPrefix(const std::string& str, const std::string& prefix) {
286 if (prefix.size() > str.size())
287 return false;
288 return 0 == str.compare(0, prefix.size(), prefix);
289}
290
291const std::string BootDevice() {
292 string proc_cmdline;
293 if (!ReadFileToString("/proc/cmdline", &proc_cmdline))
294 return "";
295 // look for "root=" in the command line
296 string::size_type pos = 0;
297 if (!StringHasPrefix(proc_cmdline, "root=")) {
298 pos = proc_cmdline.find(" root=") + 1;
299 }
300 if (pos == string::npos) {
301 // can't find root=
302 return "";
303 }
304 // at this point, pos is the point in the string where "root=" starts
305 string ret;
306 pos += strlen("root="); // advance to the device name itself
307 while (pos < proc_cmdline.size()) {
308 char c = proc_cmdline[pos];
309 if (c == ' ')
310 break;
311 ret += c;
312 pos++;
313 }
314 return ret;
315 // TODO(adlr): use findfs to figure out UUID= or LABEL= filesystems
316}
317
318bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700319 const string& mountpoint,
320 unsigned long mountflags) {
321 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000322 if (rc < 0) {
323 string msg = ErrnoNumberAsString(errno);
324 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
325 << device << " on " << mountpoint;
326 return false;
327 }
328 return true;
329}
330
331bool UnmountFilesystem(const string& mountpoint) {
332 TEST_AND_RETURN_FALSE_ERRNO(umount(mountpoint.c_str()) == 0);
333 return true;
334}
335
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800336const char* const kStatefulPartition = "/mnt/stateful_partition";
adlr@google.com3defe6a2009-12-04 20:57:17 +0000337
338} // namespace utils
339
340} // namespace chromeos_update_engine
341