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