1 /*
2  * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 
26 #include <dirent.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <unistd.h>
32 #include <limits.h>
33 
34 #include "childproc.h"
35 
36 const char * const *parentPathv;
37 
38 ssize_t
restartableWrite(int fd,const void * buf,size_t count)39 restartableWrite(int fd, const void *buf, size_t count)
40 {
41     ssize_t result;
42     RESTARTABLE(write(fd, buf, count), result);
43     return result;
44 }
45 
46 int
restartableDup2(int fd_from,int fd_to)47 restartableDup2(int fd_from, int fd_to)
48 {
49     int err;
50     RESTARTABLE(dup2(fd_from, fd_to), err);
51     return err;
52 }
53 
54 int
closeSafely(int fd)55 closeSafely(int fd)
56 {
57     return (fd == -1) ? 0 : close(fd);
58 }
59 
60 int
isAsciiDigit(char c)61 isAsciiDigit(char c)
62 {
63   return c >= '0' && c <= '9';
64 }
65 
66 #if defined(_BSDONLY_SOURCE) || defined(__DragonFly__)
67 /*
68  * Quoting POSIX: "If a multi-threaded process calls fork(), the new
69  * process shall contain a replica of the calling thread and its entire
70  * address space, possibly including the states of mutexes and other
71  * resources. Consequently, to avoid errors, the child process may only
72  * execute async-signal-safe operations until such time as one of the exec
73  * functions is called."
74  *
75  * opendir and readir are not async-signal-safe and can deadlock when
76  * called after fork or vfork (and before exec) so use closefrom syscall
77  * which is safe to call after forking.
78  */
79 int
closeDescriptors(void)80 closeDescriptors(void)
81 {
82 #if defined(__FreeBSD__) || defined(__DragonFly__)
83     closefrom(FAIL_FILENO + 1);
84 #else
85     int err;
86     RESTARTABLE(closefrom(FAIL_FILENO + 1), err);
87 #endif
88     return 1;
89 }
90 #else
91 
92 #if defined(_AIX)
93   /* AIX does not understand '/proc/self' - it requires the real process ID */
94   #define FD_DIR aix_fd_dir
95   #define DIR DIR64
96   #define opendir opendir64
97   #define closedir closedir64
98 #elif defined(MACOSX)
99   #define FD_DIR "/dev/fd"
100   #define dirent64 dirent
101   #define readdir64 readdir
102 #else
103   #define FD_DIR "/proc/self/fd"
104 #endif
105 
106 int
closeDescriptors(void)107 closeDescriptors(void)
108 {
109     DIR *dp;
110     struct dirent64 *dirp;
111     int from_fd = FAIL_FILENO + 1;
112 
113     /* We're trying to close all file descriptors, but opendir() might
114      * itself be implemented using a file descriptor, and we certainly
115      * don't want to close that while it's in use.  We assume that if
116      * opendir() is implemented using a file descriptor, then it uses
117      * the lowest numbered file descriptor, just like open().  So we
118      * close a couple explicitly.  */
119 
120     close(from_fd);          /* for possible use by opendir() */
121     close(from_fd + 1);      /* another one for good luck */
122 
123 #if defined(_AIX)
124     /* AIX does not understand '/proc/self' - it requires the real process ID */
125     char aix_fd_dir[32];     /* the pid has at most 19 digits */
126     snprintf(aix_fd_dir, 32, "/proc/%d/fd", getpid());
127 #endif
128 
129     if ((dp = opendir(FD_DIR)) == NULL)
130         return 0;
131 
132     /* We use readdir64 instead of readdir to work around Solaris bug
133      * 6395699: /proc/self/fd fails to report file descriptors >= 1024 on Solaris 9
134      */
135     while ((dirp = readdir64(dp)) != NULL) {
136         int fd;
137         if (isAsciiDigit(dirp->d_name[0]) &&
138             (fd = strtol(dirp->d_name, NULL, 10)) >= from_fd + 2)
139             close(fd);
140     }
141 
142     closedir(dp);
143 
144     return 1;
145 }
146 #endif /* _BSDONLY_SOURCE */
147 
148 int
moveDescriptor(int fd_from,int fd_to)149 moveDescriptor(int fd_from, int fd_to)
150 {
151     if (fd_from != fd_to) {
152         if ((restartableDup2(fd_from, fd_to) == -1) ||
153             (close(fd_from) == -1))
154             return -1;
155     }
156     return 0;
157 }
158 
159 int
magicNumber()160 magicNumber() {
161     return 43110;
162 }
163 
164 /*
165  * Reads nbyte bytes from file descriptor fd into buf,
166  * The read operation is retried in case of EINTR or partial reads.
167  *
168  * Returns number of bytes read (normally nbyte, but may be less in
169  * case of EOF).  In case of read errors, returns -1 and sets errno.
170  */
171 ssize_t
readFully(int fd,void * buf,size_t nbyte)172 readFully(int fd, void *buf, size_t nbyte)
173 {
174     ssize_t remaining = nbyte;
175     for (;;) {
176         ssize_t n = read(fd, buf, remaining);
177         if (n == 0) {
178             return nbyte - remaining;
179         } else if (n > 0) {
180             remaining -= n;
181             if (remaining <= 0)
182                 return nbyte;
183             /* We were interrupted in the middle of reading the bytes.
184              * Unlikely, but possible. */
185             buf = (void *) (((char *)buf) + n);
186         } else if (errno == EINTR) {
187             /* Strange signals like SIGJVM1 are possible at any time.
188              * See http://www.dreamsongs.com/WorseIsBetter.html */
189         } else {
190             return -1;
191         }
192     }
193 }
194 
195 void
initVectorFromBlock(const char ** vector,const char * block,int count)196 initVectorFromBlock(const char**vector, const char* block, int count)
197 {
198     int i;
199     const char *p;
200     for (i = 0, p = block; i < count; i++) {
201         /* Invariant: p always points to the start of a C string. */
202         vector[i] = p;
203         while (*(p++));
204     }
205     vector[count] = NULL;
206 }
207 
208 /**
209  * Exec FILE as a traditional Bourne shell script (i.e. one without #!).
210  * If we could do it over again, we would probably not support such an ancient
211  * misfeature, but compatibility wins over sanity.  The original support for
212  * this was imported accidentally from execvp().
213  */
214 void
execve_as_traditional_shell_script(const char * file,const char * argv[],const char * const envp[])215 execve_as_traditional_shell_script(const char *file,
216                                    const char *argv[],
217                                    const char *const envp[])
218 {
219     /* Use the extra word of space provided for us in argv by caller. */
220     const char *argv0 = argv[0];
221     const char *const *end = argv;
222     while (*end != NULL)
223         ++end;
224     memmove(argv+2, argv+1, (end-argv) * sizeof(*end));
225     argv[0] = "/bin/sh";
226     argv[1] = file;
227     execve(argv[0], (char **) argv, (char **) envp);
228     /* Can't even exec /bin/sh?  Big trouble, but let's soldier on... */
229     memmove(argv+1, argv+2, (end-argv) * sizeof(*end));
230     argv[0] = argv0;
231 }
232 
233 /**
234  * Like execve(2), except that in case of ENOEXEC, FILE is assumed to
235  * be a shell script and the system default shell is invoked to run it.
236  */
237 void
execve_with_shell_fallback(int mode,const char * file,const char * argv[],const char * const envp[])238 execve_with_shell_fallback(int mode, const char *file,
239                            const char *argv[],
240                            const char *const envp[])
241 {
242     if (mode == MODE_CLONE || mode == MODE_VFORK) {
243         /* shared address space; be very careful. */
244         execve(file, (char **) argv, (char **) envp);
245         if (errno == ENOEXEC)
246             execve_as_traditional_shell_script(file, argv, envp);
247     } else {
248         /* unshared address space; we can mutate environ. */
249         environ = (char **) envp;
250         execvp(file, (char **) argv);
251     }
252 }
253 
254 /**
255  * 'execvpe' should have been included in the Unix standards,
256  * and is a GNU extension in glibc 2.10.
257  *
258  * JDK_execvpe is identical to execvp, except that the child environment is
259  * specified via the 3rd argument instead of being inherited from environ.
260  */
261 void
JDK_execvpe(int mode,const char * file,const char * argv[],const char * const envp[])262 JDK_execvpe(int mode, const char *file,
263             const char *argv[],
264             const char *const envp[])
265 {
266     if (envp == NULL || (char **) envp == environ) {
267         execvp(file, (char **) argv);
268         return;
269     }
270 
271     if (*file == '\0') {
272         errno = ENOENT;
273         return;
274     }
275 
276     if (strchr(file, '/') != NULL) {
277         execve_with_shell_fallback(mode, file, argv, envp);
278     } else {
279         /* We must search PATH (parent's, not child's) */
280         char expanded_file[PATH_MAX];
281         int filelen = strlen(file);
282         int sticky_errno = 0;
283         const char * const * dirs;
284         for (dirs = parentPathv; *dirs; dirs++) {
285             const char * dir = *dirs;
286             int dirlen = strlen(dir);
287             if (filelen + dirlen + 2 >= PATH_MAX) {
288                 errno = ENAMETOOLONG;
289                 continue;
290             }
291             memcpy(expanded_file, dir, dirlen);
292             if (expanded_file[dirlen - 1] != '/')
293                 expanded_file[dirlen++] = '/';
294             memcpy(expanded_file + dirlen, file, filelen);
295             expanded_file[dirlen + filelen] = '\0';
296             execve_with_shell_fallback(mode, expanded_file, argv, envp);
297             /* There are 3 responses to various classes of errno:
298              * return immediately, continue (especially for ENOENT),
299              * or continue with "sticky" errno.
300              *
301              * From exec(3):
302              *
303              * If permission is denied for a file (the attempted
304              * execve returned EACCES), these functions will continue
305              * searching the rest of the search path.  If no other
306              * file is found, however, they will return with the
307              * global variable errno set to EACCES.
308              */
309             switch (errno) {
310             case EACCES:
311                 sticky_errno = errno;
312                 /* FALLTHRU */
313             case ENOENT:
314             case ENOTDIR:
315 #ifdef ELOOP
316             case ELOOP:
317 #endif
318 #ifdef ESTALE
319             case ESTALE:
320 #endif
321 #ifdef ENODEV
322             case ENODEV:
323 #endif
324 #ifdef ETIMEDOUT
325             case ETIMEDOUT:
326 #endif
327                 break; /* Try other directories in PATH */
328             default:
329                 return;
330             }
331         }
332         if (sticky_errno != 0)
333             errno = sticky_errno;
334     }
335 }
336 
337 /**
338  * Child process after a successful fork().
339  * This function must not return, and must be prepared for either all
340  * of its address space to be shared with its parent, or to be a copy.
341  * It must not modify global variables such as "environ".
342  */
343 int
childProcess(void * arg)344 childProcess(void *arg)
345 {
346     const ChildStuff* p = (const ChildStuff*) arg;
347     int fail_pipe_fd = p->fail[1];
348 
349     if (p->sendAlivePing) {
350         /* Child shall signal aliveness to parent at the very first
351          * moment. */
352         int code = CHILD_IS_ALIVE;
353         restartableWrite(fail_pipe_fd, &code, sizeof(code));
354     }
355 
356     /* Close the parent sides of the pipes.
357        Closing pipe fds here is redundant, since closeDescriptors()
358        would do it anyways, but a little paranoia is a good thing. */
359     if ((closeSafely(p->in[1])   == -1) ||
360         (closeSafely(p->out[0])  == -1) ||
361         (closeSafely(p->err[0])  == -1) ||
362         (closeSafely(p->childenv[0])  == -1) ||
363         (closeSafely(p->childenv[1])  == -1) ||
364         (closeSafely(p->fail[0]) == -1))
365         goto WhyCantJohnnyExec;
366 
367     /* Give the child sides of the pipes the right fileno's. */
368     /* Note: it is possible for in[0] == 0 */
369     if ((moveDescriptor(p->in[0] != -1 ?  p->in[0] : p->fds[0],
370                         STDIN_FILENO) == -1) ||
371         (moveDescriptor(p->out[1]!= -1 ? p->out[1] : p->fds[1],
372                         STDOUT_FILENO) == -1))
373         goto WhyCantJohnnyExec;
374 
375     if (p->redirectErrorStream) {
376         if ((closeSafely(p->err[1]) == -1) ||
377             (restartableDup2(STDOUT_FILENO, STDERR_FILENO) == -1))
378             goto WhyCantJohnnyExec;
379     } else {
380         if (moveDescriptor(p->err[1] != -1 ? p->err[1] : p->fds[2],
381                            STDERR_FILENO) == -1)
382             goto WhyCantJohnnyExec;
383     }
384 
385     if (moveDescriptor(fail_pipe_fd, FAIL_FILENO) == -1)
386         goto WhyCantJohnnyExec;
387 
388     /* We moved the fail pipe fd */
389     fail_pipe_fd = FAIL_FILENO;
390 
391     /* close everything */
392     if (closeDescriptors() == 0) { /* failed,  close the old way */
393         int max_fd = (int)sysconf(_SC_OPEN_MAX);
394         int fd;
395         for (fd = FAIL_FILENO + 1; fd < max_fd; fd++)
396             if (close(fd) == -1 && errno != EBADF)
397                 goto WhyCantJohnnyExec;
398     }
399 
400     /* change to the new working directory */
401     if (p->pdir != NULL && chdir(p->pdir) < 0)
402         goto WhyCantJohnnyExec;
403 
404     if (fcntl(FAIL_FILENO, F_SETFD, FD_CLOEXEC) == -1)
405         goto WhyCantJohnnyExec;
406 
407     JDK_execvpe(p->mode, p->argv[0], p->argv, p->envv);
408 
409  WhyCantJohnnyExec:
410     /* We used to go to an awful lot of trouble to predict whether the
411      * child would fail, but there is no reliable way to predict the
412      * success of an operation without *trying* it, and there's no way
413      * to try a chdir or exec in the parent.  Instead, all we need is a
414      * way to communicate any failure back to the parent.  Easy; we just
415      * send the errno back to the parent over a pipe in case of failure.
416      * The tricky thing is, how do we communicate the *success* of exec?
417      * We use FD_CLOEXEC together with the fact that a read() on a pipe
418      * yields EOF when the write ends (we have two of them!) are closed.
419      */
420     {
421         int errnum = errno;
422         restartableWrite(fail_pipe_fd, &errnum, sizeof(errnum));
423     }
424     close(fail_pipe_fd);
425     _exit(-1);
426     return 0;  /* Suppress warning "no return value from function" */
427 }
428