1 /* Auxiliary functions for the creation of subprocesses. Native Windows API.
2 Copyright (C) 2001, 2003-2017 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 <http://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 #include "msvc-nothrow.h"
34
35 #include "cloexec.h"
36 #include "xalloc.h"
37
38 /* Duplicates a file handle, making the copy uninheritable.
39 Returns -1 for a file handle that is equivalent to closed. */
40 static int
dup_noinherit(int fd)41 dup_noinherit (int fd)
42 {
43 fd = dup_cloexec (fd);
44 if (fd < 0 && errno == EMFILE)
45 error (EXIT_FAILURE, errno, _("_open_osfhandle failed"));
46
47 return fd;
48 }
49
50 /* Returns a file descriptor equivalent to FD, except that the resulting file
51 descriptor is none of STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO.
52 FD must be open and non-inheritable. The result will be non-inheritable as
53 well.
54 If FD < 0, FD itself is returned. */
55 static int
fd_safer_noinherit(int fd)56 fd_safer_noinherit (int fd)
57 {
58 if (STDIN_FILENO <= fd && fd <= STDERR_FILENO)
59 {
60 /* The recursion depth is at most 3. */
61 int nfd = fd_safer_noinherit (dup_noinherit (fd));
62 int saved_errno = errno;
63 close (fd);
64 errno = saved_errno;
65 return nfd;
66 }
67 return fd;
68 }
69
70 /* Duplicates a file handle, making the copy uninheritable and ensuring the
71 result is none of STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO.
72 Returns -1 for a file handle that is equivalent to closed. */
73 static int
dup_safer_noinherit(int fd)74 dup_safer_noinherit (int fd)
75 {
76 return fd_safer_noinherit (dup_noinherit (fd));
77 }
78
79 /* Undoes the effect of TEMPFD = dup_safer_noinherit (ORIGFD); */
80 static void
undup_safer_noinherit(int tempfd,int origfd)81 undup_safer_noinherit (int tempfd, int origfd)
82 {
83 if (tempfd >= 0)
84 {
85 if (dup2 (tempfd, origfd) < 0)
86 error (EXIT_FAILURE, errno, _("cannot restore fd %d: dup2 failed"),
87 origfd);
88 close (tempfd);
89 }
90 else
91 {
92 /* origfd was closed or open to no handle at all. Set it to a closed
93 state. This is (nearly) equivalent to the original state. */
94 close (origfd);
95 }
96 }
97
98 /* Prepares an argument vector before calling spawn().
99 Note that spawn() does not by itself call the command interpreter
100 (getenv ("COMSPEC") != NULL ? getenv ("COMSPEC") :
101 ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
102 GetVersionEx(&v);
103 v.dwPlatformId == VER_PLATFORM_WIN32_NT;
104 }) ? "cmd.exe" : "command.com").
105 Instead it simply concatenates the arguments, separated by ' ', and calls
106 CreateProcess(). We must quote the arguments since Windows CreateProcess()
107 interprets characters like ' ', '\t', '\\', '"' (but not '<' and '>') in a
108 special way:
109 - Space and tab are interpreted as delimiters. They are not treated as
110 delimiters if they are surrounded by double quotes: "...".
111 - Unescaped double quotes are removed from the input. Their only effect is
112 that within double quotes, space and tab are treated like normal
113 characters.
114 - Backslashes not followed by double quotes are not special.
115 - But 2*n+1 backslashes followed by a double quote become
116 n backslashes followed by a double quote (n >= 0):
117 \" -> "
118 \\\" -> \"
119 \\\\\" -> \\"
120 - '*', '?' characters may get expanded through wildcard expansion in the
121 callee: By default, in the callee, the initialization code before main()
122 takes the result of GetCommandLine(), wildcard-expands it, and passes it
123 to main(). The exceptions to this rule are:
124 - programs that inspect GetCommandLine() and ignore argv,
125 - mingw programs that have a global variable 'int _CRT_glob = 0;',
126 - Cygwin programs, when invoked from a Cygwin program.
127 */
128 #ifndef __KLIBC__
129 # 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*?"
130 # 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"
131 #else
132 # define SHELL_SPECIAL_CHARS ""
133 # define SHELL_SPACE_CHARS ""
134 #endif
135 static char **
prepare_spawn(char ** argv)136 prepare_spawn (char **argv)
137 {
138 size_t argc;
139 char **new_argv;
140 size_t i;
141
142 /* Count number of arguments. */
143 for (argc = 0; argv[argc] != NULL; argc++)
144 ;
145
146 /* Allocate new argument vector. */
147 new_argv = XNMALLOC (1 + argc + 1, char *);
148
149 /* Add an element upfront that can be used when argv[0] turns out to be a
150 script, not a program.
151 On Unix, this would be "/bin/sh". On native Windows, "sh" is actually
152 "sh.exe". We have to omit the directory part and rely on the search in
153 PATH, because the mingw "mount points" are not visible inside Windows
154 CreateProcess(). */
155 *new_argv++ = "sh.exe";
156
157 /* Put quoted arguments into the new argument vector. */
158 for (i = 0; i < argc; i++)
159 {
160 const char *string = argv[i];
161
162 if (string[0] == '\0')
163 new_argv[i] = xstrdup ("\"\"");
164 else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL)
165 {
166 bool quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL);
167 size_t length;
168 unsigned int backslashes;
169 const char *s;
170 char *quoted_string;
171 char *p;
172
173 length = 0;
174 backslashes = 0;
175 if (quote_around)
176 length++;
177 for (s = string; *s != '\0'; s++)
178 {
179 char c = *s;
180 if (c == '"')
181 length += backslashes + 1;
182 length++;
183 if (c == '\\')
184 backslashes++;
185 else
186 backslashes = 0;
187 }
188 if (quote_around)
189 length += backslashes + 1;
190
191 quoted_string = (char *) xmalloc (length + 1);
192
193 p = quoted_string;
194 backslashes = 0;
195 if (quote_around)
196 *p++ = '"';
197 for (s = string; *s != '\0'; s++)
198 {
199 char c = *s;
200 if (c == '"')
201 {
202 unsigned int j;
203 for (j = backslashes + 1; j > 0; j--)
204 *p++ = '\\';
205 }
206 *p++ = c;
207 if (c == '\\')
208 backslashes++;
209 else
210 backslashes = 0;
211 }
212 if (quote_around)
213 {
214 unsigned int j;
215 for (j = backslashes; j > 0; j--)
216 *p++ = '\\';
217 *p++ = '"';
218 }
219 *p = '\0';
220
221 new_argv[i] = quoted_string;
222 }
223 else
224 new_argv[i] = (char *) string;
225 }
226 new_argv[argc] = NULL;
227
228 return new_argv;
229 }
230