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