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     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::unique_ptr<char, void (*)(void*)> cwd(getcwd(nullptr, 0), &free);
480   std::string process_cwd(cwd.get());
481   if (!cwd) {
482     PLOG(ERROR) << "`getcwd(nullptr, 0)` failed";
483     return "";
484   }
485   return process_cwd;
486 }
487 
SparseFileSizes(const std::string & path)488 FileSizes SparseFileSizes(const std::string& path) {
489   auto fd = SharedFD::Open(path, O_RDONLY);
490   if (!fd->IsOpen()) {
491     LOG(ERROR) << "Could not open \"" << path << "\": " << fd->StrError();
492     return {};
493   }
494   off_t farthest_seek = fd->LSeek(0, SEEK_END);
495   LOG(VERBOSE) << "Farthest seek: " << farthest_seek;
496   if (farthest_seek == -1) {
497     LOG(ERROR) << "Could not lseek in \"" << path << "\": " << fd->StrError();
498     return {};
499   }
500   off_t data_bytes = 0;
501   off_t offset = 0;
502   while (offset < farthest_seek) {
503     off_t new_offset = fd->LSeek(offset, SEEK_HOLE);
504     if (new_offset == -1) {
505       // ENXIO is returned when there are no more blocks of this type coming.
506       if (fd->GetErrno() == ENXIO) {
507         break;
508       } else {
509         LOG(ERROR) << "Could not lseek in \"" << path << "\": " << fd->StrError();
510         return {};
511       }
512     } else {
513       data_bytes += new_offset - offset;
514       offset = new_offset;
515     }
516     if (offset >= farthest_seek) {
517       break;
518     }
519     new_offset = fd->LSeek(offset, SEEK_DATA);
520     if (new_offset == -1) {
521       // ENXIO is returned when there are no more blocks of this type coming.
522       if (fd->GetErrno() == ENXIO) {
523         break;
524       } else {
525         LOG(ERROR) << "Could not lseek in \"" << path << "\": " << fd->StrError();
526         return {};
527       }
528     } else {
529       offset = new_offset;
530     }
531   }
532   return (FileSizes) { .sparse_size = farthest_seek, .disk_size = data_bytes };
533 }
534 
FileIsSocket(const std::string & path)535 bool FileIsSocket(const std::string& path) {
536   struct stat st {};
537   return stat(path.c_str(), &st) == 0 && S_ISSOCK(st.st_mode);
538 }
539 
GetDiskUsage(const std::string & path)540 int GetDiskUsage(const std::string& path) {
541   Command du_cmd("du");
542   du_cmd.AddParameter("-b");
543   du_cmd.AddParameter("-k");
544   du_cmd.AddParameter("-s");
545   du_cmd.AddParameter(path);
546   SharedFD read_fd;
547   SharedFD write_fd;
548   SharedFD::Pipe(&read_fd, &write_fd);
549   du_cmd.RedirectStdIO(Subprocess::StdIOChannel::kStdOut, write_fd);
550   auto subprocess = du_cmd.Start();
551   std::array<char, 1024> text_output{};
552   const auto bytes_read = read_fd->Read(text_output.data(), text_output.size());
553   CHECK_GT(bytes_read, 0) << "Failed to read from pipe " << strerror(errno);
554   std::move(subprocess).Wait();
555   return atoi(text_output.data()) * 1024;
556 }
557 
558 /**
559  * Find an image file through the input path and pattern.
560  *
561  * If it finds the file, return the path string.
562  * If it can't find the file, return empty string.
563  */
FindImage(const std::string & search_path,const std::vector<std::string> & pattern)564 std::string FindImage(const std::string& search_path,
565                       const std::vector<std::string>& pattern) {
566   const std::string& search_path_extend = search_path + "/";
567   for (const auto& name : pattern) {
568     std::string image = search_path_extend + name;
569     if (FileExists(image)) {
570       return image;
571     }
572   }
573   return "";
574 }
575 
FindFile(const std::string & path,const std::string & target_name)576 std::string FindFile(const std::string& path, const std::string& target_name) {
577   std::string ret;
578   WalkDirectory(path,
579                 [&ret, &target_name](const std::string& filename) mutable {
580                   if (android::base::Basename(filename) == target_name) {
581                     ret = filename;
582                   }
583                   return true;
584                 });
585   return ret;
586 }
587 
588 // Recursively enumerate files in |dir|, and invoke the callback function with
589 // path to each file/directory.
WalkDirectory(const std::string & dir,const std::function<bool (const std::string &)> & callback)590 Result<void> WalkDirectory(
591     const std::string& dir,
592     const std::function<bool(const std::string&)>& callback) {
593   const auto files = CF_EXPECT(DirectoryContents(dir));
594   for (const auto& filename : files) {
595     auto file_path = dir + "/";
596     file_path.append(filename);
597     callback(file_path);
598     if (DirectoryExists(file_path)) {
599       WalkDirectory(file_path, callback);
600     }
601   }
602   return {};
603 }
604 
605 #ifdef __linux__
606 class InotifyWatcher {
607  public:
InotifyWatcher(int inotify,const std::string & path,int watch_mode)608   InotifyWatcher(int inotify, const std::string& path, int watch_mode)
609       : inotify_(inotify) {
610     watch_ = inotify_add_watch(inotify_, path.c_str(), watch_mode);
611   }
~InotifyWatcher()612   virtual ~InotifyWatcher() { inotify_rm_watch(inotify_, watch_); }
613 
614  private:
615   int inotify_;
616   int watch_;
617 };
618 
WaitForFileInternal(const std::string & path,int timeoutSec,int inotify)619 static Result<void> WaitForFileInternal(const std::string& path, int timeoutSec,
620                                         int inotify) {
621   CF_EXPECT_NE(path, "", "Path is empty");
622 
623   if (FileExists(path, true)) {
624     return {};
625   }
626 
627   const auto targetTime =
628       std::chrono::system_clock::now() + std::chrono::seconds(timeoutSec);
629 
630   const std::string parentPath = android::base::Dirname(path);
631   const std::string filename = android::base::Basename(path);
632 
633   CF_EXPECT(WaitForFile(parentPath, timeoutSec),
634             "Error while waiting for parent directory creation");
635 
636   auto watcher = InotifyWatcher(inotify, parentPath.c_str(), IN_CREATE);
637 
638   if (FileExists(path, true)) {
639     return {};
640   }
641 
642   while (true) {
643     const auto currentTime = std::chrono::system_clock::now();
644 
645     if (currentTime >= targetTime) {
646       return CF_ERR("Timed out");
647     }
648 
649     const auto timeRemain =
650         std::chrono::duration_cast<std::chrono::microseconds>(targetTime -
651                                                               currentTime)
652             .count();
653     const auto secondInUsec =
654         std::chrono::microseconds(std::chrono::seconds(1)).count();
655     struct timeval timeout;
656 
657     timeout.tv_sec = timeRemain / secondInUsec;
658     timeout.tv_usec = timeRemain % secondInUsec;
659 
660     fd_set readfds;
661 
662     FD_ZERO(&readfds);
663     FD_SET(inotify, &readfds);
664 
665     auto ret = select(inotify + 1, &readfds, NULL, NULL, &timeout);
666 
667     if (ret == 0) {
668       return CF_ERR("select() timed out");
669     } else if (ret < 0) {
670       return CF_ERRNO("select() failed");
671     }
672 
673     auto names = GetCreatedFileListFromInotifyFd(inotify);
674 
675     CF_EXPECT(names.size() > 0,
676               "Failed to get names from inotify " << strerror(errno));
677 
678     if (Contains(names, filename)) {
679       return {};
680     }
681   }
682 
683   return CF_ERR("This shouldn't be executed");
684 }
685 
WaitForFile(const std::string & path,int timeoutSec)686 auto WaitForFile(const std::string& path, int timeoutSec)
687     -> decltype(WaitForFileInternal(path, timeoutSec, 0)) {
688   android::base::unique_fd inotify(inotify_init1(IN_CLOEXEC));
689 
690   CF_EXPECT(WaitForFileInternal(path, timeoutSec, inotify.get()));
691 
692   return {};
693 }
694 
WaitForUnixSocket(const std::string & path,int timeoutSec)695 Result<void> WaitForUnixSocket(const std::string& path, int timeoutSec) {
696   const auto targetTime =
697       std::chrono::system_clock::now() + std::chrono::seconds(timeoutSec);
698 
699   CF_EXPECT(WaitForFile(path, timeoutSec),
700             "Waiting for socket path creation failed");
701   CF_EXPECT(FileIsSocket(path), "Specified path is not a socket");
702 
703   while (true) {
704     const auto currentTime = std::chrono::system_clock::now();
705 
706     if (currentTime >= targetTime) {
707       return CF_ERR("Timed out");
708     }
709 
710     const auto timeRemain = std::chrono::duration_cast<std::chrono::seconds>(
711                                 targetTime - currentTime)
712                                 .count();
713     auto testConnect =
714         SharedFD::SocketLocalClient(path, false, SOCK_STREAM, timeRemain);
715 
716     if (testConnect->IsOpen()) {
717       return {};
718     }
719 
720     sched_yield();
721   }
722 
723   return CF_ERR("This shouldn't be executed");
724 }
725 
WaitForUnixSocketListeningWithoutConnect(const std::string & path,int timeoutSec)726 Result<void> WaitForUnixSocketListeningWithoutConnect(const std::string& path,
727                                                       int timeoutSec) {
728   const auto targetTime =
729       std::chrono::system_clock::now() + std::chrono::seconds(timeoutSec);
730 
731   CF_EXPECT(WaitForFile(path, timeoutSec),
732             "Waiting for socket path creation failed");
733   CF_EXPECT(FileIsSocket(path), "Specified path is not a socket");
734 
735   std::regex socket_state_regex("TST=(.*)");
736 
737   while (true) {
738     const auto currentTime = std::chrono::system_clock::now();
739 
740     if (currentTime >= targetTime) {
741       return CF_ERR("Timed out");
742     }
743 
744     Command lsof("/usr/bin/lsof");
745     lsof.AddParameter(/*"format"*/ "-F", /*"connection state"*/ "TST");
746     lsof.AddParameter(path);
747     std::string lsof_out;
748     std::string lsof_err;
749     int rval =
750         RunWithManagedStdio(std::move(lsof), nullptr, &lsof_out, &lsof_err);
751     if (rval != 0) {
752       return CF_ERR("Failed to run `lsof`, stderr: " << lsof_err);
753     }
754 
755     LOG(DEBUG) << "lsof stdout:|" << lsof_out << "|";
756     LOG(DEBUG) << "lsof stderr:|" << lsof_err << "|";
757 
758     std::smatch socket_state_match;
759     if (std::regex_search(lsof_out, socket_state_match, socket_state_regex)) {
760       if (socket_state_match.size() == 2) {
761         const std::string& socket_state = socket_state_match[1];
762         if (socket_state == "LISTEN") {
763           return {};
764         }
765       }
766     }
767 
768     sched_yield();
769   }
770 
771   return CF_ERR("This shouldn't be executed");
772 }
773 #endif
774 
775 namespace {
776 
FoldPath(std::vector<std::string> elements,std::string token)777 std::vector<std::string> FoldPath(std::vector<std::string> elements,
778                                   std::string token) {
779   static constexpr std::array kIgnored = {".", "..", ""};
780   if (token == ".." && !elements.empty()) {
781     elements.pop_back();
782   } else if (!Contains(kIgnored, token)) {
783     elements.emplace_back(token);
784   }
785   return elements;
786 }
787 
CalculatePrefix(const InputPathForm & path_info)788 Result<std::vector<std::string>> CalculatePrefix(
789     const InputPathForm& path_info) {
790   const auto& path = path_info.path_to_convert;
791   std::string working_dir;
792   if (path_info.current_working_dir) {
793     working_dir = *path_info.current_working_dir;
794   } else {
795     working_dir = CurrentDirectory();
796   }
797   std::vector<std::string> prefix;
798   if (path == "~" || android::base::StartsWith(path, "~/")) {
799     const auto home_dir =
800         path_info.home_dir.value_or(CF_EXPECT(SystemWideUserHome()));
801     prefix = android::base::Tokenize(home_dir, "/");
802   } else if (!android::base::StartsWith(path, "/")) {
803     prefix = android::base::Tokenize(working_dir, "/");
804   }
805   return prefix;
806 }
807 
808 }  // namespace
809 
EmulateAbsolutePath(const InputPathForm & path_info)810 Result<std::string> EmulateAbsolutePath(const InputPathForm& path_info) {
811   const auto& path = path_info.path_to_convert;
812   std::string working_dir;
813   if (path_info.current_working_dir) {
814     working_dir = *path_info.current_working_dir;
815   } else {
816     working_dir = CurrentDirectory();
817   }
818   CF_EXPECT(android::base::StartsWith(working_dir, '/'),
819             "Current working directory should be given in an absolute path.");
820 
821   if (path.empty()) {
822     LOG(ERROR) << "The requested path to convert an absolute path is empty.";
823     return "";
824   }
825 
826   auto prefix = CF_EXPECT(CalculatePrefix(path_info));
827   std::vector<std::string> components;
828   components.insert(components.end(), prefix.begin(), prefix.end());
829   auto tokens = android::base::Tokenize(path, "/");
830   // remove first ~
831   if (!tokens.empty() && tokens.at(0) == "~") {
832     tokens.erase(tokens.begin());
833   }
834   components.insert(components.end(), tokens.begin(), tokens.end());
835 
836   std::string combined = android::base::Join(components, "/");
837   CF_EXPECTF(!Contains(components, "~"),
838              "~ is not allowed in the middle of the path: {}", combined);
839 
840   auto processed_tokens = std::accumulate(components.begin(), components.end(),
841                                           std::vector<std::string>{}, FoldPath);
842 
843   const auto processed_path = "/" + android::base::Join(processed_tokens, "/");
844 
845   std::string real_path = processed_path;
846   if (path_info.follow_symlink && FileExists(processed_path)) {
847     CF_EXPECTF(android::base::Realpath(processed_path, &real_path),
848                "Failed to effectively conduct readpath -f {}", processed_path);
849   }
850   return real_path;
851 }
852 
853 }  // namespace cuttlefish
854