blob: d8d46560876dfdfb442bd97c08fafb647b833a33 [file] [log] [blame]
Robert Sesek8225b7c2016-12-16 14:02:31 -05001/*
2 * Copyright (C) 2016 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 "fd_utils.h"
18
19#include <algorithm>
20
21#include <fcntl.h>
22#include <grp.h>
23#include <stdlib.h>
24#include <sys/socket.h>
25#include <sys/types.h>
26#include <sys/un.h>
27#include <unistd.h>
28
Narayan Kamath3879ecc2017-03-02 17:30:03 +000029#include <android-base/file.h>
Narayan Kamatha352d242017-03-02 14:44:45 +000030#include <android-base/logging.h>
Narayan Kamath3879ecc2017-03-02 17:30:03 +000031#include <android-base/stringprintf.h>
Robert Sesek8225b7c2016-12-16 14:02:31 -050032#include <android-base/strings.h>
Robert Sesek8225b7c2016-12-16 14:02:31 -050033
Robert Sesek54e387d2016-12-02 17:27:50 -050034// Static whitelist of open paths that the zygote is allowed to keep open.
Robert Sesek8225b7c2016-12-16 14:02:31 -050035static const char* kPathWhitelist[] = {
Adam Vartanian25095752019-01-08 11:00:40 +000036 "/apex/com.android.conscrypt/javalib/conscrypt.jar",
Dongwon Kang0d035532019-01-17 13:35:03 -080037 "/apex/com.android.media/javalib/updatable-media.jar",
Robert Sesek8225b7c2016-12-16 14:02:31 -050038 "/dev/null",
39 "/dev/socket/zygote",
40 "/dev/socket/zygote_secondary",
Chris Wailes7e797b62019-02-22 18:29:22 -080041 "/dev/socket/usap_pool_primary",
42 "/dev/socket/usap_pool_secondary",
Robert Sesek8225b7c2016-12-16 14:02:31 -050043 "/dev/socket/webview_zygote",
Florian Mayer6ce2d992018-10-16 14:30:02 +010044 "/dev/socket/heapprofd",
Robert Sesek8225b7c2016-12-16 14:02:31 -050045 "/sys/kernel/debug/tracing/trace_marker",
46 "/system/framework/framework-res.apk",
47 "/dev/urandom",
48 "/dev/ion",
49 "/dev/dri/renderD129", // Fixes b/31172436
50};
51
52static const char kFdPath[] = "/proc/self/fd";
53
54// static
Robert Sesek54e387d2016-12-02 17:27:50 -050055FileDescriptorWhitelist* FileDescriptorWhitelist::Get() {
56 if (instance_ == nullptr) {
57 instance_ = new FileDescriptorWhitelist();
58 }
59 return instance_;
60}
61
62bool FileDescriptorWhitelist::IsAllowed(const std::string& path) const {
63 // Check the static whitelist path.
64 for (const auto& whitelist_path : kPathWhitelist) {
65 if (path == whitelist_path)
66 return true;
67 }
68
69 // Check any paths added to the dynamic whitelist.
70 for (const auto& whitelist_path : whitelist_) {
71 if (path == whitelist_path)
72 return true;
73 }
74
Nicolas Geoffrayfca69e92019-01-22 20:56:44 +000075 // Framework jars are allowed.
Narayan Kamath3879ecc2017-03-02 17:30:03 +000076 static const char* kFrameworksPrefix = "/system/framework/";
77 static const char* kJarSuffix = ".jar";
78 if (android::base::StartsWith(path, kFrameworksPrefix)
79 && android::base::EndsWith(path, kJarSuffix)) {
Robert Sesek54e387d2016-12-02 17:27:50 -050080 return true;
81 }
82
Nicolas Geoffrayfca69e92019-01-22 20:56:44 +000083 // Jars from the runtime apex are allowed.
84 static const char* kRuntimeApexPrefix = "/apex/com.android.runtime/javalib/";
85 if (android::base::StartsWith(path, kRuntimeApexPrefix)
86 && android::base::EndsWith(path, kJarSuffix)) {
87 return true;
88 }
89
Robert Sesek54e387d2016-12-02 17:27:50 -050090 // Whitelist files needed for Runtime Resource Overlay, like these:
91 // /system/vendor/overlay/framework-res.apk
92 // /system/vendor/overlay-subdir/pg/framework-res.apk
93 // /vendor/overlay/framework-res.apk
94 // /vendor/overlay/PG/android-framework-runtime-resource-overlay.apk
95 // /data/resource-cache/system@vendor@overlay@framework-res.apk@idmap
96 // /data/resource-cache/system@vendor@overlay-subdir@pg@framework-res.apk@idmap
97 // See AssetManager.cpp for more details on overlay-subdir.
Narayan Kamath3879ecc2017-03-02 17:30:03 +000098 static const char* kOverlayDir = "/system/vendor/overlay/";
99 static const char* kVendorOverlayDir = "/vendor/overlay";
Mårten Kongstad06a1ac82018-09-20 13:09:47 +0200100 static const char* kVendorOverlaySubdir = "/system/vendor/overlay-subdir/";
Jaekyun Seok1713d9e2018-01-12 21:47:26 +0900101 static const char* kSystemProductOverlayDir = "/system/product/overlay/";
102 static const char* kProductOverlayDir = "/product/overlay";
Dario Freni4ce46792018-06-01 14:02:08 +0100103 static const char* kSystemProductServicesOverlayDir = "/system/product_services/overlay/";
104 static const char* kProductServicesOverlayDir = "/product_services/overlay";
Narayan Kamath3879ecc2017-03-02 17:30:03 +0000105 static const char* kApkSuffix = ".apk";
Robert Sesek54e387d2016-12-02 17:27:50 -0500106
Narayan Kamath3879ecc2017-03-02 17:30:03 +0000107 if ((android::base::StartsWith(path, kOverlayDir)
Mårten Kongstad06a1ac82018-09-20 13:09:47 +0200108 || android::base::StartsWith(path, kVendorOverlaySubdir)
Jaekyun Seok1713d9e2018-01-12 21:47:26 +0900109 || android::base::StartsWith(path, kVendorOverlayDir)
110 || android::base::StartsWith(path, kSystemProductOverlayDir)
Dario Freni4ce46792018-06-01 14:02:08 +0100111 || android::base::StartsWith(path, kProductOverlayDir)
112 || android::base::StartsWith(path, kSystemProductServicesOverlayDir)
113 || android::base::StartsWith(path, kProductServicesOverlayDir))
Narayan Kamath3879ecc2017-03-02 17:30:03 +0000114 && android::base::EndsWith(path, kApkSuffix)
Robert Sesek54e387d2016-12-02 17:27:50 -0500115 && path.find("/../") == std::string::npos) {
116 return true;
117 }
118
Narayan Kamath3879ecc2017-03-02 17:30:03 +0000119 static const char* kOverlayIdmapPrefix = "/data/resource-cache/";
120 static const char* kOverlayIdmapSuffix = ".apk@idmap";
121 if (android::base::StartsWith(path, kOverlayIdmapPrefix)
122 && android::base::EndsWith(path, kOverlayIdmapSuffix)
Robert Sesek54e387d2016-12-02 17:27:50 -0500123 && path.find("/../") == std::string::npos) {
124 return true;
125 }
126
127 // All regular files that are placed under this path are whitelisted automatically.
Narayan Kamath3879ecc2017-03-02 17:30:03 +0000128 static const char* kZygoteWhitelistPath = "/vendor/zygote_whitelist/";
129 if (android::base::StartsWith(path, kZygoteWhitelistPath)
130 && path.find("/../") == std::string::npos) {
Robert Sesek54e387d2016-12-02 17:27:50 -0500131 return true;
132 }
133
134 return false;
135}
136
137FileDescriptorWhitelist::FileDescriptorWhitelist()
138 : whitelist_() {
139}
140
Robert Sesek54e387d2016-12-02 17:27:50 -0500141FileDescriptorWhitelist* FileDescriptorWhitelist::instance_ = nullptr;
142
Andreas Gampe183a5d32018-03-12 14:53:34 -0700143// Keeps track of all relevant information (flags, offset etc.) of an
144// open zygote file descriptor.
145class FileDescriptorInfo {
146 public:
Chris Wailesaa1c9622019-01-10 16:55:32 -0800147 // Create a FileDescriptorInfo for a given file descriptor.
148 static FileDescriptorInfo* CreateFromFd(int fd, fail_fn_t fail_fn);
Andreas Gampe183a5d32018-03-12 14:53:34 -0700149
150 // Checks whether the file descriptor associated with this object
151 // refers to the same description.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800152 bool RefersToSameFile() const;
Andreas Gampe183a5d32018-03-12 14:53:34 -0700153
Chris Wailesaa1c9622019-01-10 16:55:32 -0800154 void ReopenOrDetach(fail_fn_t fail_fn) const;
Andreas Gampe183a5d32018-03-12 14:53:34 -0700155
156 const int fd;
157 const struct stat stat;
158 const std::string file_path;
159 const int open_flags;
160 const int fd_flags;
161 const int fs_flags;
162 const off_t offset;
163 const bool is_sock;
164
165 private:
Chih-Hung Hsieh0727be12018-12-20 13:43:46 -0800166 explicit FileDescriptorInfo(int fd);
Andreas Gampe183a5d32018-03-12 14:53:34 -0700167
168 FileDescriptorInfo(struct stat stat, const std::string& file_path, int fd, int open_flags,
169 int fd_flags, int fs_flags, off_t offset);
170
171 // Returns the locally-bound name of the socket |fd|. Returns true
172 // iff. all of the following hold :
173 //
174 // - the socket's sa_family is AF_UNIX.
175 // - the length of the path is greater than zero (i.e, not an unnamed socket).
176 // - the first byte of the path isn't zero (i.e, not a socket with an abstract
177 // address).
178 static bool GetSocketName(const int fd, std::string* result);
179
Chris Wailesaa1c9622019-01-10 16:55:32 -0800180 void DetachSocket(fail_fn_t fail_fn) const;
Andreas Gampe183a5d32018-03-12 14:53:34 -0700181
182 DISALLOW_COPY_AND_ASSIGN(FileDescriptorInfo);
183};
184
Robert Sesek54e387d2016-12-02 17:27:50 -0500185// static
Chris Wailesaa1c9622019-01-10 16:55:32 -0800186FileDescriptorInfo* FileDescriptorInfo::CreateFromFd(int fd, fail_fn_t fail_fn) {
Robert Sesek8225b7c2016-12-16 14:02:31 -0500187 struct stat f_stat;
188 // This should never happen; the zygote should always have the right set
189 // of permissions required to stat all its open files.
190 if (TEMP_FAILURE_RETRY(fstat(fd, &f_stat)) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800191 fail_fn(android::base::StringPrintf("Unable to stat %d", fd));
Robert Sesek8225b7c2016-12-16 14:02:31 -0500192 }
193
Robert Sesek54e387d2016-12-02 17:27:50 -0500194 const FileDescriptorWhitelist* whitelist = FileDescriptorWhitelist::Get();
195
Robert Sesek8225b7c2016-12-16 14:02:31 -0500196 if (S_ISSOCK(f_stat.st_mode)) {
197 std::string socket_name;
198 if (!GetSocketName(fd, &socket_name)) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800199 fail_fn("Unable to get socket name");
Robert Sesek8225b7c2016-12-16 14:02:31 -0500200 }
201
Robert Sesek54e387d2016-12-02 17:27:50 -0500202 if (!whitelist->IsAllowed(socket_name)) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800203 fail_fn(android::base::StringPrintf("Socket name not whitelisted : %s (fd=%d)",
204 socket_name.c_str(),
205 fd));
Robert Sesek8225b7c2016-12-16 14:02:31 -0500206 }
207
208 return new FileDescriptorInfo(fd);
209 }
210
211 // We only handle whitelisted regular files and character devices. Whitelisted
212 // character devices must provide a guarantee of sensible behaviour when
213 // reopened.
214 //
215 // S_ISDIR : Not supported. (We could if we wanted to, but it's unused).
216 // S_ISLINK : Not supported.
217 // S_ISBLK : Not supported.
Chris Wailes7e797b62019-02-22 18:29:22 -0800218 // S_ISFIFO : Not supported. Note that the Zygote and USAPs use pipes to
Chris Wailesaa1c9622019-01-10 16:55:32 -0800219 // communicate with the child processes across forks but those should have been
220 // added to the redirection exemption list.
Robert Sesek8225b7c2016-12-16 14:02:31 -0500221 if (!S_ISCHR(f_stat.st_mode) && !S_ISREG(f_stat.st_mode)) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800222 std::string mode = "Unknown";
223
224 if (S_ISDIR(f_stat.st_mode)) {
225 mode = "DIR";
226 } else if (S_ISLNK(f_stat.st_mode)) {
227 mode = "LINK";
228 } else if (S_ISBLK(f_stat.st_mode)) {
229 mode = "BLOCK";
230 } else if (S_ISFIFO(f_stat.st_mode)) {
231 mode = "FIFO";
232 }
233
234 fail_fn(android::base::StringPrintf("Unsupported st_mode for FD %d: %s", fd, mode.c_str()));
Robert Sesek8225b7c2016-12-16 14:02:31 -0500235 }
236
237 std::string file_path;
Narayan Kamath3879ecc2017-03-02 17:30:03 +0000238 const std::string fd_path = android::base::StringPrintf("/proc/self/fd/%d", fd);
239 if (!android::base::Readlink(fd_path, &file_path)) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800240 fail_fn(android::base::StringPrintf("Could not read fd link %s: %s",
241 fd_path.c_str(),
242 strerror(errno)));
Robert Sesek8225b7c2016-12-16 14:02:31 -0500243 }
244
Robert Sesek54e387d2016-12-02 17:27:50 -0500245 if (!whitelist->IsAllowed(file_path)) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800246 fail_fn(std::string("Not whitelisted : ").append(file_path));
Robert Sesek8225b7c2016-12-16 14:02:31 -0500247 }
248
249 // File descriptor flags : currently on FD_CLOEXEC. We can set these
250 // using F_SETFD - we're single threaded at this point of execution so
251 // there won't be any races.
252 const int fd_flags = TEMP_FAILURE_RETRY(fcntl(fd, F_GETFD));
253 if (fd_flags == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800254 fail_fn(android::base::StringPrintf("Failed fcntl(%d, F_GETFD) (%s): %s",
255 fd,
256 file_path.c_str(),
257 strerror(errno)));
Robert Sesek8225b7c2016-12-16 14:02:31 -0500258 }
259
260 // File status flags :
261 // - File access mode : (O_RDONLY, O_WRONLY...) we'll pass these through
262 // to the open() call.
263 //
264 // - File creation flags : (O_CREAT, O_EXCL...) - there's not much we can
265 // do about these, since the file has already been created. We shall ignore
266 // them here.
267 //
268 // - Other flags : We'll have to set these via F_SETFL. On linux, F_SETFL
269 // can only set O_APPEND, O_ASYNC, O_DIRECT, O_NOATIME, and O_NONBLOCK.
270 // In particular, it can't set O_SYNC and O_DSYNC. We'll have to test for
271 // their presence and pass them in to open().
272 int fs_flags = TEMP_FAILURE_RETRY(fcntl(fd, F_GETFL));
273 if (fs_flags == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800274 fail_fn(android::base::StringPrintf("Failed fcntl(%d, F_GETFL) (%s): %s",
275 fd,
276 file_path.c_str(),
277 strerror(errno)));
Robert Sesek8225b7c2016-12-16 14:02:31 -0500278 }
279
280 // File offset : Ignore the offset for non seekable files.
281 const off_t offset = TEMP_FAILURE_RETRY(lseek64(fd, 0, SEEK_CUR));
282
283 // We pass the flags that open accepts to open, and use F_SETFL for
284 // the rest of them.
285 static const int kOpenFlags = (O_RDONLY | O_WRONLY | O_RDWR | O_DSYNC | O_SYNC);
286 int open_flags = fs_flags & (kOpenFlags);
287 fs_flags = fs_flags & (~(kOpenFlags));
288
289 return new FileDescriptorInfo(f_stat, file_path, fd, open_flags, fd_flags, fs_flags, offset);
290}
291
Chris Wailesaa1c9622019-01-10 16:55:32 -0800292bool FileDescriptorInfo::RefersToSameFile() const {
Robert Sesek8225b7c2016-12-16 14:02:31 -0500293 struct stat f_stat;
294 if (TEMP_FAILURE_RETRY(fstat(fd, &f_stat)) == -1) {
Narayan Kamatha352d242017-03-02 14:44:45 +0000295 PLOG(ERROR) << "Unable to restat fd " << fd;
Robert Sesek8225b7c2016-12-16 14:02:31 -0500296 return false;
297 }
298
299 return f_stat.st_ino == stat.st_ino && f_stat.st_dev == stat.st_dev;
300}
301
Chris Wailesaa1c9622019-01-10 16:55:32 -0800302void FileDescriptorInfo::ReopenOrDetach(fail_fn_t fail_fn) const {
Robert Sesek8225b7c2016-12-16 14:02:31 -0500303 if (is_sock) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800304 return DetachSocket(fail_fn);
Robert Sesek8225b7c2016-12-16 14:02:31 -0500305 }
306
307 // NOTE: This might happen if the file was unlinked after being opened.
308 // It's a common pattern in the case of temporary files and the like but
309 // we should not allow such usage from the zygote.
310 const int new_fd = TEMP_FAILURE_RETRY(open(file_path.c_str(), open_flags));
311
312 if (new_fd == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800313 fail_fn(android::base::StringPrintf("Failed open(%s, %i): %s",
314 file_path.c_str(),
315 open_flags,
316 strerror(errno)));
Robert Sesek8225b7c2016-12-16 14:02:31 -0500317 }
318
319 if (TEMP_FAILURE_RETRY(fcntl(new_fd, F_SETFD, fd_flags)) == -1) {
320 close(new_fd);
Chris Wailesaa1c9622019-01-10 16:55:32 -0800321 fail_fn(android::base::StringPrintf("Failed fcntl(%d, F_SETFD, %d) (%s): %s",
322 new_fd,
323 fd_flags,
324 file_path.c_str(),
325 strerror(errno)));
Robert Sesek8225b7c2016-12-16 14:02:31 -0500326 }
327
328 if (TEMP_FAILURE_RETRY(fcntl(new_fd, F_SETFL, fs_flags)) == -1) {
329 close(new_fd);
Chris Wailesaa1c9622019-01-10 16:55:32 -0800330 fail_fn(android::base::StringPrintf("Failed fcntl(%d, F_SETFL, %d) (%s): %s",
331 new_fd,
332 fs_flags,
333 file_path.c_str(),
334 strerror(errno)));
Robert Sesek8225b7c2016-12-16 14:02:31 -0500335 }
336
337 if (offset != -1 && TEMP_FAILURE_RETRY(lseek64(new_fd, offset, SEEK_SET)) == -1) {
338 close(new_fd);
Chris Wailesaa1c9622019-01-10 16:55:32 -0800339 fail_fn(android::base::StringPrintf("Failed lseek64(%d, SEEK_SET) (%s): %s",
340 new_fd,
341 file_path.c_str(),
342 strerror(errno)));
Robert Sesek8225b7c2016-12-16 14:02:31 -0500343 }
344
Chris Wailesaa1c9622019-01-10 16:55:32 -0800345 int dup_flags = (fd_flags & FD_CLOEXEC) ? O_CLOEXEC : 0;
346 if (TEMP_FAILURE_RETRY(dup3(new_fd, fd, dup_flags)) == -1) {
Robert Sesek8225b7c2016-12-16 14:02:31 -0500347 close(new_fd);
Chris Wailesaa1c9622019-01-10 16:55:32 -0800348 fail_fn(android::base::StringPrintf("Failed dup3(%d, %d, %d) (%s): %s",
349 fd,
350 new_fd,
351 dup_flags,
352 file_path.c_str(),
353 strerror(errno)));
Robert Sesek8225b7c2016-12-16 14:02:31 -0500354 }
355
356 close(new_fd);
Robert Sesek8225b7c2016-12-16 14:02:31 -0500357}
358
359FileDescriptorInfo::FileDescriptorInfo(int fd) :
360 fd(fd),
361 stat(),
362 open_flags(0),
363 fd_flags(0),
364 fs_flags(0),
365 offset(0),
366 is_sock(true) {
367}
368
369FileDescriptorInfo::FileDescriptorInfo(struct stat stat, const std::string& file_path,
370 int fd, int open_flags, int fd_flags, int fs_flags,
371 off_t offset) :
372 fd(fd),
373 stat(stat),
374 file_path(file_path),
375 open_flags(open_flags),
376 fd_flags(fd_flags),
377 fs_flags(fs_flags),
378 offset(offset),
379 is_sock(false) {
380}
381
Robert Sesek8225b7c2016-12-16 14:02:31 -0500382bool FileDescriptorInfo::GetSocketName(const int fd, std::string* result) {
383 sockaddr_storage ss;
384 sockaddr* addr = reinterpret_cast<sockaddr*>(&ss);
385 socklen_t addr_len = sizeof(ss);
386
387 if (TEMP_FAILURE_RETRY(getsockname(fd, addr, &addr_len)) == -1) {
Narayan Kamath84b55112017-03-02 17:04:08 +0000388 PLOG(ERROR) << "Failed getsockname(" << fd << ")";
Robert Sesek8225b7c2016-12-16 14:02:31 -0500389 return false;
390 }
391
392 if (addr->sa_family != AF_UNIX) {
Narayan Kamath84b55112017-03-02 17:04:08 +0000393 LOG(ERROR) << "Unsupported socket (fd=" << fd << ") with family " << addr->sa_family;
Robert Sesek8225b7c2016-12-16 14:02:31 -0500394 return false;
395 }
396
397 const sockaddr_un* unix_addr = reinterpret_cast<const sockaddr_un*>(&ss);
398
399 size_t path_len = addr_len - offsetof(struct sockaddr_un, sun_path);
400 // This is an unnamed local socket, we do not accept it.
401 if (path_len == 0) {
Narayan Kamath84b55112017-03-02 17:04:08 +0000402 LOG(ERROR) << "Unsupported AF_UNIX socket (fd=" << fd << ") with empty path.";
Robert Sesek8225b7c2016-12-16 14:02:31 -0500403 return false;
404 }
405
Robert Sesekd0a190df2018-02-12 18:46:01 -0500406 // This is a local socket with an abstract address. Remove the leading NUL byte and
407 // add a human-readable "ABSTRACT/" prefix.
Robert Sesek8225b7c2016-12-16 14:02:31 -0500408 if (unix_addr->sun_path[0] == '\0') {
Robert Sesekd0a190df2018-02-12 18:46:01 -0500409 *result = "ABSTRACT/";
410 result->append(&unix_addr->sun_path[1], path_len - 1);
411 return true;
Robert Sesek8225b7c2016-12-16 14:02:31 -0500412 }
413
414 // If we're here, sun_path must refer to a null terminated filesystem
415 // pathname (man 7 unix). Remove the terminator before assigning it to an
416 // std::string.
417 if (unix_addr->sun_path[path_len - 1] == '\0') {
418 --path_len;
419 }
420
421 result->assign(unix_addr->sun_path, path_len);
422 return true;
423}
424
Chris Wailesaa1c9622019-01-10 16:55:32 -0800425void FileDescriptorInfo::DetachSocket(fail_fn_t fail_fn) const {
Nick Kralevich0361ce12019-01-25 10:08:58 -0800426 const int dev_null_fd = open("/dev/null", O_RDWR | O_CLOEXEC);
Robert Sesek8225b7c2016-12-16 14:02:31 -0500427 if (dev_null_fd < 0) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800428 fail_fn(std::string("Failed to open /dev/null: ").append(strerror(errno)));
Robert Sesek8225b7c2016-12-16 14:02:31 -0500429 }
430
Nick Kralevich0361ce12019-01-25 10:08:58 -0800431 if (dup3(dev_null_fd, fd, O_CLOEXEC) == -1) {
432 fail_fn(android::base::StringPrintf("Failed dup3 on socket descriptor %d: %s",
Chris Wailesaa1c9622019-01-10 16:55:32 -0800433 fd,
434 strerror(errno)));
Robert Sesek8225b7c2016-12-16 14:02:31 -0500435 }
436
437 if (close(dev_null_fd) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800438 fail_fn(android::base::StringPrintf("Failed close(%d): %s", dev_null_fd, strerror(errno)));
Robert Sesek8225b7c2016-12-16 14:02:31 -0500439 }
Robert Sesek8225b7c2016-12-16 14:02:31 -0500440}
441
442// static
Andreas Gampe183a5d32018-03-12 14:53:34 -0700443FileDescriptorTable* FileDescriptorTable::Create(const std::vector<int>& fds_to_ignore,
Chris Wailesaa1c9622019-01-10 16:55:32 -0800444 fail_fn_t fail_fn) {
445 DIR* proc_fd_dir = opendir(kFdPath);
446 if (proc_fd_dir == nullptr) {
447 fail_fn(std::string("Unable to open directory ").append(kFdPath));
Robert Sesek8225b7c2016-12-16 14:02:31 -0500448 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800449
450 int dir_fd = dirfd(proc_fd_dir);
451 dirent* dir_entry;
Robert Sesek8225b7c2016-12-16 14:02:31 -0500452
453 std::unordered_map<int, FileDescriptorInfo*> open_fd_map;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800454 while ((dir_entry = readdir(proc_fd_dir)) != nullptr) {
455 const int fd = ParseFd(dir_entry, dir_fd);
Robert Sesek8225b7c2016-12-16 14:02:31 -0500456 if (fd == -1) {
457 continue;
458 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800459
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800460 if (std::find(fds_to_ignore.begin(), fds_to_ignore.end(), fd) != fds_to_ignore.end()) {
Narayan Kamath84b55112017-03-02 17:04:08 +0000461 LOG(INFO) << "Ignoring open file descriptor " << fd;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800462 continue;
463 }
Robert Sesek8225b7c2016-12-16 14:02:31 -0500464
Chris Wailesaa1c9622019-01-10 16:55:32 -0800465 open_fd_map[fd] = FileDescriptorInfo::CreateFromFd(fd, fail_fn);
Robert Sesek8225b7c2016-12-16 14:02:31 -0500466 }
467
Chris Wailesaa1c9622019-01-10 16:55:32 -0800468 if (closedir(proc_fd_dir) == -1) {
469 fail_fn("Unable to close directory");
Robert Sesek8225b7c2016-12-16 14:02:31 -0500470 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800471
Robert Sesek8225b7c2016-12-16 14:02:31 -0500472 return new FileDescriptorTable(open_fd_map);
473}
474
Chris Wailesaa1c9622019-01-10 16:55:32 -0800475void FileDescriptorTable::Restat(const std::vector<int>& fds_to_ignore, fail_fn_t fail_fn) {
Robert Sesek8225b7c2016-12-16 14:02:31 -0500476 std::set<int> open_fds;
477
478 // First get the list of open descriptors.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800479 DIR* proc_fd_dir = opendir(kFdPath);
480 if (proc_fd_dir == nullptr) {
481 fail_fn(android::base::StringPrintf("Unable to open directory %s: %s",
482 kFdPath,
483 strerror(errno)));
Robert Sesek8225b7c2016-12-16 14:02:31 -0500484 }
485
Chris Wailesaa1c9622019-01-10 16:55:32 -0800486 int dir_fd = dirfd(proc_fd_dir);
487 dirent* dir_entry;
488 while ((dir_entry = readdir(proc_fd_dir)) != nullptr) {
489 const int fd = ParseFd(dir_entry, dir_fd);
Robert Sesek8225b7c2016-12-16 14:02:31 -0500490 if (fd == -1) {
491 continue;
492 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800493
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800494 if (std::find(fds_to_ignore.begin(), fds_to_ignore.end(), fd) != fds_to_ignore.end()) {
Narayan Kamath84b55112017-03-02 17:04:08 +0000495 LOG(INFO) << "Ignoring open file descriptor " << fd;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800496 continue;
497 }
Robert Sesek8225b7c2016-12-16 14:02:31 -0500498
499 open_fds.insert(fd);
500 }
501
Chris Wailesaa1c9622019-01-10 16:55:32 -0800502 if (closedir(proc_fd_dir) == -1) {
503 fail_fn(android::base::StringPrintf("Unable to close directory: %s", strerror(errno)));
Robert Sesek8225b7c2016-12-16 14:02:31 -0500504 }
505
Chris Wailesaa1c9622019-01-10 16:55:32 -0800506 RestatInternal(open_fds, fail_fn);
Robert Sesek8225b7c2016-12-16 14:02:31 -0500507}
508
Chris Wailesaa1c9622019-01-10 16:55:32 -0800509// Reopens all file descriptors that are contained in the table.
510void FileDescriptorTable::ReopenOrDetach(fail_fn_t fail_fn) {
Robert Sesek8225b7c2016-12-16 14:02:31 -0500511 std::unordered_map<int, FileDescriptorInfo*>::const_iterator it;
512 for (it = open_fd_map_.begin(); it != open_fd_map_.end(); ++it) {
513 const FileDescriptorInfo* info = it->second;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800514 if (info == nullptr) {
515 return;
516 } else {
517 info->ReopenOrDetach(fail_fn);
Robert Sesek8225b7c2016-12-16 14:02:31 -0500518 }
519 }
Robert Sesek8225b7c2016-12-16 14:02:31 -0500520}
521
522FileDescriptorTable::FileDescriptorTable(
523 const std::unordered_map<int, FileDescriptorInfo*>& map)
524 : open_fd_map_(map) {
525}
526
Chris Wailesaa1c9622019-01-10 16:55:32 -0800527void FileDescriptorTable::RestatInternal(std::set<int>& open_fds, fail_fn_t fail_fn) {
Robert Sesek8225b7c2016-12-16 14:02:31 -0500528 // Iterate through the list of file descriptors we've already recorded
529 // and check whether :
530 //
531 // (a) they continue to be open.
532 // (b) they refer to the same file.
Andreas Gampe183a5d32018-03-12 14:53:34 -0700533 //
534 // We'll only store the last error message.
Robert Sesek8225b7c2016-12-16 14:02:31 -0500535 std::unordered_map<int, FileDescriptorInfo*>::iterator it = open_fd_map_.begin();
536 while (it != open_fd_map_.end()) {
537 std::set<int>::const_iterator element = open_fds.find(it->first);
538 if (element == open_fds.end()) {
539 // The entry from the file descriptor table is no longer in the list
540 // of open files. We warn about this condition and remove it from
541 // the list of FDs under consideration.
542 //
543 // TODO(narayan): This will be an error in a future android release.
544 // error = true;
545 // ALOGW("Zygote closed file descriptor %d.", it->first);
546 it = open_fd_map_.erase(it);
547 } else {
548 // The entry from the file descriptor table is still open. Restat
549 // it and check whether it refers to the same file.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800550 if (!it->second->RefersToSameFile()) {
Robert Sesek8225b7c2016-12-16 14:02:31 -0500551 // The file descriptor refers to a different description. We must
552 // update our entry in the table.
553 delete it->second;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800554 it->second = FileDescriptorInfo::CreateFromFd(*element, fail_fn);
Robert Sesek8225b7c2016-12-16 14:02:31 -0500555 } else {
556 // It's the same file. Nothing to do here. Move on to the next open
557 // FD.
Robert Sesek8225b7c2016-12-16 14:02:31 -0500558 }
559
Chris Wailesaa1c9622019-01-10 16:55:32 -0800560 ++it;
561
Robert Sesek8225b7c2016-12-16 14:02:31 -0500562 // Finally, remove the FD from the set of open_fds. We do this last because
563 // |element| will not remain valid after a call to erase.
564 open_fds.erase(element);
565 }
566 }
567
568 if (open_fds.size() > 0) {
569 // The zygote has opened new file descriptors since our last inspection.
570 // We warn about this condition and add them to our table.
571 //
572 // TODO(narayan): This will be an error in a future android release.
573 // error = true;
574 // ALOGW("Zygote opened %zd new file descriptor(s).", open_fds.size());
575
576 // TODO(narayan): This code will be removed in a future android release.
577 std::set<int>::const_iterator it;
578 for (it = open_fds.begin(); it != open_fds.end(); ++it) {
579 const int fd = (*it);
Chris Wailesaa1c9622019-01-10 16:55:32 -0800580 open_fd_map_[fd] = FileDescriptorInfo::CreateFromFd(fd, fail_fn);
Robert Sesek8225b7c2016-12-16 14:02:31 -0500581 }
582 }
Robert Sesek8225b7c2016-12-16 14:02:31 -0500583}
584
585// static
Chris Wailesaa1c9622019-01-10 16:55:32 -0800586int FileDescriptorTable::ParseFd(dirent* dir_entry, int dir_fd) {
Robert Sesek8225b7c2016-12-16 14:02:31 -0500587 char* end;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800588 const int fd = strtol(dir_entry->d_name, &end, 10);
Robert Sesek8225b7c2016-12-16 14:02:31 -0500589 if ((*end) != '\0') {
590 return -1;
591 }
592
593 // Don't bother with the standard input/output/error, they're handled
594 // specially post-fork anyway.
595 if (fd <= STDERR_FILENO || fd == dir_fd) {
596 return -1;
597 }
598
599 return fd;
600}