Skip to content

Commit ee4ecbc

Browse files
committed
Avoid the use of low-numbered file descriptors.
1 parent b9f7cc4 commit ee4ecbc

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

tdutils/td/utils/port/FileFd.cpp

+18-4
Original file line numberDiff line numberDiff line change
@@ -157,11 +157,25 @@ Result<FileFd> FileFd::open(CSlice filepath, int32 flags, int32 mode) {
157157
}
158158
#endif
159159

160-
int native_fd = detail::skip_eintr([&] { return ::open(filepath.c_str(), native_flags, static_cast<mode_t>(mode)); });
161-
if (native_fd < 0) {
162-
return OS_ERROR(PSLICE() << "File \"" << filepath << "\" can't be " << PrintFlags{flags});
160+
while (1) {
161+
int native_fd =
162+
detail::skip_eintr([&] { return ::open(filepath.c_str(), native_flags, static_cast<mode_t>(mode)); });
163+
if (native_fd < 0) {
164+
return OS_ERROR(PSLICE() << "File \"" << filepath << "\" can't be " << PrintFlags{flags});
165+
}
166+
// Avoid the use of low-numbered file descriptors, which can be used directly by some other functions
167+
constexpr int MINIMUM_FILE_DESCRIPTOR = 3;
168+
if (native_fd < MINIMUM_FILE_DESCRIPTOR) {
169+
::close(native_fd);
170+
LOG(ERROR) << "Receive " << native_fd << " as a file descriptor";
171+
int dummy_fd = detail::skip_eintr([&] { return ::open("/dev/null", O_RDONLY, 0); });
172+
if (dummy_fd < 0) {
173+
return OS_ERROR("Can't open /dev/null");
174+
}
175+
continue;
176+
}
177+
return from_native_fd(NativeFd(native_fd));
163178
}
164-
return from_native_fd(NativeFd(native_fd));
165179
#elif TD_PORT_WINDOWS
166180
// TODO: support modes
167181
auto r_filepath = to_wstring(filepath);

0 commit comments

Comments
 (0)