Debian Codegraph @

crt/aws-c-common/source/posix/file.c

raw symbols SCIP
1 /**
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0.
4 */
5 #include <aws/common/environment.h>
6 #include <aws/common/file.h>
7 #include <aws/common/logging.h>
8 #include <aws/common/string.h>
9 #include <dirent.h>
10 #include <errno.h>
11 #include <pwd.h>
12 #include <stdio.h>
13 #include <sys/stat.h>
14 #include <unistd.h>
15
16 FILE *aws_fopen_safe(const struct aws_string *file_path, const struct aws_string *mode) {
17 FILE *f = fopen(aws_string_c_str(file_path), aws_string_c_str(mode));
18 if (!f) {
19 int errno_cpy = errno; /* Always cache errno before potential side-effect */
20 aws_translate_and_raise_io_error_or(errno_cpy, AWS_ERROR_FILE_OPEN_FAILURE);
21 AWS_LOGF_ERROR(
22 AWS_LS_COMMON_IO,
23 "static: Failed to open file. path:'%s' mode:'%s' errno:%d aws-error:%d(%s)",
24 aws_string_c_str(file_path),
25 aws_string_c_str(mode),
26 errno_cpy,
27 aws_last_error(),
28 aws_error_name(aws_last_error()));
29 }
30 return f;
31 }
32
33 int aws_directory_create(const struct aws_string *dir_path) {
34 int mkdir_ret = mkdir(aws_string_c_str(dir_path), S_IRWXU | S_IRWXG | S_IRWXO);
35 int errno_value = errno; /* Always cache errno before potential side-effect */
36
37 /** nobody cares if it already existed. */
38 if (mkdir_ret != 0 && errno_value != EEXIST) {
39 return aws_translate_and_raise_io_error(errno_value);
40 }
41
42 return AWS_OP_SUCCESS;
43 }
44
45 bool aws_directory_exists(const struct aws_string *dir_path) {
46 struct stat dir_info;
47 if (lstat(aws_string_c_str(dir_path), &dir_info) == 0 && S_ISDIR(dir_info.st_mode)) {
48 return true;
49 }
50
51 return false;
52 }
53
54 static bool s_delete_file_or_directory(const struct aws_directory_entry *entry, void *user_data) {
55 (void)user_data;
56
57 struct aws_allocator *allocator = aws_default_allocator();
58
59 struct aws_string *path_str = aws_string_new_from_cursor(allocator, &entry->relative_path);
60 int ret_val = AWS_OP_SUCCESS;
61
62 if (entry->file_type & AWS_FILE_TYPE_FILE) {
63 ret_val = aws_file_delete(path_str);
64 }
65
66 if (entry->file_type & AWS_FILE_TYPE_DIRECTORY) {
67 ret_val = aws_directory_delete(path_str, false);
68 }
69
70 aws_string_destroy(path_str);
71 return ret_val == AWS_OP_SUCCESS;
72 }
73
74 int aws_directory_delete(const struct aws_string *dir_path, bool recursive) {
75 if (!aws_directory_exists(dir_path)) {
76 return AWS_OP_SUCCESS;
77 }
78
79 int ret_val = AWS_OP_SUCCESS;
80
81 if (recursive) {
82 ret_val = aws_directory_traverse(aws_default_allocator(), dir_path, true, s_delete_file_or_directory, NULL);
83 }
84
85 if (ret_val && aws_last_error() == AWS_ERROR_FILE_INVALID_PATH) {
86 aws_reset_error();
87 return AWS_OP_SUCCESS;
88 }
89
90 if (ret_val) {
91 return AWS_OP_ERR;
92 }
93
94 int error_code = rmdir(aws_string_c_str(dir_path));
95 int errno_value = errno; /* Always cache errno before potential side-effect */
96
97 return error_code == 0 ? AWS_OP_SUCCESS : aws_translate_and_raise_io_error(errno_value);
98 }
99
100 int aws_directory_or_file_move(const struct aws_string *from, const struct aws_string *to) {
101 int error_code = rename(aws_string_c_str(from), aws_string_c_str(to));
102 int errno_value = errno; /* Always cache errno before potential side-effect */
103
104 return error_code == 0 ? AWS_OP_SUCCESS : aws_translate_and_raise_io_error(errno_value);
105 }
106
107 int aws_file_delete(const struct aws_string *file_path) {
108 int error_code = unlink(aws_string_c_str(file_path));
109 int errno_value = errno; /* Always cache errno before potential side-effect */
110
111 if (!error_code || errno_value == ENOENT) {
112 return AWS_OP_SUCCESS;
113 }
114
115 return aws_translate_and_raise_io_error(errno_value);
116 }
117
118 int aws_directory_traverse(
119 struct aws_allocator *allocator,
120 const struct aws_string *path,
121 bool recursive,
122 aws_on_directory_entry *on_entry,
123 void *user_data) {
124 DIR *dir = opendir(aws_string_c_str(path));
125 int errno_value = errno; /* Always cache errno before potential side-effect */
126
127 if (!dir) {
128 return aws_translate_and_raise_io_error(errno_value);
129 }
130
131 struct aws_byte_cursor current_path = aws_byte_cursor_from_string(path);
132 if (current_path.ptr[current_path.len - 1] == AWS_PATH_DELIM) {
133 current_path.len -= 1;
134 }
135
136 struct dirent *dirent = NULL;
137 int ret_val = AWS_ERROR_SUCCESS;
138
139 errno = 0;
140 while (!ret_val && (dirent = readdir(dir)) != NULL) {
141 /* note: dirent->name_len is only defined on the BSDs, but not linux. It's not in the
142 * required posix spec. So we use dirent->d_name as a c string here. */
143 struct aws_byte_cursor name_component = aws_byte_cursor_from_c_str(dirent->d_name);
144
145 if (aws_byte_cursor_eq_c_str(&name_component, "..") || aws_byte_cursor_eq_c_str(&name_component, ".")) {
146 continue;
147 }
148
149 struct aws_byte_buf relative_path;
150 aws_byte_buf_init_copy_from_cursor(&relative_path, allocator, current_path);
151 aws_byte_buf_append_byte_dynamic(&relative_path, AWS_PATH_DELIM);
152 aws_byte_buf_append_dynamic(&relative_path, &name_component);
153 aws_byte_buf_append_byte_dynamic(&relative_path, 0);
154 relative_path.len -= 1;
155
156 struct aws_directory_entry entry;
157 AWS_ZERO_STRUCT(entry);
158
159 struct stat dir_info;
160 if (!lstat((const char *)relative_path.buffer, &dir_info)) {
161 if (S_ISDIR(dir_info.st_mode)) {
162 entry.file_type |= AWS_FILE_TYPE_DIRECTORY;
163 }
164 if (S_ISLNK(dir_info.st_mode)) {
165 entry.file_type |= AWS_FILE_TYPE_SYM_LINK;
166 }
167 if (S_ISREG(dir_info.st_mode)) {
168 entry.file_type |= AWS_FILE_TYPE_FILE;
169 entry.file_size = dir_info.st_size;
170 }
171
172 if (!entry.file_type) {
173 AWS_ASSERT("Unknown file type encountered");
174 }
175
176 entry.relative_path = aws_byte_cursor_from_buf(&relative_path);
177 const char *full_path = realpath((const char *)relative_path.buffer, NULL);
178
179 if (full_path) {
180 entry.path = aws_byte_cursor_from_c_str(full_path);
181 }
182
183 if (recursive && entry.file_type & AWS_FILE_TYPE_DIRECTORY) {
184 struct aws_string *rel_path_str = aws_string_new_from_cursor(allocator, &entry.relative_path);
185 ret_val = aws_directory_traverse(allocator, rel_path_str, recursive, on_entry, user_data);
186 aws_string_destroy(rel_path_str);
187 }
188
189 /* post order traversal, if a node below us ended the traversal, don't call the visitor again. */
190 if (ret_val && aws_last_error() == AWS_ERROR_OPERATION_INTERUPTED) {
191 goto cleanup;
192 }
193
194 if (!on_entry(&entry, user_data)) {
195 ret_val = aws_raise_error(AWS_ERROR_OPERATION_INTERUPTED);
196 goto cleanup;
197 }
198
199 if (ret_val) {
200 goto cleanup;
201 }
202
203 cleanup:
204 /* per https://man7.org/linux/man-pages/man3/realpath.3.html, realpath must be freed, if NULL was passed
205 * to the second argument. */
206 if (full_path) {
207 free((void *)full_path);
208 }
209 aws_byte_buf_clean_up(&relative_path);
210 }
211 }
212
213 closedir(dir);
214 return ret_val;
215 }
216
217 char aws_get_platform_directory_separator(void) {
218 return '/';
219 }
220
221 AWS_STATIC_STRING_FROM_LITERAL(s_home_env_var, "HOME");
222
223 struct aws_string *aws_get_home_directory(struct aws_allocator *allocator) {
224
225 /* First, check "HOME" environment variable.
226 * If it's set, then return it, even if it's an empty string. */
227 struct aws_string *home_value = NULL;
228 aws_get_environment_value(allocator, s_home_env_var, &home_value);
229 if (home_value != NULL) {
230 return home_value;
231 }
232
233 /* Next, check getpwuid_r().
234 * We need to allocate a tmp buffer to store the result strings,
235 * and the max possible size for this thing can be pretty big,
236 * so start with a reasonable allocation, and if that's not enough try something bigger. */
237 uid_t uid = getuid(); /* cannot fail */
238 struct passwd pwd;
239 struct passwd *result = NULL;
240 char *buf = NULL;
241 int status = ERANGE;
242 for (size_t bufsize = 1024; bufsize <= 16384 && status == ERANGE; bufsize *= 2) {
243 if (buf) {
244 aws_mem_release(allocator, buf);
245 }
246 buf = aws_mem_acquire(allocator, bufsize);
247 /* Note: on newer GCC with address sanitizer on, getpwuid_r triggers
248 * build error, since buf can in theory be null, but buffsize will be
249 * nonzero. following if statement works around that. */
250 if (buf == NULL) {
251 aws_raise_error(AWS_ERROR_GET_HOME_DIRECTORY_FAILED);
252 return NULL;
253 }
254
255 status = getpwuid_r(uid, &pwd, buf, bufsize, &result);
256 }
257
258 if (status == 0 && result != NULL && result->pw_dir != NULL) {
259 home_value = aws_string_new_from_c_str(allocator, result->pw_dir);
260 } else {
261 aws_raise_error(AWS_ERROR_GET_HOME_DIRECTORY_FAILED);
262 }
263
264 aws_mem_release(allocator, buf);
265 return home_value;
266 }
267
268 bool aws_path_exists(const struct aws_string *path) {
269 struct stat buffer;
270 return stat(aws_string_c_str(path), &buffer) == 0;
271 }
272
273 int aws_fseek(FILE *file, int64_t offset, int whence) {
274
275 #ifdef AWS_HAVE_POSIX_LARGE_FILE_SUPPORT
276 int result = fseeko(file, offset, whence);
277 #else
278 /* must use fseek(), which takes offset as a long */
279 if (offset < LONG_MIN || offset > LONG_MAX) {
280 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
281 }
282 int result = fseek(file, offset, whence);
283 #endif /* AWS_HAVE_POSIX_LFS */
284 int errno_value = errno; /* Always cache errno before potential side-effect */
285
286 if (result != 0) {
287 return aws_translate_and_raise_io_error_or(errno_value, AWS_ERROR_STREAM_UNSEEKABLE);
288 }
289
290 return AWS_OP_SUCCESS;
291 }
292
293 int aws_file_get_length(FILE *file, int64_t *length) {
294
295 struct stat file_stats;
296
297 int fd = fileno(file);
298 if (fd == -1) {
299 return aws_raise_error(AWS_ERROR_INVALID_FILE_HANDLE);
300 }
301
302 if (fstat(fd, &file_stats)) {
303 int errno_value = errno; /* Always cache errno before potential side-effect */
304 return aws_translate_and_raise_io_error(errno_value);
305 }
306
307 *length = file_stats.st_size;
308
309 return AWS_OP_SUCCESS;
310 }