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