blob: 80bb44dce9092d5f3aa3d7ef0ab240d317a05972 [file] [log] [blame]
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001/* Authors: Gregory P. Smith & Jeffrey Yasskin */
2#include "Python.h"
Victor Stinner5572ba72011-05-26 14:10:08 +02003#if defined(HAVE_PIPE2) && !defined(_GNU_SOURCE)
4# define _GNU_SOURCE
Gregory P. Smith51ee2702010-12-13 07:59:39 +00005#endif
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00006#include <unistd.h>
Gregory P. Smith51ee2702010-12-13 07:59:39 +00007#include <fcntl.h>
Gregory P. Smith8facece2012-01-21 14:01:08 -08008#ifdef HAVE_SYS_TYPES_H
9#include <sys/types.h>
10#endif
Gregory P. Smithf3751ef2019-10-12 13:24:56 -070011#if defined(HAVE_SYS_STAT_H)
Gregory P. Smith4842efc2012-01-21 21:01:24 -080012#include <sys/stat.h>
13#endif
Gregory P. Smith8facece2012-01-21 14:01:08 -080014#ifdef HAVE_SYS_SYSCALL_H
15#include <sys/syscall.h>
16#endif
Gregory P. Smithf9681772015-04-25 23:43:34 -070017#if defined(HAVE_SYS_RESOURCE_H)
18#include <sys/resource.h>
19#endif
Gregory P. Smith8facece2012-01-21 14:01:08 -080020#ifdef HAVE_DIRENT_H
21#include <dirent.h>
22#endif
Patrick McLean2b2ead72019-09-12 10:15:44 -070023#ifdef HAVE_GRP_H
24#include <grp.h>
25#endif /* HAVE_GRP_H */
26
27#include "posixmodule.h"
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000028
Gregory P. Smith3015fb82018-11-12 22:01:22 -080029#ifdef _Py_MEMORY_SANITIZER
Gregory P. Smith1584a002018-11-12 12:07:14 -080030# include <sanitizer/msan_interface.h>
31#endif
32
Xavier de Gayec716f182016-06-15 11:35:29 +020033#if defined(__ANDROID__) && __ANDROID_API__ < 21 && !defined(SYS_getdents64)
Gregory P. Smithefeb9da2014-04-14 13:31:21 -070034# include <sys/linux-syscalls.h>
35# define SYS_getdents64 __NR_getdents64
36#endif
37
Jakub Kulík6f9bc722018-12-31 03:16:40 +010038#if defined(__sun) && defined(__SVR4)
Gregory P. Smithe3f78482012-01-21 15:16:17 -080039/* readdir64 is used to work around Solaris 9 bug 6395699. */
40# define readdir readdir64
41# define dirent dirent64
42# if !defined(HAVE_DIRFD)
Gregory P. Smith8facece2012-01-21 14:01:08 -080043/* Some versions of Solaris lack dirfd(). */
Gregory P. Smithe9b7cab2012-01-21 15:19:11 -080044# define dirfd(dirp) ((dirp)->dd_fd)
Gregory P. Smithe3f78482012-01-21 15:16:17 -080045# define HAVE_DIRFD
Gregory P. Smithe3f78482012-01-21 15:16:17 -080046# endif
Gregory P. Smith8facece2012-01-21 14:01:08 -080047#endif
48
Gregory P. Smith4842efc2012-01-21 21:01:24 -080049#if defined(__FreeBSD__) || (defined(__APPLE__) && defined(__MACH__))
50# define FD_DIR "/dev/fd"
51#else
52# define FD_DIR "/proc/self/fd"
53#endif
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000054
Patrick McLean2b2ead72019-09-12 10:15:44 -070055#ifdef NGROUPS_MAX
56#define MAX_GROUPS NGROUPS_MAX
57#else
58#define MAX_GROUPS 64
59#endif
60
Victor Stinnerdaf45552013-08-28 00:53:59 +020061#define POSIX_CALL(call) do { if ((call) == -1) goto error; } while (0)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000062
Dino Viehland5a7d2e12019-09-10 12:01:20 +010063typedef struct {
64 PyObject* disable;
65 PyObject* enable;
66 PyObject* isenabled;
67} _posixsubprocessstate;
68
69static struct PyModuleDef _posixsubprocessmodule;
70
71#define _posixsubprocessstate(o) ((_posixsubprocessstate *)PyModule_GetState(o))
72#define _posixsubprocessstate_global _posixsubprocessstate(PyState_FindModule(&_posixsubprocessmodule))
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000073
Martin Panterafdd5132015-11-30 02:21:41 +000074/* If gc was disabled, call gc.enable(). Return 0 on success. */
Benjamin Peterson91eef982012-01-22 20:04:46 -050075static int
Martin Panterafdd5132015-11-30 02:21:41 +000076_enable_gc(int need_to_reenable_gc, PyObject *gc_module)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000077{
78 PyObject *result;
Martin Panterafdd5132015-11-30 02:21:41 +000079 PyObject *exctype, *val, *tb;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020080
Martin Panterafdd5132015-11-30 02:21:41 +000081 if (need_to_reenable_gc) {
82 PyErr_Fetch(&exctype, &val, &tb);
Dino Viehland5a7d2e12019-09-10 12:01:20 +010083 result = _PyObject_CallMethodNoArgs(
84 gc_module, _posixsubprocessstate_global->enable);
Martin Panterafdd5132015-11-30 02:21:41 +000085 if (exctype != NULL) {
86 PyErr_Restore(exctype, val, tb);
87 }
88 if (result == NULL) {
89 return 1;
90 }
91 Py_DECREF(result);
92 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000093 return 0;
94}
95
96
Gregory P. Smith8facece2012-01-21 14:01:08 -080097/* Convert ASCII to a positive int, no libc call. no overflow. -1 on error. */
Benjamin Peterson91eef982012-01-22 20:04:46 -050098static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020099_pos_int_from_ascii(const char *name)
Gregory P. Smith8facece2012-01-21 14:01:08 -0800100{
101 int num = 0;
102 while (*name >= '0' && *name <= '9') {
103 num = num * 10 + (*name - '0');
104 ++name;
105 }
106 if (*name)
107 return -1; /* Non digit found, not a number. */
108 return num;
109}
110
111
Gregory P. Smith4842efc2012-01-21 21:01:24 -0800112#if defined(__FreeBSD__)
113/* When /dev/fd isn't mounted it is often a static directory populated
114 * with 0 1 2 or entries for 0 .. 63 on FreeBSD, NetBSD and OpenBSD.
115 * NetBSD and OpenBSD have a /proc fs available (though not necessarily
116 * mounted) and do not have fdescfs for /dev/fd. MacOS X has a devfs
117 * that properly supports /dev/fd.
118 */
Benjamin Peterson91eef982012-01-22 20:04:46 -0500119static int
Ross Lagerwall7f4fdb22012-03-07 20:06:33 +0200120_is_fdescfs_mounted_on_dev_fd(void)
Gregory P. Smith4842efc2012-01-21 21:01:24 -0800121{
122 struct stat dev_stat;
123 struct stat dev_fd_stat;
124 if (stat("/dev", &dev_stat) != 0)
125 return 0;
126 if (stat(FD_DIR, &dev_fd_stat) != 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +0200127 return 0;
Gregory P. Smith4842efc2012-01-21 21:01:24 -0800128 if (dev_stat.st_dev == dev_fd_stat.st_dev)
129 return 0; /* / == /dev == /dev/fd means it is static. #fail */
130 return 1;
131}
132#endif
133
134
Gregory P. Smith8facece2012-01-21 14:01:08 -0800135/* Returns 1 if there is a problem with fd_sequence, 0 otherwise. */
Benjamin Peterson91eef982012-01-22 20:04:46 -0500136static int
137_sanity_check_python_fd_sequence(PyObject *fd_sequence)
Gregory P. Smith8facece2012-01-21 14:01:08 -0800138{
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300139 Py_ssize_t seq_idx;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800140 long prev_fd = -1;
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300141 for (seq_idx = 0; seq_idx < PyTuple_GET_SIZE(fd_sequence); ++seq_idx) {
142 PyObject* py_fd = PyTuple_GET_ITEM(fd_sequence, seq_idx);
143 long iter_fd;
144 if (!PyLong_Check(py_fd)) {
145 return 1;
146 }
147 iter_fd = PyLong_AsLong(py_fd);
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -0800148 if (iter_fd < 0 || iter_fd <= prev_fd || iter_fd > INT_MAX) {
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300149 /* Negative, overflow, unsorted, too big for a fd. */
Gregory P. Smith8facece2012-01-21 14:01:08 -0800150 return 1;
151 }
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -0800152 prev_fd = iter_fd;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800153 }
154 return 0;
155}
156
157
158/* Is fd found in the sorted Python Sequence? */
Benjamin Peterson91eef982012-01-22 20:04:46 -0500159static int
160_is_fd_in_sorted_fd_sequence(int fd, PyObject *fd_sequence)
Gregory P. Smith8facece2012-01-21 14:01:08 -0800161{
162 /* Binary search. */
163 Py_ssize_t search_min = 0;
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300164 Py_ssize_t search_max = PyTuple_GET_SIZE(fd_sequence) - 1;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800165 if (search_max < 0)
166 return 0;
167 do {
168 long middle = (search_min + search_max) / 2;
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300169 long middle_fd = PyLong_AsLong(PyTuple_GET_ITEM(fd_sequence, middle));
Gregory P. Smith8facece2012-01-21 14:01:08 -0800170 if (fd == middle_fd)
171 return 1;
172 if (fd > middle_fd)
173 search_min = middle + 1;
174 else
175 search_max = middle - 1;
176 } while (search_min <= search_max);
177 return 0;
178}
179
Victor Stinnerdaf45552013-08-28 00:53:59 +0200180static int
181make_inheritable(PyObject *py_fds_to_keep, int errpipe_write)
182{
183 Py_ssize_t i, len;
184
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300185 len = PyTuple_GET_SIZE(py_fds_to_keep);
Victor Stinnerdaf45552013-08-28 00:53:59 +0200186 for (i = 0; i < len; ++i) {
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300187 PyObject* fdobj = PyTuple_GET_ITEM(py_fds_to_keep, i);
Victor Stinnerdaf45552013-08-28 00:53:59 +0200188 long fd = PyLong_AsLong(fdobj);
189 assert(!PyErr_Occurred());
190 assert(0 <= fd && fd <= INT_MAX);
191 if (fd == errpipe_write) {
192 /* errpipe_write is part of py_fds_to_keep. It must be closed at
193 exec(), but kept open in the child process until exec() is
194 called. */
195 continue;
196 }
Alexey Izbyshevc1e46e92018-02-06 09:09:34 +0300197 if (_Py_set_inheritable_async_safe((int)fd, 1, NULL) < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +0200198 return -1;
199 }
200 return 0;
201}
202
Gregory P. Smith8facece2012-01-21 14:01:08 -0800203
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700204/* Get the maximum file descriptor that could be opened by this process.
205 * This function is async signal safe for use between fork() and exec().
206 */
207static long
208safe_get_max_fd(void)
209{
210 long local_max_fd;
211#if defined(__NetBSD__)
212 local_max_fd = fcntl(0, F_MAXFD);
213 if (local_max_fd >= 0)
214 return local_max_fd;
215#endif
Gregory P. Smithf9681772015-04-25 23:43:34 -0700216#if defined(HAVE_SYS_RESOURCE_H) && defined(__OpenBSD__)
217 struct rlimit rl;
218 /* Not on the POSIX async signal safe functions list but likely
219 * safe. TODO - Someone should audit OpenBSD to make sure. */
220 if (getrlimit(RLIMIT_NOFILE, &rl) >= 0)
221 return (long) rl.rlim_max;
222#endif
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700223#ifdef _SC_OPEN_MAX
224 local_max_fd = sysconf(_SC_OPEN_MAX);
225 if (local_max_fd == -1)
226#endif
227 local_max_fd = 256; /* Matches legacy Lib/subprocess.py behavior. */
228 return local_max_fd;
229}
230
231
232/* Close all file descriptors in the range from start_fd and higher
233 * except for those in py_fds_to_keep. If the range defined by
234 * [start_fd, safe_get_max_fd()) is large this will take a long
235 * time as it calls close() on EVERY possible fd.
236 *
237 * It isn't possible to know for sure what the max fd to go up to
238 * is for processes with the capability of raising their maximum.
Gregory P. Smith8facece2012-01-21 14:01:08 -0800239 */
Benjamin Peterson91eef982012-01-22 20:04:46 -0500240static void
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700241_close_fds_by_brute_force(long start_fd, PyObject *py_fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -0800242{
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700243 long end_fd = safe_get_max_fd();
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300244 Py_ssize_t num_fds_to_keep = PyTuple_GET_SIZE(py_fds_to_keep);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800245 Py_ssize_t keep_seq_idx;
246 int fd_num;
247 /* As py_fds_to_keep is sorted we can loop through the list closing
luzpaza5293b42017-11-05 07:37:50 -0600248 * fds in between any in the keep list falling within our range. */
Gregory P. Smith8facece2012-01-21 14:01:08 -0800249 for (keep_seq_idx = 0; keep_seq_idx < num_fds_to_keep; ++keep_seq_idx) {
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300250 PyObject* py_keep_fd = PyTuple_GET_ITEM(py_fds_to_keep, keep_seq_idx);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800251 int keep_fd = PyLong_AsLong(py_keep_fd);
252 if (keep_fd < start_fd)
253 continue;
254 for (fd_num = start_fd; fd_num < keep_fd; ++fd_num) {
Victor Stinnere7c74922015-04-02 16:24:46 +0200255 close(fd_num);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800256 }
257 start_fd = keep_fd + 1;
258 }
259 if (start_fd <= end_fd) {
260 for (fd_num = start_fd; fd_num < end_fd; ++fd_num) {
Victor Stinnere7c74922015-04-02 16:24:46 +0200261 close(fd_num);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800262 }
263 }
264}
265
266
267#if defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)
268/* It doesn't matter if d_name has room for NAME_MAX chars; we're using this
269 * only to read a directory of short file descriptor number names. The kernel
270 * will return an error if we didn't give it enough space. Highly Unlikely.
271 * This structure is very old and stable: It will not change unless the kernel
272 * chooses to break compatibility with all existing binaries. Highly Unlikely.
273 */
Gregory P. Smith255bf5b2013-03-03 10:45:05 -0800274struct linux_dirent64 {
Gregory P. Smith58f07a92012-06-05 13:26:39 -0700275 unsigned long long d_ino;
Gregory P. Smith255bf5b2013-03-03 10:45:05 -0800276 long long d_off;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800277 unsigned short d_reclen; /* Length of this linux_dirent */
Gregory P. Smith255bf5b2013-03-03 10:45:05 -0800278 unsigned char d_type;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800279 char d_name[256]; /* Filename (null-terminated) */
280};
281
Gregory P. Smitha26987a2014-06-01 13:46:36 -0700282/* Close all open file descriptors in the range from start_fd and higher
283 * Do not close any in the sorted py_fds_to_keep list.
Gregory P. Smith8facece2012-01-21 14:01:08 -0800284 *
285 * This version is async signal safe as it does not make any unsafe C library
286 * calls, malloc calls or handle any locks. It is _unfortunate_ to be forced
287 * to resort to making a kernel system call directly but this is the ONLY api
288 * available that does no harm. opendir/readdir/closedir perform memory
289 * allocation and locking so while they usually work they are not guaranteed
290 * to (especially if you have replaced your malloc implementation). A version
291 * of this function that uses those can be found in the _maybe_unsafe variant.
292 *
293 * This is Linux specific because that is all I am ready to test it on. It
294 * should be easy to add OS specific dirent or dirent64 structures and modify
295 * it with some cpp #define magic to work on other OSes as well if you want.
296 */
Benjamin Peterson91eef982012-01-22 20:04:46 -0500297static void
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700298_close_open_fds_safe(int start_fd, PyObject* py_fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -0800299{
300 int fd_dir_fd;
Victor Stinnerdaf45552013-08-28 00:53:59 +0200301
Victor Stinner160e8192015-03-30 02:18:31 +0200302 fd_dir_fd = _Py_open_noraise(FD_DIR, O_RDONLY);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800303 if (fd_dir_fd == -1) {
304 /* No way to get a list of open fds. */
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700305 _close_fds_by_brute_force(start_fd, py_fds_to_keep);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800306 return;
307 } else {
Gregory P. Smith255bf5b2013-03-03 10:45:05 -0800308 char buffer[sizeof(struct linux_dirent64)];
Gregory P. Smith8facece2012-01-21 14:01:08 -0800309 int bytes;
Gregory P. Smith255bf5b2013-03-03 10:45:05 -0800310 while ((bytes = syscall(SYS_getdents64, fd_dir_fd,
311 (struct linux_dirent64 *)buffer,
Gregory P. Smith8facece2012-01-21 14:01:08 -0800312 sizeof(buffer))) > 0) {
Gregory P. Smith255bf5b2013-03-03 10:45:05 -0800313 struct linux_dirent64 *entry;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800314 int offset;
Gregory P. Smith3015fb82018-11-12 22:01:22 -0800315#ifdef _Py_MEMORY_SANITIZER
Gregory P. Smith1584a002018-11-12 12:07:14 -0800316 __msan_unpoison(buffer, bytes);
317#endif
Gregory P. Smith8facece2012-01-21 14:01:08 -0800318 for (offset = 0; offset < bytes; offset += entry->d_reclen) {
319 int fd;
Gregory P. Smith255bf5b2013-03-03 10:45:05 -0800320 entry = (struct linux_dirent64 *)(buffer + offset);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800321 if ((fd = _pos_int_from_ascii(entry->d_name)) < 0)
322 continue; /* Not a number. */
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700323 if (fd != fd_dir_fd && fd >= start_fd &&
Gregory P. Smith8facece2012-01-21 14:01:08 -0800324 !_is_fd_in_sorted_fd_sequence(fd, py_fds_to_keep)) {
Victor Stinnere7c74922015-04-02 16:24:46 +0200325 close(fd);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800326 }
327 }
328 }
Victor Stinnere7c74922015-04-02 16:24:46 +0200329 close(fd_dir_fd);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800330 }
331}
332
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700333#define _close_open_fds _close_open_fds_safe
Gregory P. Smith8facece2012-01-21 14:01:08 -0800334
335#else /* NOT (defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)) */
336
337
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700338/* Close all open file descriptors from start_fd and higher.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300339 * Do not close any in the sorted py_fds_to_keep tuple.
Gregory P. Smith8facece2012-01-21 14:01:08 -0800340 *
341 * This function violates the strict use of async signal safe functions. :(
Gregory P. Smithe3f78482012-01-21 15:16:17 -0800342 * It calls opendir(), readdir() and closedir(). Of these, the one most
Gregory P. Smith8facece2012-01-21 14:01:08 -0800343 * likely to ever cause a problem is opendir() as it performs an internal
344 * malloc(). Practically this should not be a problem. The Java VM makes the
345 * same calls between fork and exec in its own UNIXProcess_md.c implementation.
346 *
347 * readdir_r() is not used because it provides no benefit. It is typically
348 * implemented as readdir() followed by memcpy(). See also:
349 * http://womble.decadent.org.uk/readdir_r-advisory.html
350 */
Benjamin Peterson91eef982012-01-22 20:04:46 -0500351static void
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700352_close_open_fds_maybe_unsafe(long start_fd, PyObject* py_fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -0800353{
354 DIR *proc_fd_dir;
355#ifndef HAVE_DIRFD
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700356 while (_is_fd_in_sorted_fd_sequence(start_fd, py_fds_to_keep)) {
Gregory P. Smith8facece2012-01-21 14:01:08 -0800357 ++start_fd;
358 }
Gregory P. Smith8facece2012-01-21 14:01:08 -0800359 /* Close our lowest fd before we call opendir so that it is likely to
360 * reuse that fd otherwise we might close opendir's file descriptor in
361 * our loop. This trick assumes that fd's are allocated on a lowest
362 * available basis. */
Victor Stinnere7c74922015-04-02 16:24:46 +0200363 close(start_fd);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800364 ++start_fd;
365#endif
Gregory P. Smith8facece2012-01-21 14:01:08 -0800366
Gregory P. Smith4842efc2012-01-21 21:01:24 -0800367#if defined(__FreeBSD__)
368 if (!_is_fdescfs_mounted_on_dev_fd())
369 proc_fd_dir = NULL;
370 else
371#endif
372 proc_fd_dir = opendir(FD_DIR);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800373 if (!proc_fd_dir) {
374 /* No way to get a list of open fds. */
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700375 _close_fds_by_brute_force(start_fd, py_fds_to_keep);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800376 } else {
Gregory P. Smithe3f78482012-01-21 15:16:17 -0800377 struct dirent *dir_entry;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800378#ifdef HAVE_DIRFD
Gregory P. Smithe9b7cab2012-01-21 15:19:11 -0800379 int fd_used_by_opendir = dirfd(proc_fd_dir);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800380#else
381 int fd_used_by_opendir = start_fd - 1;
382#endif
383 errno = 0;
Gregory P. Smithe3f78482012-01-21 15:16:17 -0800384 while ((dir_entry = readdir(proc_fd_dir))) {
Gregory P. Smith8facece2012-01-21 14:01:08 -0800385 int fd;
386 if ((fd = _pos_int_from_ascii(dir_entry->d_name)) < 0)
387 continue; /* Not a number. */
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700388 if (fd != fd_used_by_opendir && fd >= start_fd &&
Gregory P. Smith8facece2012-01-21 14:01:08 -0800389 !_is_fd_in_sorted_fd_sequence(fd, py_fds_to_keep)) {
Victor Stinnere7c74922015-04-02 16:24:46 +0200390 close(fd);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800391 }
392 errno = 0;
393 }
394 if (errno) {
395 /* readdir error, revert behavior. Highly Unlikely. */
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700396 _close_fds_by_brute_force(start_fd, py_fds_to_keep);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800397 }
398 closedir(proc_fd_dir);
399 }
400}
401
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700402#define _close_open_fds _close_open_fds_maybe_unsafe
Gregory P. Smith8facece2012-01-21 14:01:08 -0800403
404#endif /* else NOT (defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)) */
405
406
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000407/*
408 * This function is code executed in the child process immediately after fork
409 * to set things up and call exec().
410 *
411 * All of the code in this function must only use async-signal-safe functions,
412 * listed at `man 7 signal` or
413 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
414 *
415 * This restriction is documented at
416 * http://www.opengroup.org/onlinepubs/009695399/functions/fork.html.
417 */
Benjamin Peterson91eef982012-01-22 20:04:46 -0500418static void
419child_exec(char *const exec_array[],
420 char *const argv[],
421 char *const envp[],
422 const char *cwd,
423 int p2cread, int p2cwrite,
424 int c2pread, int c2pwrite,
425 int errread, int errwrite,
426 int errpipe_read, int errpipe_write,
427 int close_fds, int restore_signals,
428 int call_setsid,
Patrick McLean2b2ead72019-09-12 10:15:44 -0700429 int call_setgid, gid_t gid,
430 int call_setgroups, size_t groups_size, const gid_t *groups,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700431 int call_setuid, uid_t uid, int child_umask,
Benjamin Peterson91eef982012-01-22 20:04:46 -0500432 PyObject *py_fds_to_keep,
433 PyObject *preexec_fn,
434 PyObject *preexec_fn_args_tuple)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000435{
Victor Stinner185fd332015-04-01 18:35:53 +0200436 int i, saved_errno, reached_preexec = 0;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000437 PyObject *result;
Gregory P. Smith14affb82010-12-22 05:22:17 +0000438 const char* err_msg = "";
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000439 /* Buffer large enough to hold a hex integer. We can't malloc. */
440 char hex_errno[sizeof(saved_errno)*2+1];
441
Victor Stinnerdaf45552013-08-28 00:53:59 +0200442 if (make_inheritable(py_fds_to_keep, errpipe_write) < 0)
443 goto error;
444
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000445 /* Close parent's pipe ends. */
Victor Stinnerdaf45552013-08-28 00:53:59 +0200446 if (p2cwrite != -1)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000447 POSIX_CALL(close(p2cwrite));
Victor Stinnerdaf45552013-08-28 00:53:59 +0200448 if (c2pread != -1)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000449 POSIX_CALL(close(c2pread));
Victor Stinnerdaf45552013-08-28 00:53:59 +0200450 if (errread != -1)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000451 POSIX_CALL(close(errread));
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000452 POSIX_CALL(close(errpipe_read));
453
Ross Lagerwalld98646e2011-07-27 07:16:31 +0200454 /* When duping fds, if there arises a situation where one of the fds is
455 either 0, 1 or 2, it is possible that it is overwritten (#12607). */
Gregory P. Smithce344102018-09-10 17:46:22 -0700456 if (c2pwrite == 0) {
Ross Lagerwalld98646e2011-07-27 07:16:31 +0200457 POSIX_CALL(c2pwrite = dup(c2pwrite));
Gregory P. Smithce344102018-09-10 17:46:22 -0700458 /* issue32270 */
459 if (_Py_set_inheritable_async_safe(c2pwrite, 0, NULL) < 0) {
460 goto error;
461 }
462 }
463 while (errwrite == 0 || errwrite == 1) {
Ross Lagerwalld98646e2011-07-27 07:16:31 +0200464 POSIX_CALL(errwrite = dup(errwrite));
Gregory P. Smithce344102018-09-10 17:46:22 -0700465 /* issue32270 */
466 if (_Py_set_inheritable_async_safe(errwrite, 0, NULL) < 0) {
467 goto error;
468 }
469 }
Ross Lagerwalld98646e2011-07-27 07:16:31 +0200470
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000471 /* Dup fds for child.
472 dup2() removes the CLOEXEC flag but we must do it ourselves if dup2()
473 would be a no-op (issue #10806). */
474 if (p2cread == 0) {
Alexey Izbyshevc1e46e92018-02-06 09:09:34 +0300475 if (_Py_set_inheritable_async_safe(p2cread, 1, NULL) < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +0200476 goto error;
477 }
478 else if (p2cread != -1)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000479 POSIX_CALL(dup2(p2cread, 0)); /* stdin */
Victor Stinnerdaf45552013-08-28 00:53:59 +0200480
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000481 if (c2pwrite == 1) {
Alexey Izbyshevc1e46e92018-02-06 09:09:34 +0300482 if (_Py_set_inheritable_async_safe(c2pwrite, 1, NULL) < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +0200483 goto error;
484 }
485 else if (c2pwrite != -1)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000486 POSIX_CALL(dup2(c2pwrite, 1)); /* stdout */
Victor Stinnerdaf45552013-08-28 00:53:59 +0200487
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000488 if (errwrite == 2) {
Alexey Izbyshevc1e46e92018-02-06 09:09:34 +0300489 if (_Py_set_inheritable_async_safe(errwrite, 1, NULL) < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +0200490 goto error;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000491 }
Victor Stinnerdaf45552013-08-28 00:53:59 +0200492 else if (errwrite != -1)
493 POSIX_CALL(dup2(errwrite, 2)); /* stderr */
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000494
Gregory P. Smithce344102018-09-10 17:46:22 -0700495 /* We no longer manually close p2cread, c2pwrite, and errwrite here as
496 * _close_open_fds takes care when it is not already non-inheritable. */
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000497
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000498 if (cwd)
499 POSIX_CALL(chdir(cwd));
500
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700501 if (child_umask >= 0)
502 umask(child_umask); /* umask() always succeeds. */
503
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000504 if (restore_signals)
505 _Py_RestoreSignals();
506
507#ifdef HAVE_SETSID
508 if (call_setsid)
509 POSIX_CALL(setsid());
510#endif
511
Patrick McLean2b2ead72019-09-12 10:15:44 -0700512#ifdef HAVE_SETGROUPS
513 if (call_setgroups)
514 POSIX_CALL(setgroups(groups_size, groups));
515#endif /* HAVE_SETGROUPS */
516
517#ifdef HAVE_SETREGID
518 if (call_setgid)
519 POSIX_CALL(setregid(gid, gid));
520#endif /* HAVE_SETREGID */
521
522#ifdef HAVE_SETREUID
523 if (call_setuid)
524 POSIX_CALL(setreuid(uid, uid));
525#endif /* HAVE_SETREUID */
526
527
Gregory P. Smith5591b022012-10-10 03:34:47 -0700528 reached_preexec = 1;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000529 if (preexec_fn != Py_None && preexec_fn_args_tuple) {
530 /* This is where the user has asked us to deadlock their program. */
531 result = PyObject_Call(preexec_fn, preexec_fn_args_tuple, NULL);
532 if (result == NULL) {
533 /* Stringifying the exception or traceback would involve
534 * memory allocation and thus potential for deadlock.
535 * We've already faced potential deadlock by calling back
536 * into Python in the first place, so it probably doesn't
537 * matter but we avoid it to minimize the possibility. */
538 err_msg = "Exception occurred in preexec_fn.";
539 errno = 0; /* We don't want to report an OSError. */
540 goto error;
541 }
542 /* Py_DECREF(result); - We're about to exec so why bother? */
543 }
544
Charles-François Natali249cdc32013-08-25 18:24:45 +0200545 /* close FDs after executing preexec_fn, which might open FDs */
546 if (close_fds) {
Charles-François Natali249cdc32013-08-25 18:24:45 +0200547 /* TODO HP-UX could use pstat_getproc() if anyone cares about it. */
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700548 _close_open_fds(3, py_fds_to_keep);
Charles-François Natali249cdc32013-08-25 18:24:45 +0200549 }
550
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000551 /* This loop matches the Lib/os.py _execvpe()'s PATH search when */
552 /* given the executable_list generated by Lib/subprocess.py. */
553 saved_errno = 0;
554 for (i = 0; exec_array[i] != NULL; ++i) {
555 const char *executable = exec_array[i];
556 if (envp) {
557 execve(executable, argv, envp);
558 } else {
559 execv(executable, argv);
560 }
561 if (errno != ENOENT && errno != ENOTDIR && saved_errno == 0) {
562 saved_errno = errno;
563 }
564 }
565 /* Report the first exec error, not the last. */
566 if (saved_errno)
567 errno = saved_errno;
568
569error:
570 saved_errno = errno;
571 /* Report the posix error to our parent process. */
Gregory P. Smith12fdca52012-01-21 12:31:25 -0800572 /* We ignore all write() return values as the total size of our writes is
Victor Stinner185fd332015-04-01 18:35:53 +0200573 less than PIPEBUF and we cannot do anything about an error anyways.
574 Use _Py_write_noraise() to retry write() if it is interrupted by a
575 signal (fails with EINTR). */
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000576 if (saved_errno) {
577 char *cur;
Victor Stinner185fd332015-04-01 18:35:53 +0200578 _Py_write_noraise(errpipe_write, "OSError:", 8);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000579 cur = hex_errno + sizeof(hex_errno);
Serhiy Storchaka5ae4f492016-09-27 22:03:51 +0300580 while (saved_errno != 0 && cur != hex_errno) {
Gregory P. Smith4dff6f62015-04-25 23:42:38 +0000581 *--cur = Py_hexdigits[saved_errno % 16];
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000582 saved_errno /= 16;
583 }
Victor Stinner185fd332015-04-01 18:35:53 +0200584 _Py_write_noraise(errpipe_write, cur, hex_errno + sizeof(hex_errno) - cur);
585 _Py_write_noraise(errpipe_write, ":", 1);
Gregory P. Smith5591b022012-10-10 03:34:47 -0700586 if (!reached_preexec) {
587 /* Indicate to the parent that the error happened before exec(). */
Victor Stinner185fd332015-04-01 18:35:53 +0200588 _Py_write_noraise(errpipe_write, "noexec", 6);
Gregory P. Smith5591b022012-10-10 03:34:47 -0700589 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000590 /* We can't call strerror(saved_errno). It is not async signal safe.
591 * The parent process will look the error message up. */
592 } else {
Victor Stinner185fd332015-04-01 18:35:53 +0200593 _Py_write_noraise(errpipe_write, "SubprocessError:0:", 18);
594 _Py_write_noraise(errpipe_write, err_msg, strlen(err_msg));
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000595 }
596}
597
598
599static PyObject *
600subprocess_fork_exec(PyObject* self, PyObject *args)
601{
602 PyObject *gc_module = NULL;
Antoine Pitrou721738f2012-08-15 23:20:39 +0200603 PyObject *executable_list, *py_fds_to_keep;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000604 PyObject *env_list, *preexec_fn;
Gregory P. Smith68f52172010-03-15 06:07:42 +0000605 PyObject *process_args, *converted_args = NULL, *fast_args = NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000606 PyObject *preexec_fn_args_tuple = NULL;
Patrick McLean2b2ead72019-09-12 10:15:44 -0700607 PyObject *groups_list;
608 PyObject *uid_object, *gid_object;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000609 int p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite;
610 int errpipe_read, errpipe_write, close_fds, restore_signals;
611 int call_setsid;
Patrick McLean2b2ead72019-09-12 10:15:44 -0700612 int call_setgid = 0, call_setgroups = 0, call_setuid = 0;
613 uid_t uid;
614 gid_t gid, *groups = NULL;
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700615 int child_umask;
Victor Stinner0e59cc32010-04-16 23:49:32 +0000616 PyObject *cwd_obj, *cwd_obj2;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000617 const char *cwd;
618 pid_t pid;
619 int need_to_reenable_gc = 0;
620 char *const *exec_array, *const *argv = NULL, *const *envp = NULL;
Patrick McLean2b2ead72019-09-12 10:15:44 -0700621 Py_ssize_t arg_num, num_groups = 0;
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200622 int need_after_fork = 0;
Gregory P. Smitha20b6ad2018-09-13 04:30:10 -0700623 int saved_errno = 0;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000624
625 if (!PyArg_ParseTuple(
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700626 args, "OOpO!OOiiiiiiiiiiOOOiO:fork_exec",
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300627 &process_args, &executable_list,
628 &close_fds, &PyTuple_Type, &py_fds_to_keep,
Victor Stinner0e59cc32010-04-16 23:49:32 +0000629 &cwd_obj, &env_list,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000630 &p2cread, &p2cwrite, &c2pread, &c2pwrite,
631 &errread, &errwrite, &errpipe_read, &errpipe_write,
Patrick McLean2b2ead72019-09-12 10:15:44 -0700632 &restore_signals, &call_setsid,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700633 &gid_object, &groups_list, &uid_object, &child_umask,
Patrick McLean2b2ead72019-09-12 10:15:44 -0700634 &preexec_fn))
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000635 return NULL;
636
Christian Heimes98d90f72019-08-27 23:36:56 +0200637 if ((preexec_fn != Py_None) &&
638 (_PyInterpreterState_Get() != PyInterpreterState_Main())) {
639 PyErr_SetString(PyExc_RuntimeError,
640 "preexec_fn not supported within subinterpreters");
Eric Snow59032962018-09-14 14:17:20 -0700641 return NULL;
642 }
643
Gregory P. Smith361e30c2013-12-01 00:12:24 -0800644 if (close_fds && errpipe_write < 3) { /* precondition */
645 PyErr_SetString(PyExc_ValueError, "errpipe_write must be >= 3");
646 return NULL;
647 }
Gregory P. Smith8facece2012-01-21 14:01:08 -0800648 if (_sanity_check_python_fd_sequence(py_fds_to_keep)) {
649 PyErr_SetString(PyExc_ValueError, "bad value(s) in fds_to_keep");
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000650 return NULL;
651 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000652
653 /* We need to call gc.disable() when we'll be calling preexec_fn */
654 if (preexec_fn != Py_None) {
655 PyObject *result;
Victor Stinnerdaf45552013-08-28 00:53:59 +0200656
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000657 gc_module = PyImport_ImportModule("gc");
658 if (gc_module == NULL)
659 return NULL;
Dino Viehland5a7d2e12019-09-10 12:01:20 +0100660 result = _PyObject_CallMethodNoArgs(
661 gc_module, _posixsubprocessstate_global->isenabled);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000662 if (result == NULL) {
663 Py_DECREF(gc_module);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000664 return NULL;
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000665 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000666 need_to_reenable_gc = PyObject_IsTrue(result);
667 Py_DECREF(result);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000668 if (need_to_reenable_gc == -1) {
669 Py_DECREF(gc_module);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000670 return NULL;
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000671 }
Dino Viehland5a7d2e12019-09-10 12:01:20 +0100672 result = _PyObject_CallMethodNoArgs(
673 gc_module, _posixsubprocessstate_global->disable);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000674 if (result == NULL) {
675 Py_DECREF(gc_module);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000676 return NULL;
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000677 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000678 Py_DECREF(result);
679 }
680
681 exec_array = _PySequence_BytesToCharpArray(executable_list);
Victor Stinner8f437aa2014-10-05 17:25:19 +0200682 if (!exec_array)
683 goto cleanup;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000684
685 /* Convert args and env into appropriate arguments for exec() */
686 /* These conversions are done in the parent process to avoid allocating
687 or freeing memory in the child process. */
688 if (process_args != Py_None) {
Gregory P. Smith68f52172010-03-15 06:07:42 +0000689 Py_ssize_t num_args;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000690 /* Equivalent to: */
691 /* tuple(PyUnicode_FSConverter(arg) for arg in process_args) */
Gregory P. Smith68f52172010-03-15 06:07:42 +0000692 fast_args = PySequence_Fast(process_args, "argv must be a tuple");
Stefan Krahdb579d72012-08-20 14:36:47 +0200693 if (fast_args == NULL)
694 goto cleanup;
Gregory P. Smith68f52172010-03-15 06:07:42 +0000695 num_args = PySequence_Fast_GET_SIZE(fast_args);
696 converted_args = PyTuple_New(num_args);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000697 if (converted_args == NULL)
698 goto cleanup;
Gregory P. Smith68f52172010-03-15 06:07:42 +0000699 for (arg_num = 0; arg_num < num_args; ++arg_num) {
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000700 PyObject *borrowed_arg, *converted_arg;
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300701 if (PySequence_Fast_GET_SIZE(fast_args) != num_args) {
702 PyErr_SetString(PyExc_RuntimeError, "args changed during iteration");
703 goto cleanup;
704 }
Gregory P. Smith68f52172010-03-15 06:07:42 +0000705 borrowed_arg = PySequence_Fast_GET_ITEM(fast_args, arg_num);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000706 if (PyUnicode_FSConverter(borrowed_arg, &converted_arg) == 0)
707 goto cleanup;
708 PyTuple_SET_ITEM(converted_args, arg_num, converted_arg);
709 }
710
711 argv = _PySequence_BytesToCharpArray(converted_args);
712 Py_CLEAR(converted_args);
Gregory P. Smith68f52172010-03-15 06:07:42 +0000713 Py_CLEAR(fast_args);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000714 if (!argv)
715 goto cleanup;
716 }
717
718 if (env_list != Py_None) {
719 envp = _PySequence_BytesToCharpArray(env_list);
720 if (!envp)
721 goto cleanup;
722 }
723
Victor Stinner0e59cc32010-04-16 23:49:32 +0000724 if (cwd_obj != Py_None) {
725 if (PyUnicode_FSConverter(cwd_obj, &cwd_obj2) == 0)
726 goto cleanup;
Victor Stinnerdcb24032010-04-22 12:08:36 +0000727 cwd = PyBytes_AsString(cwd_obj2);
Victor Stinner0e59cc32010-04-16 23:49:32 +0000728 } else {
729 cwd = NULL;
730 cwd_obj2 = NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000731 }
732
Patrick McLean2b2ead72019-09-12 10:15:44 -0700733 if (groups_list != Py_None) {
734#ifdef HAVE_SETGROUPS
735 Py_ssize_t i;
736 unsigned long gid;
737
738 if (!PyList_Check(groups_list)) {
739 PyErr_SetString(PyExc_TypeError,
740 "setgroups argument must be a list");
741 goto cleanup;
742 }
743 num_groups = PySequence_Size(groups_list);
744
745 if (num_groups < 0)
746 goto cleanup;
747
748 if (num_groups > MAX_GROUPS) {
749 PyErr_SetString(PyExc_ValueError, "too many groups");
750 goto cleanup;
751 }
752
753 if ((groups = PyMem_RawMalloc(num_groups * sizeof(gid_t))) == NULL) {
754 PyErr_SetString(PyExc_MemoryError,
755 "failed to allocate memory for group list");
756 goto cleanup;
757 }
758
759 for (i = 0; i < num_groups; i++) {
760 PyObject *elem;
761 elem = PySequence_GetItem(groups_list, i);
762 if (!elem)
763 goto cleanup;
764 if (!PyLong_Check(elem)) {
765 PyErr_SetString(PyExc_TypeError,
766 "groups must be integers");
767 Py_DECREF(elem);
768 goto cleanup;
769 } else {
770 /* In posixmodule.c UnsignedLong is used as a fallback value
771 * if the value provided does not fit in a Long. Since we are
772 * already doing the bounds checking on the Python side, we
773 * can go directly to an UnsignedLong here. */
774 if (!_Py_Gid_Converter(elem, &gid)) {
775 Py_DECREF(elem);
776 PyErr_SetString(PyExc_ValueError, "invalid group id");
777 goto cleanup;
778 }
779 groups[i] = gid;
780 }
781 Py_DECREF(elem);
782 }
783 call_setgroups = 1;
784
785#else /* HAVE_SETGROUPS */
786 PyErr_BadInternalCall();
787 goto cleanup;
788#endif /* HAVE_SETGROUPS */
789 }
790
791 if (gid_object != Py_None) {
792#ifdef HAVE_SETREGID
793 if (!_Py_Gid_Converter(gid_object, &gid))
794 goto cleanup;
795
796 call_setgid = 1;
797
798#else /* HAVE_SETREGID */
799 PyErr_BadInternalCall();
800 goto cleanup;
801#endif /* HAVE_SETREUID */
802 }
803
804 if (uid_object != Py_None) {
805#ifdef HAVE_SETREUID
806 if (!_Py_Uid_Converter(uid_object, &uid))
807 goto cleanup;
808
809 call_setuid = 1;
810
811#else /* HAVE_SETREUID */
812 PyErr_BadInternalCall();
813 goto cleanup;
814#endif /* HAVE_SETREUID */
815 }
816
Gregory P. Smith163468a2017-05-29 10:03:41 -0700817 /* This must be the last thing done before fork() because we do not
818 * want to call PyOS_BeforeFork() if there is any chance of another
819 * error leading to the cleanup: code without calling fork(). */
820 if (preexec_fn != Py_None) {
821 preexec_fn_args_tuple = PyTuple_New(0);
822 if (!preexec_fn_args_tuple)
823 goto cleanup;
824 PyOS_BeforeFork();
825 need_after_fork = 1;
826 }
827
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000828 pid = fork();
829 if (pid == 0) {
830 /* Child process */
Victor Stinner0e59cc32010-04-16 23:49:32 +0000831 /*
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000832 * Code from here to _exit() must only use async-signal-safe functions,
833 * listed at `man 7 signal` or
834 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
835 */
836
837 if (preexec_fn != Py_None) {
838 /* We'll be calling back into Python later so we need to do this.
839 * This call may not be async-signal-safe but neither is calling
840 * back into Python. The user asked us to use hope as a strategy
841 * to avoid deadlock... */
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200842 PyOS_AfterFork_Child();
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000843 }
844
845 child_exec(exec_array, argv, envp, cwd,
846 p2cread, p2cwrite, c2pread, c2pwrite,
847 errread, errwrite, errpipe_read, errpipe_write,
848 close_fds, restore_signals, call_setsid,
Patrick McLean2b2ead72019-09-12 10:15:44 -0700849 call_setgid, gid, call_setgroups, num_groups, groups,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700850 call_setuid, uid, child_umask,
Gregory P. Smith8facece2012-01-21 14:01:08 -0800851 py_fds_to_keep, preexec_fn, preexec_fn_args_tuple);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000852 _exit(255);
853 return NULL; /* Dead code to avoid a potential compiler warning. */
854 }
Gregory P. Smitha20b6ad2018-09-13 04:30:10 -0700855 /* Parent (original) process */
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000856 if (pid == -1) {
Gregory P. Smitha20b6ad2018-09-13 04:30:10 -0700857 /* Capture errno for the exception. */
858 saved_errno = errno;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000859 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000860
Gregory P. Smitha20b6ad2018-09-13 04:30:10 -0700861 Py_XDECREF(cwd_obj2);
862
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200863 if (need_after_fork)
864 PyOS_AfterFork_Parent();
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000865 if (envp)
866 _Py_FreeCharPArray(envp);
867 if (argv)
868 _Py_FreeCharPArray(argv);
869 _Py_FreeCharPArray(exec_array);
870
871 /* Reenable gc in the parent process (or if fork failed). */
Martin Panterafdd5132015-11-30 02:21:41 +0000872 if (_enable_gc(need_to_reenable_gc, gc_module)) {
873 pid = -1;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000874 }
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000875 Py_XDECREF(preexec_fn_args_tuple);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000876 Py_XDECREF(gc_module);
877
Gregory P. Smitha20b6ad2018-09-13 04:30:10 -0700878 if (pid == -1) {
879 errno = saved_errno;
880 /* We can't call this above as PyOS_AfterFork_Parent() calls back
881 * into Python code which would see the unreturned error. */
882 PyErr_SetFromErrno(PyExc_OSError);
883 return NULL; /* fork() failed. */
884 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000885
886 return PyLong_FromPid(pid);
887
888cleanup:
889 if (envp)
890 _Py_FreeCharPArray(envp);
891 if (argv)
892 _Py_FreeCharPArray(argv);
Victor Stinner8f437aa2014-10-05 17:25:19 +0200893 if (exec_array)
894 _Py_FreeCharPArray(exec_array);
Patrick McLean2b2ead72019-09-12 10:15:44 -0700895
896 PyMem_RawFree(groups);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000897 Py_XDECREF(converted_args);
Gregory P. Smith68f52172010-03-15 06:07:42 +0000898 Py_XDECREF(fast_args);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000899 Py_XDECREF(preexec_fn_args_tuple);
Martin Panterafdd5132015-11-30 02:21:41 +0000900 _enable_gc(need_to_reenable_gc, gc_module);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000901 Py_XDECREF(gc_module);
902 return NULL;
903}
904
905
906PyDoc_STRVAR(subprocess_fork_exec_doc,
Orivej Desh77abf232019-09-20 17:01:10 +0000907"fork_exec(args, executable_list, close_fds, pass_fds, cwd, env,\n\
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000908 p2cread, p2cwrite, c2pread, c2pwrite,\n\
909 errread, errwrite, errpipe_read, errpipe_write,\n\
Patrick McLean2b2ead72019-09-12 10:15:44 -0700910 restore_signals, call_setsid,\n\
Orivej Desh77abf232019-09-20 17:01:10 +0000911 gid, groups_list, uid,\n\
Patrick McLean2b2ead72019-09-12 10:15:44 -0700912 preexec_fn)\n\
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000913\n\
914Forks a child process, closes parent file descriptors as appropriate in the\n\
915child and dups the few that are needed before calling exec() in the child\n\
916process.\n\
917\n\
Orivej Desh77abf232019-09-20 17:01:10 +0000918If close_fds is true, close file descriptors 3 and higher, except those listed\n\
919in the sorted tuple pass_fds.\n\
920\n\
921The preexec_fn, if supplied, will be called immediately before closing file\n\
922descriptors and exec.\n\
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000923WARNING: preexec_fn is NOT SAFE if your application uses threads.\n\
924 It may trigger infrequent, difficult to debug deadlocks.\n\
925\n\
926If an error occurs in the child process before the exec, it is\n\
927serialized and written to the errpipe_write fd per subprocess.py.\n\
928\n\
929Returns: the child process's PID.\n\
930\n\
931Raises: Only on an error in the parent process.\n\
932");
933
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000934/* module level code ********************************************************/
935
936PyDoc_STRVAR(module_doc,
937"A POSIX helper for the subprocess module.");
938
939
940static PyMethodDef module_methods[] = {
941 {"fork_exec", subprocess_fork_exec, METH_VARARGS, subprocess_fork_exec_doc},
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000942 {NULL, NULL} /* sentinel */
943};
944
945
Dino Viehland5a7d2e12019-09-10 12:01:20 +0100946static int _posixsubprocess_traverse(PyObject *m, visitproc visit, void *arg) {
947 Py_VISIT(_posixsubprocessstate(m)->disable);
948 Py_VISIT(_posixsubprocessstate(m)->enable);
949 Py_VISIT(_posixsubprocessstate(m)->isenabled);
950 return 0;
951}
952
953static int _posixsubprocess_clear(PyObject *m) {
954 Py_CLEAR(_posixsubprocessstate(m)->disable);
955 Py_CLEAR(_posixsubprocessstate(m)->enable);
956 Py_CLEAR(_posixsubprocessstate(m)->isenabled);
957 return 0;
958}
959
960static void _posixsubprocess_free(void *m) {
961 _posixsubprocess_clear((PyObject *)m);
962}
963
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000964static struct PyModuleDef _posixsubprocessmodule = {
luzpaza5293b42017-11-05 07:37:50 -0600965 PyModuleDef_HEAD_INIT,
966 "_posixsubprocess",
967 module_doc,
Dino Viehland5a7d2e12019-09-10 12:01:20 +0100968 sizeof(_posixsubprocessstate),
luzpaza5293b42017-11-05 07:37:50 -0600969 module_methods,
Dino Viehland5a7d2e12019-09-10 12:01:20 +0100970 NULL,
971 _posixsubprocess_traverse,
972 _posixsubprocess_clear,
973 _posixsubprocess_free,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000974};
975
976PyMODINIT_FUNC
977PyInit__posixsubprocess(void)
978{
Dino Viehland5a7d2e12019-09-10 12:01:20 +0100979 PyObject* m;
980
981 m = PyState_FindModule(&_posixsubprocessmodule);
982 if (m != NULL) {
983 Py_INCREF(m);
984 return m;
985 }
986
987 m = PyModule_Create(&_posixsubprocessmodule);
988 if (m == NULL) {
989 return NULL;
990 }
991
992 _posixsubprocessstate(m)->disable = PyUnicode_InternFromString("disable");
993 _posixsubprocessstate(m)->enable = PyUnicode_InternFromString("enable");
994 _posixsubprocessstate(m)->isenabled = PyUnicode_InternFromString("isenabled");
995
996 PyState_AddModule(m, &_posixsubprocessmodule);
997 return m;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000998}