summaryrefslogtreecommitdiffstats
path: root/osdep/subprocess-posix.c
blob: 395186d9628dad8158ec96ae01e50b07736521e6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
/*
 * This file is part of mpv.
 *
 * mpv is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * mpv is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with mpv.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "osdep/posix-spawn.h"
#include <poll.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>

#include "osdep/subprocess.h"

#include "common/common.h"
#include "misc/thread_tools.h"
#include "osdep/io.h"
#include "stream/stream.h"

       #include <sys/syscall.h>
       #include <unistd.h>
       #include <poll.h>
       #include <stdlib.h>
       #include <stdio.h>

       #ifndef __NR_pidfd_open
       #define __NR_pidfd_open 434   /* System call # on most architectures */
       #endif

       static int
       pidfd_open(pid_t pid, unsigned int flags)
       {
           return syscall(__NR_pidfd_open, pid, flags);
       }


extern char **environ;

#define SAFE_CLOSE(fd) do { if ((fd) >= 0) close((fd)); (fd) = -1; } while (0)

void mp_subprocess2(struct mp_subprocess_opts *opts,
                    struct mp_subprocess_result *res)
{
    posix_spawn_file_actions_t fa;
    bool fa_destroy = false;
    int status = -1;
    int comm_pipe[MP_SUBPROCESS_MAX_FDS][2];
    int devnull = -1;
    pid_t pid = 0;
    bool spawned = false;
    bool killed_by_us = false;
    int cancel_fd = -1;
    int pid_fd = -1;

    *res = (struct mp_subprocess_result){0};

    for (int n = 0; n < opts->num_fds; n++)
        comm_pipe[n][0] = comm_pipe[n][1] = -1;

    if (opts->cancel) {
        cancel_fd = mp_cancel_get_fd(opts->cancel);
        if (cancel_fd < 0)
            goto done;
    }

    for (int n = 0; n < opts->num_fds; n++) {
        if (opts->fds[n].on_read && mp_make_cloexec_pipe(comm_pipe[n]) < 0)
            goto done;
    }

    devnull = open("/dev/null", O_RDONLY | O_CLOEXEC);
    if (devnull < 0)
        goto done;

    if (posix_spawn_file_actions_init(&fa))
        goto done;
    fa_destroy = true;

    // redirect FDs
    for (int n = 0; n < opts->num_fds; n++) {
        int src_fd = devnull;
        if (comm_pipe[n][1] >= 0)
            src_fd = comm_pipe[n][1];
        if (opts->fds[n].src_fd >= 0)
            src_fd = opts->fds[n].src_fd;
        if (posix_spawn_file_actions_adddup2(&fa, src_fd, opts->fds[n].fd))
            goto done;
    }

    char **env = opts->env ? opts->env : environ;

    if (opts->detach) {
        // If we run it detached, we fork a child to start the process; then
        // it exits immediately, letting PID 1 inherit it. So we don't need
        // anything else to collect these child PIDs.
        sigset_t sigmask, oldmask;
        sigfillset(&sigmask);
        pthread_sigmask(SIG_BLOCK, &sigmask, &oldmask);
        pid_t fres = fork();
        if (fres < 0)
            goto done;
        if (fres == 0) {
            // child
            setsid();
            if (posix_spawnp(&pid, opts->exe, &fa, NULL, opts->args, env))
                _exit(1);
            _exit(0);
        }
        pthread_sigmask(SIG_SETMASK, &oldmask, NULL);
        int child_status = 0;
        while (waitpid(fres, &child_status, 0) < 0 && errno == EINTR) {}
        if (!WIFEXITED(child_status) || WEXITSTATUS(child_status) != 0)
            goto done;
        spawned = true;
    } else {
        if (posix_spawnp(&pid, opts->exe, &fa, NULL, opts->args, env))
            goto done;
        spawned = true;
    }

    for (int n = 0; n < opts->num_fds; n++)
        SAFE_CLOSE(comm_pipe[n][1]);
    SAFE_CLOSE(devnull);

    if (pid)
        pid_fd = pidfd_open(pid, 0);

    while (1) {
        struct pollfd fds[MP_SUBPROCESS_MAX_FDS + 2];
        int map_fds[MP_SUBPROCESS_MAX_FDS + 2];
        int num_fds = 0;
        for (int n = 0; n < opts->num_fds; n++) {
            if (comm_pipe[n][0] >= 0) {
                map_fds[num_fds] = n;
                fds[num_fds++] = (struct pollfd){
                    .events = POLLIN,
                    .fd = comm_pipe[n][0],
                };
            }
        }

        if (pid_fd >= 0) {
            map_fds[num_fds] = -2;
            fds[num_fds++] = (struct pollfd){.events = POLLIN, .fd = pid_fd};
        }

        if (!num_fds)
            break;

        if (cancel_fd >= 0) {
            map_fds[num_fds] = -1;
            fds[num_fds++] = (struct pollfd){.events = POLLIN, .fd = cancel_fd};
        }

        if (poll(fds, num_fds, -1) < 0 && errno != EINTR)
            break;

        for (int idx = 0; idx < num_fds; idx++) {
            if (fds[idx].revents) {
                int n = map_fds[idx];
                if (n == -1) {
                    // cancel_fd
                    if (pid)
                        kill(pid, SIGKILL);
                    killed_by_us = true;
                    break;
                } else if (n == -2) {
                    // pid_fd
                    // ignore until all pipes are read fully
                    SAFE_CLOSE(pid_fd);
                    printf("notify close\n");
                } else {
                    char buf[4096];
                    ssize_t r = read(comm_pipe[n][0], buf, sizeof(buf));
                    if (r < 0 && errno == EINTR)
                        continue;
                    if (r > 0 && opts->fds[n].on_read)
                        opts->fds[n].on_read(opts->fds[n].on_read_ctx, buf, r);
                    if (r <= 0) {
                        printf("close %d \n", n);
                        SAFE_CLOSE(comm_pipe[n][0]);
                    }
                }
            }
        }
    }

    // Note: it can happen that a child process closes the pipe, but does not
    //       terminate yet. In this case, we would have to run waitpid() in
    //       a separate thread and use pthread_cancel(), or use other weird
    //       and laborious tricks in order to react to mp_cancel.
    //       So this isn't handled yet.
    //       Unless pidfd_open() is available.
    if (pid) {
        printf("waitpid start\n");
        while (waitpid(pid, &status, 0) < 0 && errno == EINTR) {}
        printf("waitpid done\n");
    }

done:
    if (fa_destroy)
        posix_spawn_file_actions_destroy(&fa);
    for (int n = 0; n < opts->num_fds; n++) {
        SAFE_CLOSE(comm_pipe[n][0]);
        SAFE_CLOSE(comm_pipe[n][1]);
    }
    SAFE_CLOSE(devnull);
    SAFE_CLOSE(pid_fd);

    if (!spawned || (pid && WIFEXITED(status) && WEXITSTATUS(status) == 127)) {
        res->error = MP_SUBPROCESS_EINIT;
    } else if (pid && WIFEXITED(status)) {
        res->exit_status = WEXITSTATUS(status);
    } else if (spawned && opts->detach) {
        // ok
    } else if (killed_by_us) {
        res->error = MP_SUBPROCESS_EKILLED_BY_US;
    } else {
        res->error = MP_SUBPROCESS_EGENERIC;
    }
}