1 /*
2  * Copyright (C) 2022 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 #pragma once
18 
19 #include <dirent.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 
23 #include <stdio.h>
24 #include <sys/types.h>
25 #include <unistd.h>
26 
27 // DO NOT INCLUDE OTHER LIBBASE HEADERS HERE!
28 // This file gets used in libbinder, and libbinder is used everywhere.
29 // Including other headers from libbase frequently results in inclusion of
30 // android-base/macros.h, which causes macro collisions.
31 
32 #if defined(__BIONIC__)
33 #include <android/fdsan.h>
34 #endif
35 #if !defined(_WIN32) && !defined(__TRUSTY__)
36 #include <sys/socket.h>
37 #endif
38 
39 namespace android {
40 namespace base {
41 
42 // Container for a file descriptor that automatically closes the descriptor as
43 // it goes out of scope.
44 //
45 //      unique_fd ufd(open("/some/path", "r"));
46 //      if (ufd.get() == -1) return error;
47 //
48 //      // Do something useful, possibly including 'return'.
49 //
50 //      return 0; // Descriptor is closed for you.
51 //
52 // See also the Pipe()/Socketpair()/Fdopen()/Fdopendir() functions in this file
53 // that provide interoperability with the libc functions with the same (but
54 // lowercase) names.
55 //
56 // unique_fd is also known as ScopedFd/ScopedFD/scoped_fd; mentioned here to
57 // help you find this class if you're searching for one of those names.
58 //
59 // unique_fd itself is a specialization of unique_fd_impl with a default closer.
60 template <typename Closer>
61 class unique_fd_impl final {
62 public:
unique_fd_impl()63     unique_fd_impl() {}
64 
unique_fd_impl(int fd)65     explicit unique_fd_impl(int fd) { reset(fd); }
~unique_fd_impl()66     ~unique_fd_impl() { reset(); }
67 
68     unique_fd_impl(const unique_fd_impl&) = delete;
69     void operator=(const unique_fd_impl&) = delete;
unique_fd_impl(unique_fd_impl && other)70     unique_fd_impl(unique_fd_impl&& other) noexcept { reset(other.release()); }
71     unique_fd_impl& operator=(unique_fd_impl&& s) noexcept {
72         int fd = s.fd_;
73         s.fd_ = -1;
74         reset(fd, &s);
75         return *this;
76     }
77 
78     [[clang::reinitializes]] void reset(int new_value = -1) {
79         reset(new_value, nullptr);
80     }
81 
get()82     int get() const { return fd_; }
83 
84 #if !defined(ANDROID_BASE_UNIQUE_FD_DISABLE_IMPLICIT_CONVERSION)
85     // unique_fd's operator int is dangerous, but we have way too much code that
86     // depends on it, so make this opt-in at first.
87     operator int() const { return get(); }  // NOLINT
88 #endif
89 
90     bool operator>=(int rhs) const { return get() >= rhs; }
91     bool operator<(int rhs) const { return get() < rhs; }
92     bool operator==(int rhs) const { return get() == rhs; }
93     bool operator!=(int rhs) const { return get() != rhs; }
94     bool operator==(const unique_fd_impl& rhs) const {
95         return get() == rhs.get();
96     }
97     bool operator!=(const unique_fd_impl& rhs) const {
98         return get() != rhs.get();
99     }
100 
101     // Catch bogus error checks (i.e.: "!fd" instead of "fd != -1").
102     bool operator!() const = delete;
103 
ok()104     bool ok() const { return get() >= 0; }
105 
release()106     int release() __attribute__((warn_unused_result)) {
107         tag(fd_, this, nullptr);
108         int ret = fd_;
109         fd_ = -1;
110         return ret;
111     }
112 
113 private:
reset(int new_value,void * previous_tag)114     void reset(int new_value, void* previous_tag) {
115         int previous_errno = errno;
116 
117         if (fd_ != -1) {
118             close(fd_, this);
119         }
120 
121         fd_ = new_value;
122         if (new_value != -1) {
123             tag(new_value, previous_tag, this);
124         }
125 
126         errno = previous_errno;
127     }
128 
129     int fd_ = -1;
130 
131     // Template magic to use Closer::Tag if available, and do nothing if not.
132     // If Closer::Tag exists, this implementation is preferred, because int is a
133     // better match. If not, this implementation is SFINAEd away, and the no-op
134     // below is the only one that exists.
135     template <typename T = Closer>
136     static auto tag(int fd, void* old_tag, void* new_tag)
137             -> decltype(T::Tag(fd, old_tag, new_tag), void()) {
138         T::Tag(fd, old_tag, new_tag);
139     }
140 
141     template <typename T = Closer>
tag(long,void *,void *)142     static void tag(long, void*, void*) {
143         // No-op.
144     }
145 
146     // Same as above, to select between Closer::Close(int) and
147     // Closer::Close(int, void*).
148     template <typename T = Closer>
149     static auto close(int fd, void* tag_value)
150             -> decltype(T::Close(fd, tag_value), void()) {
151         T::Close(fd, tag_value);
152     }
153 
154     template <typename T = Closer>
155     static auto close(int fd, void*) -> decltype(T::Close(fd), void()) {
156         T::Close(fd);
157     }
158 };
159 
160 // The actual details of closing are factored out to support unusual cases.
161 // Almost everyone will want this DefaultCloser, which handles fdsan on bionic.
162 struct DefaultCloser {
163 #if defined(__BIONIC__)
TagDefaultCloser164     static void Tag(int fd, void* old_addr, void* new_addr) {
165         if (android_fdsan_exchange_owner_tag) {
166             uint64_t old_tag = android_fdsan_create_owner_tag(
167                     ANDROID_FDSAN_OWNER_TYPE_UNIQUE_FD,
168                     reinterpret_cast<uint64_t>(old_addr));
169             uint64_t new_tag = android_fdsan_create_owner_tag(
170                     ANDROID_FDSAN_OWNER_TYPE_UNIQUE_FD,
171                     reinterpret_cast<uint64_t>(new_addr));
172             android_fdsan_exchange_owner_tag(fd, old_tag, new_tag);
173         }
174     }
CloseDefaultCloser175     static void Close(int fd, void* addr) {
176         if (android_fdsan_close_with_tag) {
177             uint64_t tag = android_fdsan_create_owner_tag(
178                     ANDROID_FDSAN_OWNER_TYPE_UNIQUE_FD,
179                     reinterpret_cast<uint64_t>(addr));
180             android_fdsan_close_with_tag(fd, tag);
181         } else {
182             close(fd);
183         }
184     }
185 #else
186     static void Close(int fd) {
187         // Even if close(2) fails with EINTR, the fd will have been closed.
188         // Using TEMP_FAILURE_RETRY will either lead to EBADF or closing someone
189         // else's fd.
190         // http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
191         ::close(fd);
192     }
193 #endif
194 };
195 
196 using unique_fd = unique_fd_impl<DefaultCloser>;
197 
198 #if !defined(_WIN32) && !defined(__TRUSTY__)
199 
200 // Inline functions, so that they can be used header-only.
201 
202 // See pipe(2).
203 // This helper hides the details of converting to unique_fd, and also hides the
204 // fact that macOS doesn't support O_CLOEXEC or O_NONBLOCK directly.
205 template <typename Closer>
206 inline bool Pipe(unique_fd_impl<Closer>* read,
207                  unique_fd_impl<Closer>* write,
208                  int flags = O_CLOEXEC) {
209     int pipefd[2];
210 
211 #if defined(__linux__)
212     if (pipe2(pipefd, flags) != 0) {
213         return false;
214     }
215 #else  // defined(__APPLE__)
216     if (flags & ~(O_CLOEXEC | O_NONBLOCK)) {
217         return false;
218     }
219     if (pipe(pipefd) != 0) {
220         return false;
221     }
222 
223     if (flags & O_CLOEXEC) {
224         if (fcntl(pipefd[0], F_SETFD, FD_CLOEXEC) != 0 ||
225             fcntl(pipefd[1], F_SETFD, FD_CLOEXEC) != 0) {
226             close(pipefd[0]);
227             close(pipefd[1]);
228             return false;
229         }
230     }
231     if (flags & O_NONBLOCK) {
232         if (fcntl(pipefd[0], F_SETFL, O_NONBLOCK) != 0 ||
233             fcntl(pipefd[1], F_SETFL, O_NONBLOCK) != 0) {
234             close(pipefd[0]);
235             close(pipefd[1]);
236             return false;
237         }
238     }
239 #endif
240 
241     read->reset(pipefd[0]);
242     write->reset(pipefd[1]);
243     return true;
244 }
245 
246 // See socketpair(2).
247 // This helper hides the details of converting to unique_fd.
248 template <typename Closer>
Socketpair(int domain,int type,int protocol,unique_fd_impl<Closer> * left,unique_fd_impl<Closer> * right)249 inline bool Socketpair(int domain,
250                        int type,
251                        int protocol,
252                        unique_fd_impl<Closer>* left,
253                        unique_fd_impl<Closer>* right) {
254     int sockfd[2];
255     if (socketpair(domain, type, protocol, sockfd) != 0) {
256         return false;
257     }
258     left->reset(sockfd[0]);
259     right->reset(sockfd[1]);
260     return true;
261 }
262 
263 // See socketpair(2).
264 // This helper hides the details of converting to unique_fd.
265 template <typename Closer>
Socketpair(int type,unique_fd_impl<Closer> * left,unique_fd_impl<Closer> * right)266 inline bool Socketpair(int type,
267                        unique_fd_impl<Closer>* left,
268                        unique_fd_impl<Closer>* right) {
269     return Socketpair(AF_UNIX, type, 0, left, right);
270 }
271 
272 // See fdopen(3).
273 // Using fdopen with unique_fd correctly is more annoying than it should be,
274 // because fdopen doesn't close the file descriptor received upon failure.
Fdopen(unique_fd && ufd,const char * mode)275 inline FILE* Fdopen(unique_fd&& ufd, const char* mode) {
276     int fd = ufd.release();
277     FILE* file = fdopen(fd, mode);
278     if (!file) {
279         close(fd);
280     }
281     return file;
282 }
283 
284 // See fdopendir(3).
285 // Using fdopendir with unique_fd correctly is more annoying than it should be,
286 // because fdopen doesn't close the file descriptor received upon failure.
Fdopendir(unique_fd && ufd)287 inline DIR* Fdopendir(unique_fd&& ufd) {
288     int fd = ufd.release();
289     DIR* dir = fdopendir(fd);
290     if (dir == nullptr) {
291         close(fd);
292     }
293     return dir;
294 }
295 
296 #endif  // !defined(_WIN32) && !defined(__TRUSTY__)
297 
298 // A wrapper type that can be implicitly constructed from either int or
299 // unique_fd. This supports cases where you don't actually own the file
300 // descriptor, and can't take ownership, but are temporarily acting as if
301 // you're the owner.
302 //
303 // One example would be a function that needs to also allow
304 // STDERR_FILENO, not just a newly-opened fd. Another example would be JNI code
305 // that's using a file descriptor that's actually owned by a
306 // ParcelFileDescriptor or whatever on the Java side, but where the JNI code
307 // would like to enforce this weaker sense of "temporary ownership".
308 //
309 // If you think of unique_fd as being like std::string in that represents
310 // ownership, borrowed_fd is like std::string_view (and int is like const
311 // char*).
312 struct borrowed_fd {
borrowed_fdborrowed_fd313     /* implicit */ borrowed_fd(int fd) : fd_(fd) {}  // NOLINT
314     template <typename T>
borrowed_fdborrowed_fd315     /* implicit */ borrowed_fd(const unique_fd_impl<T>& ufd)
316             : fd_(ufd.get()) {}  // NOLINT
317 
getborrowed_fd318     int get() const { return fd_; }
319 
320     bool operator>=(int rhs) const { return get() >= rhs; }
321     bool operator<(int rhs) const { return get() < rhs; }
322     bool operator==(int rhs) const { return get() == rhs; }
323     bool operator!=(int rhs) const { return get() != rhs; }
324 
325 private:
326     int fd_ = -1;
327 };
328 }  // namespace base
329 }  // namespace android
330 
331 template <typename T>
332 int close(const android::base::unique_fd_impl<T>&)
333         __attribute__((__unavailable__("close called on unique_fd")));
334 
335 template <typename T>
336 FILE* fdopen(const android::base::unique_fd_impl<T>&, const char* mode)
337         __attribute__((__unavailable__(
338                 "fdopen takes ownership of the fd passed in; either dup the "
339                 "unique_fd, or use android::base::Fdopen to pass ownership")));
340 
341 template <typename T>
342 DIR* fdopendir(const android::base::unique_fd_impl<T>&)
343         __attribute__((__unavailable__(
344                 "fdopendir takes ownership of the fd passed in; either dup the "
345                 "unique_fd, or use android::base::Fdopendir to pass ownership")));
346