1 /* Auxiliary functions for the creation of subprocesses.  Native Windows API.
2    Copyright (C) 2001, 2003-2020 Free Software Foundation, Inc.
3    Written by Bruno Haible <bruno@clisp.org>, 2003.
4 
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3 of the License, or
8    (at your option) any later version.
9 
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14 
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
17 
18 #ifndef __KLIBC__
19 /* Get declarations of the native Windows API functions.  */
20 # define WIN32_LEAN_AND_MEAN
21 # include <windows.h>
22 #endif
23 
24 /* Get _open_osfhandle().  */
25 #include <io.h>
26 
27 #include <stdbool.h>
28 #include <string.h>
29 #include <unistd.h>
30 #include <errno.h>
31 
32 /* Get _get_osfhandle().  */
33 # if GNULIB_MSVC_NOTHROW
34 #  include "msvc-nothrow.h"
35 # else
36 #  include <io.h>
37 # endif
38 
39 #include "cloexec.h"
40 #include "xalloc.h"
41 
42 /* Duplicates a file handle, making the copy uninheritable.
43    Returns -1 for a file handle that is equivalent to closed.  */
44 static int
dup_noinherit(int fd)45 dup_noinherit (int fd)
46 {
47   fd = dup_cloexec (fd);
48   if (fd < 0 && errno == EMFILE)
49     error (EXIT_FAILURE, errno, _("_open_osfhandle failed"));
50 
51   return fd;
52 }
53 
54 /* Returns a file descriptor equivalent to FD, except that the resulting file
55    descriptor is none of STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO.
56    FD must be open and non-inheritable.  The result will be non-inheritable as
57    well.
58    If FD < 0, FD itself is returned.  */
59 static int
fd_safer_noinherit(int fd)60 fd_safer_noinherit (int fd)
61 {
62   if (STDIN_FILENO <= fd && fd <= STDERR_FILENO)
63     {
64       /* The recursion depth is at most 3.  */
65       int nfd = fd_safer_noinherit (dup_noinherit (fd));
66       int saved_errno = errno;
67       close (fd);
68       errno = saved_errno;
69       return nfd;
70     }
71   return fd;
72 }
73 
74 /* Duplicates a file handle, making the copy uninheritable and ensuring the
75    result is none of STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO.
76    Returns -1 for a file handle that is equivalent to closed.  */
77 static int
dup_safer_noinherit(int fd)78 dup_safer_noinherit (int fd)
79 {
80   return fd_safer_noinherit (dup_noinherit (fd));
81 }
82 
83 /* Undoes the effect of TEMPFD = dup_safer_noinherit (ORIGFD);  */
84 static void
undup_safer_noinherit(int tempfd,int origfd)85 undup_safer_noinherit (int tempfd, int origfd)
86 {
87   if (tempfd >= 0)
88     {
89       if (dup2 (tempfd, origfd) < 0)
90         error (EXIT_FAILURE, errno, _("cannot restore fd %d: dup2 failed"),
91                origfd);
92       close (tempfd);
93     }
94   else
95     {
96       /* origfd was closed or open to no handle at all.  Set it to a closed
97          state.  This is (nearly) equivalent to the original state.  */
98       close (origfd);
99     }
100 }
101 
102 /* Prepares an argument vector before calling spawn().
103    Note that spawn() does not by itself call the command interpreter
104      (getenv ("COMSPEC") != NULL ? getenv ("COMSPEC") :
105       ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
106          GetVersionEx(&v);
107          v.dwPlatformId == VER_PLATFORM_WIN32_NT;
108       }) ? "cmd.exe" : "command.com").
109    Instead it simply concatenates the arguments, separated by ' ', and calls
110    CreateProcess().  We must quote the arguments since Windows CreateProcess()
111    interprets characters like ' ', '\t', '\\', '"' (but not '<' and '>') in a
112    special way:
113    - Space and tab are interpreted as delimiters. They are not treated as
114      delimiters if they are surrounded by double quotes: "...".
115    - Unescaped double quotes are removed from the input. Their only effect is
116      that within double quotes, space and tab are treated like normal
117      characters.
118    - Backslashes not followed by double quotes are not special.
119    - But 2*n+1 backslashes followed by a double quote become
120      n backslashes followed by a double quote (n >= 0):
121        \" -> "
122        \\\" -> \"
123        \\\\\" -> \\"
124    - '*', '?' characters may get expanded through wildcard expansion in the
125      callee: By default, in the callee, the initialization code before main()
126      takes the result of GetCommandLine(), wildcard-expands it, and passes it
127      to main(). The exceptions to this rule are:
128        - programs that inspect GetCommandLine() and ignore argv,
129        - mingw programs that have a global variable 'int _CRT_glob = 0;',
130        - Cygwin programs, when invoked from a Cygwin program.
131  */
132 #ifndef __KLIBC__
133 # define SHELL_SPECIAL_CHARS "\"\\ \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037*?"
134 # define SHELL_SPACE_CHARS " \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037"
135 #else
136 # define SHELL_SPECIAL_CHARS ""
137 # define SHELL_SPACE_CHARS ""
138 #endif
139 static char **
prepare_spawn(char ** argv)140 prepare_spawn (char **argv)
141 {
142   size_t argc;
143   char **new_argv;
144   size_t i;
145 
146   /* Count number of arguments.  */
147   for (argc = 0; argv[argc] != NULL; argc++)
148     ;
149 
150   /* Allocate new argument vector.  */
151   new_argv = XNMALLOC (1 + argc + 1, char *);
152 
153   /* Add an element upfront that can be used when argv[0] turns out to be a
154      script, not a program.
155      On Unix, this would be "/bin/sh". On native Windows, "sh" is actually
156      "sh.exe".  We have to omit the directory part and rely on the search in
157      PATH, because the mingw "mount points" are not visible inside Windows
158      CreateProcess().  */
159   *new_argv++ = "sh.exe";
160 
161   /* Put quoted arguments into the new argument vector.  */
162   for (i = 0; i < argc; i++)
163     {
164       const char *string = argv[i];
165 
166       if (string[0] == '\0')
167         new_argv[i] = xstrdup ("\"\"");
168       else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL)
169         {
170           bool quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL);
171           size_t length;
172           unsigned int backslashes;
173           const char *s;
174           char *quoted_string;
175           char *p;
176 
177           length = 0;
178           backslashes = 0;
179           if (quote_around)
180             length++;
181           for (s = string; *s != '\0'; s++)
182             {
183               char c = *s;
184               if (c == '"')
185                 length += backslashes + 1;
186               length++;
187               if (c == '\\')
188                 backslashes++;
189               else
190                 backslashes = 0;
191             }
192           if (quote_around)
193             length += backslashes + 1;
194 
195           quoted_string = (char *) xmalloc (length + 1);
196 
197           p = quoted_string;
198           backslashes = 0;
199           if (quote_around)
200             *p++ = '"';
201           for (s = string; *s != '\0'; s++)
202             {
203               char c = *s;
204               if (c == '"')
205                 {
206                   unsigned int j;
207                   for (j = backslashes + 1; j > 0; j--)
208                     *p++ = '\\';
209                 }
210               *p++ = c;
211               if (c == '\\')
212                 backslashes++;
213               else
214                 backslashes = 0;
215             }
216           if (quote_around)
217             {
218               unsigned int j;
219               for (j = backslashes; j > 0; j--)
220                 *p++ = '\\';
221               *p++ = '"';
222             }
223           *p = '\0';
224 
225           new_argv[i] = quoted_string;
226         }
227       else
228         new_argv[i] = (char *) string;
229     }
230   new_argv[argc] = NULL;
231 
232   return new_argv;
233 }
234