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