• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include <android-base/logging.h>
20 
21 #include <array>
22 #include <climits>
23 #include <cstdio>
24 #include <cstdlib>
25 #include <fstream>
26 #include <libgen.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <unistd.h>
30 #include <dirent.h>
31 #include <vector>
32 
33 #include "common/libs/fs/shared_fd.h"
34 
35 namespace cuttlefish {
36 
FileExists(const std::string & path)37 bool FileExists(const std::string& path) {
38   struct stat st;
39   return stat(path.c_str(), &st) == 0;
40 }
41 
FileHasContent(const std::string & path)42 bool FileHasContent(const std::string& path) {
43   return FileSize(path) > 0;
44 }
45 
DirectoryContents(const std::string & path)46 std::vector<std::string> DirectoryContents(const std::string& path) {
47   std::vector<std::string> ret;
48   std::unique_ptr<DIR, int(*)(DIR*)> dir(opendir(path.c_str()), closedir);
49   CHECK(dir != nullptr) << "Could not read from dir \"" << path << "\"";
50   if (dir) {
51     struct dirent *ent;
52     while ((ent = readdir(dir.get()))) {
53       ret.push_back(ent->d_name);
54     }
55   }
56   return ret;
57 }
58 
DirectoryExists(const std::string & path)59 bool DirectoryExists(const std::string& path) {
60   struct stat st;
61   if (stat(path.c_str(), &st) == -1) {
62     return false;
63   }
64   if ((st.st_mode & S_IFMT) != S_IFDIR) {
65     return false;
66   }
67   return true;
68 }
69 
IsDirectoryEmpty(const std::string & path)70 bool IsDirectoryEmpty(const std::string& path) {
71   auto direc = ::opendir(path.c_str());
72   if (!direc) {
73     LOG(ERROR) << "IsDirectoryEmpty test failed with " << path
74                << " as it failed to be open" << std::endl;
75     return false;
76   }
77 
78   decltype(::readdir(direc)) sub = nullptr;
79   int cnt {0};
80   while ( (sub = ::readdir(direc)) ) {
81     cnt++;
82     if (cnt > 2) {
83     LOG(ERROR) << "IsDirectoryEmpty test failed with " << path
84                << " as it exists but not empty" << std::endl;
85       return false;
86     }
87   }
88   return true;
89 }
90 
AbsolutePath(const std::string & path)91 std::string AbsolutePath(const std::string& path) {
92   if (path.empty()) {
93     return {};
94   }
95   if (path[0] == '/') {
96     return path;
97   }
98   if (path[0] == '~') {
99     LOG(WARNING) << "Tilde expansion in path " << path <<" is not supported";
100     return {};
101   }
102 
103   std::array<char, PATH_MAX> buffer{};
104   if (!realpath(".", buffer.data())) {
105     LOG(WARNING) << "Could not get real path for current directory \".\""
106                  << ": " << strerror(errno);
107     return {};
108   }
109   return std::string{buffer.data()} + "/" + path;
110 }
111 
FileSize(const std::string & path)112 off_t FileSize(const std::string& path) {
113   struct stat st;
114   if (stat(path.c_str(), &st) == -1) {
115     return 0;
116   }
117   return st.st_size;
118 }
119 
120 // TODO(schuffelen): Use std::filesystem::last_write_time when on C++17
FileModificationTime(const std::string & path)121 std::chrono::system_clock::time_point FileModificationTime(const std::string& path) {
122   struct stat st;
123   if (stat(path.c_str(), &st) == -1) {
124     return std::chrono::system_clock::time_point();
125   }
126   std::chrono::seconds seconds(st.st_mtim.tv_sec);
127   return std::chrono::system_clock::time_point(seconds);
128 }
129 
RenameFile(const std::string & old_name,const std::string & new_name)130 bool RenameFile(const std::string& old_name, const std::string& new_name) {
131   LOG(DEBUG) << "Renaming " << old_name << " to " << new_name;
132   if(rename(old_name.c_str(), new_name.c_str())) {
133     LOG(ERROR) << "File rename failed due to " << strerror(errno);
134     return false;
135   }
136 
137   return true;
138 }
139 
RemoveFile(const std::string & file)140 bool RemoveFile(const std::string& file) {
141   LOG(DEBUG) << "Removing " << file;
142   return remove(file.c_str()) == 0;
143 }
144 
145 
ReadFile(const std::string & file)146 std::string ReadFile(const std::string& file) {
147   std::string contents;
148   std::ifstream in(file, std::ios::in | std::ios::binary);
149   in.seekg(0, std::ios::end);
150   contents.resize(in.tellg());
151   in.seekg(0, std::ios::beg);
152   in.read(&contents[0], contents.size());
153   in.close();
154   return(contents);
155 }
156 
CurrentDirectory()157 std::string CurrentDirectory() {
158   char* path = getcwd(nullptr, 0);
159   std::string ret(path);
160   free(path);
161   return ret;
162 }
163 
SparseFileSizes(const std::string & path)164 FileSizes SparseFileSizes(const std::string& path) {
165   auto fd = SharedFD::Open(path, O_RDONLY);
166   if (!fd->IsOpen()) {
167     LOG(ERROR) << "Could not open \"" << path << "\": " << fd->StrError();
168     return {};
169   }
170   off_t farthest_seek = fd->LSeek(0, SEEK_END);
171   LOG(VERBOSE) << "Farthest seek: " << farthest_seek;
172   if (farthest_seek == -1) {
173     LOG(ERROR) << "Could not lseek in \"" << path << "\": " << fd->StrError();
174     return {};
175   }
176   off_t data_bytes = 0;
177   off_t offset = 0;
178   while (offset < farthest_seek) {
179     off_t new_offset = fd->LSeek(offset, SEEK_HOLE);
180     if (new_offset == -1) {
181       // ENXIO is returned when there are no more blocks of this type coming.
182       if (fd->GetErrno() == ENXIO) {
183         break;
184       } else {
185         LOG(ERROR) << "Could not lseek in \"" << path << "\": " << fd->StrError();
186         return {};
187       }
188     } else {
189       data_bytes += new_offset - offset;
190       offset = new_offset;
191     }
192     if (offset >= farthest_seek) {
193       break;
194     }
195     new_offset = fd->LSeek(offset, SEEK_DATA);
196     if (new_offset == -1) {
197       // ENXIO is returned when there are no more blocks of this type coming.
198       if (fd->GetErrno() == ENXIO) {
199         break;
200       } else {
201         LOG(ERROR) << "Could not lseek in \"" << path << "\": " << fd->StrError();
202         return {};
203       }
204     } else {
205       offset = new_offset;
206     }
207   }
208   return (FileSizes) { .sparse_size = farthest_seek, .disk_size = data_bytes };
209 }
210 
cpp_basename(const std::string & str)211 std::string cpp_basename(const std::string& str) {
212   char* copy = strdup(str.c_str()); // basename may modify its argument
213   std::string ret(basename(copy));
214   free(copy);
215   return ret;
216 }
217 
cpp_dirname(const std::string & str)218 std::string cpp_dirname(const std::string& str) {
219   char* copy = strdup(str.c_str()); // dirname may modify its argument
220   std::string ret(dirname(copy));
221   free(copy);
222   return ret;
223 }
224 
225 }  // namespace cuttlefish
226