1 /*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "common/libs/utils/files.h"
18
19 #ifdef __linux__
20 #include <linux/fiemap.h>
21 #include <linux/fs.h>
22 #include <sys/inotify.h>
23 #include <sys/sendfile.h>
24 #endif
25
26 #include <dirent.h>
27 #include <fcntl.h>
28 #include <ftw.h>
29 #include <libgen.h>
30 #include <sched.h>
31 #include <sys/ioctl.h>
32 #include <sys/select.h>
33 #include <sys/socket.h>
34 #include <sys/stat.h>
35 #include <sys/types.h>
36 #include <sys/uio.h>
37 #include <unistd.h>
38
39 #include <algorithm>
40 #include <array>
41 #include <cerrno>
42 #include <chrono>
43 #include <climits>
44 #include <cstdio>
45 #include <cstdlib>
46 #include <cstring>
47 #include <fstream>
48 #include <ios>
49 #include <iosfwd>
50 #include <istream>
51 #include <memory>
52 #include <numeric>
53 #include <ostream>
54 #include <ratio>
55 #include <regex>
56 #include <string>
57 #include <vector>
58
59 #include <android-base/file.h>
60 #include <android-base/logging.h>
61 #include <android-base/macros.h>
62 #include <android-base/strings.h>
63 #include <android-base/unique_fd.h>
64
65 #include "common/libs/fs/shared_buf.h"
66 #include "common/libs/fs/shared_fd.h"
67 #include "common/libs/utils/contains.h"
68 #include "common/libs/utils/in_sandbox.h"
69 #include "common/libs/utils/inotify.h"
70 #include "common/libs/utils/result.h"
71 #include "common/libs/utils/subprocess.h"
72 #include "common/libs/utils/users.h"
73
74 #ifdef __APPLE__
75 #define off64_t off_t
76 #define ftruncate64 ftruncate
77 #endif
78
79 namespace cuttlefish {
80
FileExists(const std::string & path,bool follow_symlinks)81 bool FileExists(const std::string& path, bool follow_symlinks) {
82 struct stat st {};
83 return (follow_symlinks ? stat : lstat)(path.c_str(), &st) == 0;
84 }
85
FileDeviceId(const std::string & path)86 Result<dev_t> FileDeviceId(const std::string& path) {
87 struct stat out;
88 CF_EXPECTF(
89 stat(path.c_str(), &out) == 0,
90 "stat() failed trying to retrieve device ID information for \"{}\" "
91 "with error: {}",
92 path, strerror(errno));
93 return out.st_dev;
94 }
95
CanHardLink(const std::string & source,const std::string & destination)96 Result<bool> CanHardLink(const std::string& source,
97 const std::string& destination) {
98 return CF_EXPECT(FileDeviceId(source)) ==
99 CF_EXPECT(FileDeviceId(destination));
100 }
101
FileInodeNumber(const std::string & path)102 Result<ino_t> FileInodeNumber(const std::string& path) {
103 struct stat out;
104 CF_EXPECTF(
105 stat(path.c_str(), &out) == 0,
106 "stat() failed trying to retrieve inode num information for \"{}\" "
107 "with error: {}",
108 path, strerror(errno));
109 return out.st_ino;
110 }
111
AreHardLinked(const std::string & source,const std::string & destination)112 Result<bool> AreHardLinked(const std::string& source,
113 const std::string& destination) {
114 return (CF_EXPECT(FileDeviceId(source)) ==
115 CF_EXPECT(FileDeviceId(destination))) &&
116 (CF_EXPECT(FileInodeNumber(source)) ==
117 CF_EXPECT(FileInodeNumber(destination)));
118 }
119
CreateHardLink(const std::string & target,const std::string & hardlink,const bool overwrite_existing)120 Result<std::string> CreateHardLink(const std::string& target,
121 const std::string& hardlink,
122 const bool overwrite_existing) {
123 if (FileExists(hardlink)) {
124 if (CF_EXPECT(AreHardLinked(target, hardlink))) {
125 return hardlink;
126 }
127 if (!overwrite_existing) {
128 return CF_ERRF(
129 "Cannot hardlink from \"{}\" to \"{}\", the second file already "
130 "exists and is not hardlinked to the first",
131 target, hardlink);
132 }
133 LOG(WARNING) << "Overwriting existing file \"" << hardlink << "\" with \""
134 << target << "\" from the cache";
135 CF_EXPECTF(unlink(hardlink.c_str()) == 0,
136 "Failed to unlink \"{}\" with error: {}", hardlink,
137 strerror(errno));
138 }
139 CF_EXPECTF(link(target.c_str(), hardlink.c_str()) == 0,
140 "link() failed trying to create hardlink from \"{}\" to \"{}\" "
141 "with error: {}",
142 target, hardlink, strerror(errno));
143 return hardlink;
144 }
145
FileHasContent(const std::string & path)146 bool FileHasContent(const std::string& path) {
147 return FileSize(path) > 0;
148 }
149
DirectoryContents(const std::string & path)150 Result<std::vector<std::string>> DirectoryContents(const std::string& path) {
151 std::vector<std::string> ret;
152 std::unique_ptr<DIR, int(*)(DIR*)> dir(opendir(path.c_str()), closedir);
153 CF_EXPECTF(dir != nullptr, "Could not read from dir \"{}\"", path);
154 struct dirent* ent{};
155 while ((ent = readdir(dir.get()))) {
156 if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) {
157 continue;
158 }
159 ret.emplace_back(ent->d_name);
160 }
161 return ret;
162 }
163
DirectoryExists(const std::string & path,bool follow_symlinks)164 bool DirectoryExists(const std::string& path, bool follow_symlinks) {
165 struct stat st {};
166 if ((follow_symlinks ? stat : lstat)(path.c_str(), &st) == -1) {
167 return false;
168 }
169 if ((st.st_mode & S_IFMT) != S_IFDIR) {
170 return false;
171 }
172 return true;
173 }
174
EnsureDirectoryExists(const std::string & directory_path,const mode_t mode,const std::string & group_name)175 Result<void> EnsureDirectoryExists(const std::string& directory_path,
176 const mode_t mode,
177 const std::string& group_name) {
178 if (DirectoryExists(directory_path, /* follow_symlinks */ true)) {
179 return {};
180 }
181 if (FileExists(directory_path, false) && !FileExists(directory_path, true)) {
182 // directory_path is a link to a path that doesn't exist. This could happen
183 // after executing certain cvd subcommands.
184 CF_EXPECT(RemoveFile(directory_path),
185 "Can't remove broken link: " << directory_path);
186 }
187 const auto parent_dir = android::base::Dirname(directory_path);
188 if (parent_dir.size() > 1) {
189 CF_EXPECT(EnsureDirectoryExists(parent_dir, mode, group_name));
190 }
191 LOG(VERBOSE) << "Setting up " << directory_path;
192 if (mkdir(directory_path.c_str(), mode) < 0 && errno != EEXIST) {
193 return CF_ERRNO("Failed to create directory: \"" << directory_path << "\""
194 << strerror(errno));
195 }
196 // TODO(schuffelen): Find an alternative for host-sandboxing mode
197 if (InSandbox()) {
198 return {};
199 }
200
201 CF_EXPECTF(chmod(directory_path.c_str(), mode) == 0,
202 "Failed to set permission on {}: {}", directory_path,
203 strerror(errno));
204
205 if (group_name != "") {
206 CF_EXPECT(ChangeGroup(directory_path, group_name));
207 }
208
209 return {};
210 }
211
ChangeGroup(const std::string & path,const std::string & group_name)212 Result<void> ChangeGroup(const std::string& path,
213 const std::string& group_name) {
214 auto groupId = GroupIdFromName(group_name);
215
216 if (groupId == -1) {
217 return CF_ERR("Failed to get group id: ") << group_name;
218 }
219
220 if (chown(path.c_str(), -1, groupId) != 0) {
221 return CF_ERRNO("Failed to set group for path: "
222 << path << ", " << group_name << ", " << strerror(errno));
223 }
224
225 return {};
226 }
227
CanAccess(const std::string & path,const int mode)228 bool CanAccess(const std::string& path, const int mode) {
229 return access(path.c_str(), mode) == 0;
230 }
231
IsDirectoryEmpty(const std::string & path)232 bool IsDirectoryEmpty(const std::string& path) {
233 auto direc = ::opendir(path.c_str());
234 if (!direc) {
235 LOG(ERROR) << "IsDirectoryEmpty test failed with " << path
236 << " as it failed to be open" << std::endl;
237 return false;
238 }
239
240 decltype(::readdir(direc)) sub = nullptr;
241 int cnt {0};
242 while ( (sub = ::readdir(direc)) ) {
243 cnt++;
244 if (cnt > 2) {
245 LOG(ERROR) << "IsDirectoryEmpty test failed with " << path
246 << " as it exists but not empty" << std::endl;
247 return false;
248 }
249 }
250 return true;
251 }
252
RecursivelyRemoveDirectory(const std::string & path)253 Result<void> RecursivelyRemoveDirectory(const std::string& path) {
254 // Copied from libbase TemporaryDir destructor.
255 auto callback = [](const char* child, const struct stat*, int file_type,
256 struct FTW*) -> int {
257 switch (file_type) {
258 case FTW_D:
259 case FTW_DP:
260 case FTW_DNR:
261 if (rmdir(child) == -1) {
262 PLOG(ERROR) << "rmdir " << child;
263 return -1;
264 }
265 break;
266 case FTW_NS:
267 default:
268 if (rmdir(child) != -1) {
269 break;
270 }
271 // FALLTHRU (for gcc, lint, pcc, etc; and following for clang)
272 FALLTHROUGH_INTENDED;
273 case FTW_F:
274 case FTW_SL:
275 case FTW_SLN:
276 if (unlink(child) == -1) {
277 PLOG(ERROR) << "unlink " << child;
278 return -1;
279 }
280 break;
281 }
282 return 0;
283 };
284
285 if (nftw(path.c_str(), callback, 128, FTW_DEPTH | FTW_MOUNT | FTW_PHYS) < 0) {
286 return CF_ERRNO("Failed to remove directory \""
287 << path << "\": " << strerror(errno));
288 }
289 return {};
290 }
291
292 namespace {
293
SendFile(int out_fd,int in_fd,off64_t * offset,size_t count)294 bool SendFile(int out_fd, int in_fd, off64_t* offset, size_t count) {
295 while (count > 0) {
296 #ifdef __linux__
297 const auto bytes_written =
298 TEMP_FAILURE_RETRY(sendfile(out_fd, in_fd, offset, count));
299 if (bytes_written <= 0) {
300 return false;
301 }
302 #elif defined(__APPLE__)
303 off_t bytes_written = count;
304 auto success = TEMP_FAILURE_RETRY(
305 sendfile(in_fd, out_fd, *offset, &bytes_written, nullptr, 0));
306 *offset += bytes_written;
307 if (success < 0 || bytes_written == 0) {
308 return false;
309 }
310 #endif
311 count -= bytes_written;
312 }
313 return true;
314 }
315
316 } // namespace
317
Copy(const std::string & from,const std::string & to)318 bool Copy(const std::string& from, const std::string& to) {
319 android::base::unique_fd fd_from(
320 open(from.c_str(), O_RDONLY | O_CLOEXEC));
321 android::base::unique_fd fd_to(
322 open(to.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644));
323
324 if (fd_from.get() < 0 || fd_to.get() < 0) {
325 return false;
326 }
327
328 off_t farthest_seek = lseek(fd_from.get(), 0, SEEK_END);
329 if (farthest_seek == -1) {
330 PLOG(ERROR) << "Could not lseek in \"" << from << "\"";
331 return false;
332 }
333 if (ftruncate64(fd_to.get(), farthest_seek) < 0) {
334 PLOG(ERROR) << "Failed to ftruncate " << to;
335 }
336 off_t offset = 0;
337 while (offset < farthest_seek) {
338 off_t new_offset = lseek(fd_from.get(), offset, SEEK_HOLE);
339 if (new_offset == -1) {
340 // ENXIO is returned when there are no more blocks of this type
341 // coming.
342 if (errno == ENXIO) {
343 return true;
344 }
345 PLOG(ERROR) << "Could not lseek in \"" << from << "\"";
346 return false;
347 }
348 auto data_bytes = new_offset - offset;
349 if (lseek(fd_to.get(), offset, SEEK_SET) < 0) {
350 PLOG(ERROR) << "lseek() on " << to << " failed";
351 return false;
352 }
353 if (!SendFile(fd_to.get(), fd_from.get(), &offset, data_bytes)) {
354 PLOG(ERROR) << "sendfile() failed";
355 return false;
356 }
357 CHECK_EQ(offset, new_offset);
358 if (offset >= farthest_seek) {
359 return true;
360 }
361 new_offset = lseek(fd_from.get(), offset, SEEK_DATA);
362 if (new_offset == -1) {
363 // ENXIO is returned when there are no more blocks of this type
364 // coming.
365 if (errno == ENXIO) {
366 return true;
367 }
368 PLOG(ERROR) << "Could not lseek in \"" << from << "\"";
369 return false;
370 }
371 offset = new_offset;
372 }
373 return true;
374 }
375
AbsolutePath(const std::string & path)376 std::string AbsolutePath(const std::string& path) {
377 if (path.empty()) {
378 return {};
379 }
380 if (path[0] == '/') {
381 return path;
382 }
383 if (path[0] == '~') {
384 LOG(WARNING) << "Tilde expansion in path " << path <<" is not supported";
385 return {};
386 }
387
388 std::array<char, PATH_MAX> buffer{};
389 if (!realpath(".", buffer.data())) {
390 LOG(WARNING) << "Could not get real path for current directory \".\""
391 << ": " << strerror(errno);
392 return {};
393 }
394 return std::string{buffer.data()} + "/" + path;
395 }
396
FileSize(const std::string & path)397 off_t FileSize(const std::string& path) {
398 struct stat st {};
399 if (stat(path.c_str(), &st) == -1) {
400 return 0;
401 }
402 return st.st_size;
403 }
404
MakeFileExecutable(const std::string & path)405 bool MakeFileExecutable(const std::string& path) {
406 LOG(DEBUG) << "Making " << path << " executable";
407 return chmod(path.c_str(), S_IRWXU) == 0;
408 }
409
410 // TODO(schuffelen): Use std::filesystem::last_write_time when on C++17
FileModificationTime(const std::string & path)411 std::chrono::system_clock::time_point FileModificationTime(const std::string& path) {
412 struct stat st {};
413 if (stat(path.c_str(), &st) == -1) {
414 return std::chrono::system_clock::time_point();
415 }
416 #ifdef __linux__
417 std::chrono::seconds seconds(st.st_mtim.tv_sec);
418 #elif defined(__APPLE__)
419 std::chrono::seconds seconds(st.st_mtimespec.tv_sec);
420 #else
421 #error "Unsupported operating system"
422 #endif
423 return std::chrono::system_clock::time_point(seconds);
424 }
425
RenameFile(const std::string & current_filepath,const std::string & target_filepath)426 Result<std::string> RenameFile(const std::string& current_filepath,
427 const std::string& target_filepath) {
428 if (current_filepath != target_filepath) {
429 CF_EXPECT(rename(current_filepath.c_str(), target_filepath.c_str()) == 0,
430 "rename " << current_filepath << " to " << target_filepath
431 << " failed: " << strerror(errno));
432 }
433 return target_filepath;
434 }
435
RemoveFile(const std::string & file)436 bool RemoveFile(const std::string& file) {
437 LOG(DEBUG) << "Removing file " << file;
438 if (remove(file.c_str()) == 0) {
439 return true;
440 }
441 LOG(ERROR) << "Failed to remove file " << file << " : "
442 << std::strerror(errno);
443 return false;
444 }
445
ReadFile(const std::string & file)446 std::string ReadFile(const std::string& file) {
447 std::string contents;
448 std::ifstream in(file, std::ios::in | std::ios::binary);
449 in.seekg(0, std::ios::end);
450 if (in.fail()) {
451 // TODO(schuffelen): Return a failing Result instead
452 return "";
453 }
454 if (in.tellg() == std::ifstream::pos_type(-1)) {
455 PLOG(ERROR) << "Failed to seek on " << file;
456 return "";
457 }
458 contents.resize(in.tellg());
459 in.seekg(0, std::ios::beg);
460 in.read(&contents[0], contents.size());
461 in.close();
462 return(contents);
463 }
464
ReadFileContents(const std::string & filepath)465 Result<std::string> ReadFileContents(const std::string& filepath) {
466 CF_EXPECTF(FileExists(filepath), "The file at \"{}\" does not exist.",
467 filepath);
468 auto file = SharedFD::Open(filepath, O_RDONLY);
469 CF_EXPECTF(file->IsOpen(), "Failed to open file \"{}\". Error:\n", filepath,
470 file->StrError());
471 std::string file_content;
472 auto size = ReadAll(file, &file_content);
473 CF_EXPECTF(size >= 0, "Failed to read file contents. Error:\n",
474 file->StrError());
475 return file_content;
476 }
477
CurrentDirectory()478 std::string CurrentDirectory() {
479 std::vector<char> process_wd(1 << 12, ' ');
480 while (getcwd(process_wd.data(), process_wd.size()) == nullptr) {
481 if (errno == ERANGE) {
482 process_wd.resize(process_wd.size() * 2, ' ');
483 } else {
484 PLOG(ERROR) << "getcwd failed";
485 return "";
486 }
487 }
488 // Will find the null terminator and size the string appropriately.
489 return std::string(process_wd.data());
490 }
491
SparseFileSizes(const std::string & path)492 FileSizes SparseFileSizes(const std::string& path) {
493 auto fd = SharedFD::Open(path, O_RDONLY);
494 if (!fd->IsOpen()) {
495 LOG(ERROR) << "Could not open \"" << path << "\": " << fd->StrError();
496 return {};
497 }
498 off_t farthest_seek = fd->LSeek(0, SEEK_END);
499 LOG(VERBOSE) << "Farthest seek: " << farthest_seek;
500 if (farthest_seek == -1) {
501 LOG(ERROR) << "Could not lseek in \"" << path << "\": " << fd->StrError();
502 return {};
503 }
504 off_t data_bytes = 0;
505 off_t offset = 0;
506 while (offset < farthest_seek) {
507 off_t new_offset = fd->LSeek(offset, SEEK_HOLE);
508 if (new_offset == -1) {
509 // ENXIO is returned when there are no more blocks of this type coming.
510 if (fd->GetErrno() == ENXIO) {
511 break;
512 } else {
513 LOG(ERROR) << "Could not lseek in \"" << path << "\": " << fd->StrError();
514 return {};
515 }
516 } else {
517 data_bytes += new_offset - offset;
518 offset = new_offset;
519 }
520 if (offset >= farthest_seek) {
521 break;
522 }
523 new_offset = fd->LSeek(offset, SEEK_DATA);
524 if (new_offset == -1) {
525 // ENXIO is returned when there are no more blocks of this type coming.
526 if (fd->GetErrno() == ENXIO) {
527 break;
528 } else {
529 LOG(ERROR) << "Could not lseek in \"" << path << "\": " << fd->StrError();
530 return {};
531 }
532 } else {
533 offset = new_offset;
534 }
535 }
536 return (FileSizes) { .sparse_size = farthest_seek, .disk_size = data_bytes };
537 }
538
FileIsSocket(const std::string & path)539 bool FileIsSocket(const std::string& path) {
540 struct stat st {};
541 return stat(path.c_str(), &st) == 0 && S_ISSOCK(st.st_mode);
542 }
543
GetDiskUsage(const std::string & path)544 int GetDiskUsage(const std::string& path) {
545 Command du_cmd("du");
546 du_cmd.AddParameter("-b");
547 du_cmd.AddParameter("-k");
548 du_cmd.AddParameter("-s");
549 du_cmd.AddParameter(path);
550 SharedFD read_fd;
551 SharedFD write_fd;
552 SharedFD::Pipe(&read_fd, &write_fd);
553 du_cmd.RedirectStdIO(Subprocess::StdIOChannel::kStdOut, write_fd);
554 auto subprocess = du_cmd.Start();
555 std::array<char, 1024> text_output{};
556 const auto bytes_read = read_fd->Read(text_output.data(), text_output.size());
557 CHECK_GT(bytes_read, 0) << "Failed to read from pipe " << strerror(errno);
558 std::move(subprocess).Wait();
559 return atoi(text_output.data()) * 1024;
560 }
561
562 /**
563 * Find an image file through the input path and pattern.
564 *
565 * If it finds the file, return the path string.
566 * If it can't find the file, return empty string.
567 */
FindImage(const std::string & search_path,const std::vector<std::string> & pattern)568 std::string FindImage(const std::string& search_path,
569 const std::vector<std::string>& pattern) {
570 const std::string& search_path_extend = search_path + "/";
571 for (const auto& name : pattern) {
572 std::string image = search_path_extend + name;
573 if (FileExists(image)) {
574 return image;
575 }
576 }
577 return "";
578 }
579
FindFile(const std::string & path,const std::string & target_name)580 Result<std::string> FindFile(const std::string& path,
581 const std::string& target_name) {
582 std::string ret;
583 auto res = WalkDirectory(
584 path, [&ret, &target_name](const std::string& filename) mutable {
585 if (android::base::Basename(filename) == target_name) {
586 ret = filename;
587 }
588 return true;
589 });
590 if (!res.ok()) {
591 return "";
592 }
593 return ret;
594 }
595
596 // Recursively enumerate files in |dir|, and invoke the callback function with
597 // path to each file/directory.
WalkDirectory(const std::string & dir,const std::function<bool (const std::string &)> & callback)598 Result<void> WalkDirectory(
599 const std::string& dir,
600 const std::function<bool(const std::string&)>& callback) {
601 const auto files = CF_EXPECT(DirectoryContents(dir));
602 for (const auto& filename : files) {
603 auto file_path = dir + "/";
604 file_path.append(filename);
605 callback(file_path);
606 if (DirectoryExists(file_path)) {
607 auto res = WalkDirectory(file_path, callback);
608 if (!res.ok()) {
609 return res;
610 }
611 }
612 }
613 return {};
614 }
615
616 #ifdef __linux__
617 class InotifyWatcher {
618 public:
InotifyWatcher(int inotify,const std::string & path,int watch_mode)619 InotifyWatcher(int inotify, const std::string& path, int watch_mode)
620 : inotify_(inotify) {
621 watch_ = inotify_add_watch(inotify_, path.c_str(), watch_mode);
622 }
~InotifyWatcher()623 virtual ~InotifyWatcher() { inotify_rm_watch(inotify_, watch_); }
624
625 private:
626 int inotify_;
627 int watch_;
628 };
629
WaitForFileInternal(const std::string & path,int timeoutSec,int inotify)630 static Result<void> WaitForFileInternal(const std::string& path, int timeoutSec,
631 int inotify) {
632 CF_EXPECT_NE(path, "", "Path is empty");
633
634 if (FileExists(path, true)) {
635 return {};
636 }
637
638 const auto targetTime =
639 std::chrono::system_clock::now() + std::chrono::seconds(timeoutSec);
640
641 const std::string parentPath = android::base::Dirname(path);
642 const std::string filename = android::base::Basename(path);
643
644 CF_EXPECT(WaitForFile(parentPath, timeoutSec),
645 "Error while waiting for parent directory creation");
646
647 auto watcher = InotifyWatcher(inotify, parentPath.c_str(), IN_CREATE);
648
649 if (FileExists(path, true)) {
650 return {};
651 }
652
653 while (true) {
654 const auto currentTime = std::chrono::system_clock::now();
655
656 if (currentTime >= targetTime) {
657 return CF_ERR("Timed out");
658 }
659
660 const auto timeRemain =
661 std::chrono::duration_cast<std::chrono::microseconds>(targetTime -
662 currentTime)
663 .count();
664 const auto secondInUsec =
665 std::chrono::microseconds(std::chrono::seconds(1)).count();
666 struct timeval timeout;
667
668 timeout.tv_sec = timeRemain / secondInUsec;
669 timeout.tv_usec = timeRemain % secondInUsec;
670
671 fd_set readfds;
672
673 FD_ZERO(&readfds);
674 FD_SET(inotify, &readfds);
675
676 auto ret = select(inotify + 1, &readfds, NULL, NULL, &timeout);
677
678 if (ret == 0) {
679 return CF_ERR("select() timed out");
680 } else if (ret < 0) {
681 return CF_ERRNO("select() failed");
682 }
683
684 auto names = GetCreatedFileListFromInotifyFd(inotify);
685
686 CF_EXPECT(names.size() > 0,
687 "Failed to get names from inotify " << strerror(errno));
688
689 if (Contains(names, filename)) {
690 return {};
691 }
692 }
693
694 return CF_ERR("This shouldn't be executed");
695 }
696
WaitForFile(const std::string & path,int timeoutSec)697 auto WaitForFile(const std::string& path, int timeoutSec)
698 -> decltype(WaitForFileInternal(path, timeoutSec, 0)) {
699 android::base::unique_fd inotify(inotify_init1(IN_CLOEXEC));
700
701 CF_EXPECT(WaitForFileInternal(path, timeoutSec, inotify.get()));
702
703 return {};
704 }
705
WaitForUnixSocket(const std::string & path,int timeoutSec)706 Result<void> WaitForUnixSocket(const std::string& path, int timeoutSec) {
707 const auto targetTime =
708 std::chrono::system_clock::now() + std::chrono::seconds(timeoutSec);
709
710 CF_EXPECT(WaitForFile(path, timeoutSec),
711 "Waiting for socket path creation failed");
712 CF_EXPECT(FileIsSocket(path), "Specified path is not a socket");
713
714 while (true) {
715 const auto currentTime = std::chrono::system_clock::now();
716
717 if (currentTime >= targetTime) {
718 return CF_ERR("Timed out");
719 }
720
721 const auto timeRemain = std::chrono::duration_cast<std::chrono::seconds>(
722 targetTime - currentTime)
723 .count();
724 auto testConnect =
725 SharedFD::SocketLocalClient(path, false, SOCK_STREAM, timeRemain);
726
727 if (testConnect->IsOpen()) {
728 return {};
729 }
730
731 sched_yield();
732 }
733
734 return CF_ERR("This shouldn't be executed");
735 }
736
WaitForUnixSocketListeningWithoutConnect(const std::string & path,int timeoutSec)737 Result<void> WaitForUnixSocketListeningWithoutConnect(const std::string& path,
738 int timeoutSec) {
739 const auto targetTime =
740 std::chrono::system_clock::now() + std::chrono::seconds(timeoutSec);
741
742 CF_EXPECT(WaitForFile(path, timeoutSec),
743 "Waiting for socket path creation failed");
744 CF_EXPECT(FileIsSocket(path), "Specified path is not a socket");
745
746 std::regex socket_state_regex("TST=(.*)");
747
748 while (true) {
749 const auto currentTime = std::chrono::system_clock::now();
750
751 if (currentTime >= targetTime) {
752 return CF_ERR("Timed out");
753 }
754
755 Command lsof("/usr/bin/lsof");
756 lsof.AddParameter(/*"format"*/ "-F", /*"connection state"*/ "TST");
757 lsof.AddParameter(path);
758 std::string lsof_out;
759 std::string lsof_err;
760 int rval =
761 RunWithManagedStdio(std::move(lsof), nullptr, &lsof_out, &lsof_err);
762 if (rval != 0) {
763 return CF_ERR("Failed to run `lsof`, stderr: " << lsof_err);
764 }
765
766 LOG(DEBUG) << "lsof stdout:|" << lsof_out << "|";
767 LOG(DEBUG) << "lsof stderr:|" << lsof_err << "|";
768
769 std::smatch socket_state_match;
770 if (std::regex_search(lsof_out, socket_state_match, socket_state_regex)) {
771 if (socket_state_match.size() == 2) {
772 const std::string& socket_state = socket_state_match[1];
773 if (socket_state == "LISTEN") {
774 return {};
775 }
776 }
777 }
778
779 sched_yield();
780 }
781
782 return CF_ERR("This shouldn't be executed");
783 }
784 #endif
785
786 namespace {
787
FoldPath(std::vector<std::string> elements,std::string token)788 std::vector<std::string> FoldPath(std::vector<std::string> elements,
789 std::string token) {
790 static constexpr std::array kIgnored = {".", "..", ""};
791 if (token == ".." && !elements.empty()) {
792 elements.pop_back();
793 } else if (!Contains(kIgnored, token)) {
794 elements.emplace_back(token);
795 }
796 return elements;
797 }
798
CalculatePrefix(const InputPathForm & path_info)799 Result<std::vector<std::string>> CalculatePrefix(
800 const InputPathForm& path_info) {
801 const auto& path = path_info.path_to_convert;
802 std::string working_dir;
803 if (path_info.current_working_dir) {
804 working_dir = *path_info.current_working_dir;
805 } else {
806 working_dir = CurrentDirectory();
807 }
808 std::vector<std::string> prefix;
809 if (path == "~" || android::base::StartsWith(path, "~/")) {
810 const auto home_dir =
811 path_info.home_dir.value_or(CF_EXPECT(SystemWideUserHome()));
812 prefix = android::base::Tokenize(home_dir, "/");
813 } else if (!android::base::StartsWith(path, "/")) {
814 prefix = android::base::Tokenize(working_dir, "/");
815 }
816 return prefix;
817 }
818
819 } // namespace
820
EmulateAbsolutePath(const InputPathForm & path_info)821 Result<std::string> EmulateAbsolutePath(const InputPathForm& path_info) {
822 const auto& path = path_info.path_to_convert;
823 std::string working_dir;
824 if (path_info.current_working_dir) {
825 working_dir = *path_info.current_working_dir;
826 } else {
827 working_dir = CurrentDirectory();
828 }
829 CF_EXPECT(android::base::StartsWith(working_dir, '/'),
830 "Current working directory should be given in an absolute path.");
831
832 if (path.empty()) {
833 LOG(ERROR) << "The requested path to convert an absolute path is empty.";
834 return "";
835 }
836
837 auto prefix = CF_EXPECT(CalculatePrefix(path_info));
838 std::vector<std::string> components;
839 components.insert(components.end(), prefix.begin(), prefix.end());
840 auto tokens = android::base::Tokenize(path, "/");
841 // remove first ~
842 if (!tokens.empty() && tokens.at(0) == "~") {
843 tokens.erase(tokens.begin());
844 }
845 components.insert(components.end(), tokens.begin(), tokens.end());
846
847 std::string combined = android::base::Join(components, "/");
848 CF_EXPECTF(!Contains(components, "~"),
849 "~ is not allowed in the middle of the path: {}", combined);
850
851 auto processed_tokens = std::accumulate(components.begin(), components.end(),
852 std::vector<std::string>{}, FoldPath);
853
854 const auto processed_path = "/" + android::base::Join(processed_tokens, "/");
855
856 std::string real_path = processed_path;
857 if (path_info.follow_symlink && FileExists(processed_path)) {
858 CF_EXPECTF(android::base::Realpath(processed_path, &real_path),
859 "Failed to effectively conduct readpath -f {}", processed_path);
860 }
861 return real_path;
862 }
863
864 } // namespace cuttlefish
865