1 /* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
2  *
3  * Permission is hereby granted, free of charge, to any person obtaining a copy
4  * of this software and associated documentation files (the "Software"), to
5  * deal in the Software without restriction, including without limitation the
6  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7  * sell copies of the Software, and to permit persons to whom the Software is
8  * furnished to do so, subject to the following conditions:
9  *
10  * The above copyright notice and this permission notice shall be included in
11  * all copies or substantial portions of the Software.
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
19  * IN THE SOFTWARE.
20  */
21 
22 #include <assert.h>
23 #include <io.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 
27 #include "uv.h"
28 #include "internal.h"
29 #include "handle-inl.h"
30 
31 
32 /*
33  * The `child_stdio_buffer` buffer has the following layout:
34  *   int number_of_fds
35  *   unsigned char crt_flags[number_of_fds]
36  *   HANDLE os_handle[number_of_fds]
37  */
38 #define CHILD_STDIO_SIZE(count)                     \
39     (sizeof(int) +                                  \
40      sizeof(unsigned char) * (count) +              \
41      sizeof(uintptr_t) * (count))
42 
43 #define CHILD_STDIO_COUNT(buffer)                   \
44     *((unsigned int*) (buffer))
45 
46 #define CHILD_STDIO_CRT_FLAGS(buffer, fd)           \
47     *((unsigned char*) (buffer) + sizeof(int) + fd)
48 
49 #define CHILD_STDIO_HANDLE(buffer, fd)              \
50     *((HANDLE*) ((unsigned char*) (buffer) +        \
51                  sizeof(int) +                      \
52                  sizeof(unsigned char) *            \
53                  CHILD_STDIO_COUNT((buffer)) +      \
54                  sizeof(HANDLE) * (fd)))
55 
56 
57 /* CRT file descriptor mode flags */
58 #define FOPEN       0x01
59 #define FEOFLAG     0x02
60 #define FCRLF       0x04
61 #define FPIPE       0x08
62 #define FNOINHERIT  0x10
63 #define FAPPEND     0x20
64 #define FDEV        0x40
65 #define FTEXT       0x80
66 
67 
68 /*
69  * Clear the HANDLE_FLAG_INHERIT flag from all HANDLEs that were inherited
70  * the parent process. Don't check for errors - the stdio handles may not be
71  * valid, or may be closed already. There is no guarantee that this function
72  * does a perfect job.
73  */
uv_disable_stdio_inheritance(void)74 void uv_disable_stdio_inheritance(void) {
75   HANDLE handle;
76   STARTUPINFOW si;
77 
78   /* Make the windows stdio handles non-inheritable. */
79   handle = GetStdHandle(STD_INPUT_HANDLE);
80   if (handle != NULL && handle != INVALID_HANDLE_VALUE)
81     SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0);
82 
83   handle = GetStdHandle(STD_OUTPUT_HANDLE);
84   if (handle != NULL && handle != INVALID_HANDLE_VALUE)
85     SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0);
86 
87   handle = GetStdHandle(STD_ERROR_HANDLE);
88   if (handle != NULL && handle != INVALID_HANDLE_VALUE)
89     SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0);
90 
91   /* Make inherited CRT FDs non-inheritable. */
92   GetStartupInfoW(&si);
93   if (uv__stdio_verify(si.lpReserved2, si.cbReserved2))
94     uv__stdio_noinherit(si.lpReserved2);
95 }
96 
97 
uv__create_stdio_pipe_pair(uv_loop_t * loop,uv_pipe_t * server_pipe,HANDLE * child_pipe_ptr,unsigned int flags)98 static int uv__create_stdio_pipe_pair(uv_loop_t* loop,
99     uv_pipe_t* server_pipe, HANDLE* child_pipe_ptr, unsigned int flags) {
100   char pipe_name[64];
101   SECURITY_ATTRIBUTES sa;
102   DWORD server_access = 0;
103   DWORD client_access = 0;
104   HANDLE child_pipe = INVALID_HANDLE_VALUE;
105   int err;
106 
107   if (flags & UV_READABLE_PIPE) {
108     /* The server needs inbound access too, otherwise CreateNamedPipe() */
109     /* won't give us the FILE_READ_ATTRIBUTES permission. We need that to */
110     /* probe the state of the write buffer when we're trying to shutdown */
111     /* the pipe. */
112     server_access |= PIPE_ACCESS_OUTBOUND | PIPE_ACCESS_INBOUND;
113     client_access |= GENERIC_READ | FILE_WRITE_ATTRIBUTES;
114   }
115   if (flags & UV_WRITABLE_PIPE) {
116     server_access |= PIPE_ACCESS_INBOUND;
117     client_access |= GENERIC_WRITE | FILE_READ_ATTRIBUTES;
118   }
119 
120   /* Create server pipe handle. */
121   err = uv_stdio_pipe_server(loop,
122                              server_pipe,
123                              server_access,
124                              pipe_name,
125                              sizeof(pipe_name));
126   if (err)
127     goto error;
128 
129   /* Create child pipe handle. */
130   sa.nLength = sizeof sa;
131   sa.lpSecurityDescriptor = NULL;
132   sa.bInheritHandle = TRUE;
133 
134   child_pipe = CreateFileA(pipe_name,
135                            client_access,
136                            0,
137                            &sa,
138                            OPEN_EXISTING,
139                            server_pipe->ipc ? FILE_FLAG_OVERLAPPED : 0,
140                            NULL);
141   if (child_pipe == INVALID_HANDLE_VALUE) {
142     err = GetLastError();
143     goto error;
144   }
145 
146 #ifndef NDEBUG
147   /* Validate that the pipe was opened in the right mode. */
148   {
149     DWORD mode;
150     BOOL r = GetNamedPipeHandleState(child_pipe,
151                                      &mode,
152                                      NULL,
153                                      NULL,
154                                      NULL,
155                                      NULL,
156                                      0);
157     assert(r == TRUE);
158     assert(mode == (PIPE_READMODE_BYTE | PIPE_WAIT));
159   }
160 #endif
161 
162   /* Do a blocking ConnectNamedPipe.  This should not block because we have */
163   /* both ends of the pipe created. */
164   if (!ConnectNamedPipe(server_pipe->handle, NULL)) {
165     if (GetLastError() != ERROR_PIPE_CONNECTED) {
166       err = GetLastError();
167       goto error;
168     }
169   }
170 
171   /* The server end is now readable and/or writable. */
172   if (flags & UV_READABLE_PIPE)
173     server_pipe->flags |= UV_HANDLE_WRITABLE;
174   if (flags & UV_WRITABLE_PIPE)
175     server_pipe->flags |= UV_HANDLE_READABLE;
176 
177   *child_pipe_ptr = child_pipe;
178   return 0;
179 
180  error:
181   if (server_pipe->handle != INVALID_HANDLE_VALUE) {
182     uv_pipe_cleanup(loop, server_pipe);
183   }
184 
185   if (child_pipe != INVALID_HANDLE_VALUE) {
186     CloseHandle(child_pipe);
187   }
188 
189   return err;
190 }
191 
192 
uv__duplicate_handle(uv_loop_t * loop,HANDLE handle,HANDLE * dup)193 static int uv__duplicate_handle(uv_loop_t* loop, HANDLE handle, HANDLE* dup) {
194   HANDLE current_process;
195 
196 
197   /* _get_osfhandle will sometimes return -2 in case of an error. This seems */
198   /* to happen when fd <= 2 and the process' corresponding stdio handle is */
199   /* set to NULL. Unfortunately DuplicateHandle will happily duplicate */
200   /* (HANDLE) -2, so this situation goes unnoticed until someone tries to */
201   /* use the duplicate. Therefore we filter out known-invalid handles here. */
202   if (handle == INVALID_HANDLE_VALUE ||
203       handle == NULL ||
204       handle == (HANDLE) -2) {
205     *dup = INVALID_HANDLE_VALUE;
206     return ERROR_INVALID_HANDLE;
207   }
208 
209   current_process = GetCurrentProcess();
210 
211   if (!DuplicateHandle(current_process,
212                        handle,
213                        current_process,
214                        dup,
215                        0,
216                        TRUE,
217                        DUPLICATE_SAME_ACCESS)) {
218     *dup = INVALID_HANDLE_VALUE;
219     return GetLastError();
220   }
221 
222   return 0;
223 }
224 
225 
uv__duplicate_fd(uv_loop_t * loop,int fd,HANDLE * dup)226 static int uv__duplicate_fd(uv_loop_t* loop, int fd, HANDLE* dup) {
227   HANDLE handle;
228 
229   if (fd == -1) {
230     *dup = INVALID_HANDLE_VALUE;
231     return ERROR_INVALID_HANDLE;
232   }
233 
234   handle = uv__get_osfhandle(fd);
235   return uv__duplicate_handle(loop, handle, dup);
236 }
237 
238 
uv__create_nul_handle(HANDLE * handle_ptr,DWORD access)239 int uv__create_nul_handle(HANDLE* handle_ptr,
240     DWORD access) {
241   HANDLE handle;
242   SECURITY_ATTRIBUTES sa;
243 
244   sa.nLength = sizeof sa;
245   sa.lpSecurityDescriptor = NULL;
246   sa.bInheritHandle = TRUE;
247 
248   handle = CreateFileW(L"NUL",
249                        access,
250                        FILE_SHARE_READ | FILE_SHARE_WRITE,
251                        &sa,
252                        OPEN_EXISTING,
253                        0,
254                        NULL);
255   if (handle == INVALID_HANDLE_VALUE) {
256     return GetLastError();
257   }
258 
259   *handle_ptr = handle;
260   return 0;
261 }
262 
263 
uv__stdio_create(uv_loop_t * loop,const uv_process_options_t * options,BYTE ** buffer_ptr)264 int uv__stdio_create(uv_loop_t* loop,
265                      const uv_process_options_t* options,
266                      BYTE** buffer_ptr) {
267   BYTE* buffer;
268   int count, i;
269   int err;
270 
271   count = options->stdio_count;
272 
273   if (count < 0 || count > 255) {
274     /* Only support FDs 0-255 */
275     return ERROR_NOT_SUPPORTED;
276   } else if (count < 3) {
277     /* There should always be at least 3 stdio handles. */
278     count = 3;
279   }
280 
281   /* Allocate the child stdio buffer */
282   buffer = (BYTE*) malloc(CHILD_STDIO_SIZE(count));
283   if (buffer == NULL) {
284     return ERROR_OUTOFMEMORY;
285   }
286 
287   /* Prepopulate the buffer with INVALID_HANDLE_VALUE handles so we can */
288   /* clean up on failure. */
289   CHILD_STDIO_COUNT(buffer) = count;
290   for (i = 0; i < count; i++) {
291     CHILD_STDIO_CRT_FLAGS(buffer, i) = 0;
292     CHILD_STDIO_HANDLE(buffer, i) = INVALID_HANDLE_VALUE;
293   }
294 
295   for (i = 0; i < count; i++) {
296     uv_stdio_container_t fdopt;
297     if (i < options->stdio_count) {
298       fdopt = options->stdio[i];
299     } else {
300       fdopt.flags = UV_IGNORE;
301     }
302 
303     switch (fdopt.flags & (UV_IGNORE | UV_CREATE_PIPE | UV_INHERIT_FD |
304             UV_INHERIT_STREAM)) {
305       case UV_IGNORE:
306         /* Starting a process with no stdin/stout/stderr can confuse it. */
307         /* So no matter what the user specified, we make sure the first */
308         /* three FDs are always open in their typical modes, e.g. stdin */
309         /* be readable and stdout/err should be writable. For FDs > 2, don't */
310         /* do anything - all handles in the stdio buffer are initialized with */
311         /* INVALID_HANDLE_VALUE, which should be okay. */
312         if (i <= 2) {
313           DWORD access = (i == 0) ? FILE_GENERIC_READ :
314                                     FILE_GENERIC_WRITE | FILE_READ_ATTRIBUTES;
315 
316           err = uv__create_nul_handle(&CHILD_STDIO_HANDLE(buffer, i),
317                                       access);
318           if (err)
319             goto error;
320 
321           CHILD_STDIO_CRT_FLAGS(buffer, i) = FOPEN | FDEV;
322         }
323         break;
324 
325       case UV_CREATE_PIPE: {
326         /* Create a pair of two connected pipe ends; one end is turned into */
327         /* an uv_pipe_t for use by the parent. The other one is given to */
328         /* the child. */
329         uv_pipe_t* parent_pipe = (uv_pipe_t*) fdopt.data.stream;
330         HANDLE child_pipe;
331 
332         /* Create a new, connected pipe pair. stdio[i].stream should point */
333         /* to an uninitialized, but not connected pipe handle. */
334         assert(fdopt.data.stream->type == UV_NAMED_PIPE);
335         assert(!(fdopt.data.stream->flags & UV_HANDLE_CONNECTION));
336         assert(!(fdopt.data.stream->flags & UV_HANDLE_PIPESERVER));
337 
338         err = uv__create_stdio_pipe_pair(loop,
339                                          parent_pipe,
340                                          &child_pipe,
341                                          fdopt.flags);
342         if (err)
343           goto error;
344 
345         CHILD_STDIO_HANDLE(buffer, i) = child_pipe;
346         CHILD_STDIO_CRT_FLAGS(buffer, i) = FOPEN | FPIPE;
347         break;
348       }
349 
350       case UV_INHERIT_FD: {
351         /* Inherit a raw FD. */
352         HANDLE child_handle;
353 
354         /* Make an inheritable duplicate of the handle. */
355         err = uv__duplicate_fd(loop, fdopt.data.fd, &child_handle);
356         if (err) {
357           /* If fdopt.data.fd is not valid and fd fd <= 2, then ignore the */
358           /* error. */
359           if (fdopt.data.fd <= 2 && err == ERROR_INVALID_HANDLE) {
360             CHILD_STDIO_CRT_FLAGS(buffer, i) = 0;
361             CHILD_STDIO_HANDLE(buffer, i) = INVALID_HANDLE_VALUE;
362             break;
363           }
364           goto error;
365         }
366 
367         /* Figure out what the type is. */
368         switch (GetFileType(child_handle)) {
369           case FILE_TYPE_DISK:
370             CHILD_STDIO_CRT_FLAGS(buffer, i) = FOPEN;
371             break;
372 
373           case FILE_TYPE_PIPE:
374             CHILD_STDIO_CRT_FLAGS(buffer, i) = FOPEN | FPIPE;
375 
376           case FILE_TYPE_CHAR:
377           case FILE_TYPE_REMOTE:
378             CHILD_STDIO_CRT_FLAGS(buffer, i) = FOPEN | FDEV;
379             break;
380 
381           case FILE_TYPE_UNKNOWN:
382             if (GetLastError() != 0) {
383               err = GetLastError();
384               CloseHandle(child_handle);
385               goto error;
386             }
387             CHILD_STDIO_CRT_FLAGS(buffer, i) = FOPEN | FDEV;
388             break;
389 
390           default:
391             assert(0);
392         }
393 
394         CHILD_STDIO_HANDLE(buffer, i) = child_handle;
395         break;
396       }
397 
398       case UV_INHERIT_STREAM: {
399         /* Use an existing stream as the stdio handle for the child. */
400         HANDLE stream_handle, child_handle;
401         unsigned char crt_flags;
402         uv_stream_t* stream = fdopt.data.stream;
403 
404         /* Leech the handle out of the stream. */
405         if (stream->type == UV_TTY) {
406           stream_handle = ((uv_tty_t*) stream)->handle;
407           crt_flags = FOPEN | FDEV;
408         } else if (stream->type == UV_NAMED_PIPE &&
409                    stream->flags & UV_HANDLE_CONNECTED) {
410           stream_handle = ((uv_pipe_t*) stream)->handle;
411           crt_flags = FOPEN | FPIPE;
412         } else {
413           stream_handle = INVALID_HANDLE_VALUE;
414           crt_flags = 0;
415         }
416 
417         if (stream_handle == NULL ||
418             stream_handle == INVALID_HANDLE_VALUE) {
419           /* The handle is already closed, or not yet created, or the */
420           /* stream type is not supported. */
421           err = ERROR_NOT_SUPPORTED;
422           goto error;
423         }
424 
425         /* Make an inheritable copy of the handle. */
426         if (uv__duplicate_handle(loop,
427                              stream_handle,
428                              &child_handle) < 0) {
429           goto error;
430         }
431 
432         CHILD_STDIO_HANDLE(buffer, i) = child_handle;
433         CHILD_STDIO_CRT_FLAGS(buffer, i) = crt_flags;
434         break;
435       }
436 
437       default:
438         assert(0);
439     }
440   }
441 
442   *buffer_ptr  = buffer;
443   return 0;
444 
445  error:
446   uv__stdio_destroy(buffer);
447   return err;
448 }
449 
450 
uv__stdio_destroy(BYTE * buffer)451 void uv__stdio_destroy(BYTE* buffer) {
452   int i, count;
453 
454   count = CHILD_STDIO_COUNT(buffer);
455   for (i = 0; i < count; i++) {
456     HANDLE handle = CHILD_STDIO_HANDLE(buffer, i);
457     if (handle != INVALID_HANDLE_VALUE) {
458       CloseHandle(handle);
459     }
460   }
461 
462   free(buffer);
463 }
464 
465 
uv__stdio_noinherit(BYTE * buffer)466 void uv__stdio_noinherit(BYTE* buffer) {
467   int i, count;
468 
469   count = CHILD_STDIO_COUNT(buffer);
470   for (i = 0; i < count; i++) {
471     HANDLE handle = CHILD_STDIO_HANDLE(buffer, i);
472     if (handle != INVALID_HANDLE_VALUE) {
473       SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0);
474     }
475   }
476 }
477 
478 
uv__stdio_verify(BYTE * buffer,WORD size)479 int uv__stdio_verify(BYTE* buffer, WORD size) {
480   unsigned int count;
481 
482   /* Check the buffer pointer. */
483   if (buffer == NULL)
484     return 0;
485 
486   /* Verify that the buffer is at least big enough to hold the count. */
487   if (size < CHILD_STDIO_SIZE(0))
488     return 0;
489 
490   /* Verify if the count is within range. */
491   count = CHILD_STDIO_COUNT(buffer);
492   if (count > 256)
493     return 0;
494 
495   /* Verify that the buffer size is big enough to hold info for N FDs. */
496   if (size < CHILD_STDIO_SIZE(count))
497     return 0;
498 
499   return 1;
500 }
501 
502 
uv__stdio_size(BYTE * buffer)503 WORD uv__stdio_size(BYTE* buffer) {
504   return (WORD) CHILD_STDIO_SIZE(CHILD_STDIO_COUNT((buffer)));
505 }
506 
507 
uv__stdio_handle(BYTE * buffer,int fd)508 HANDLE uv__stdio_handle(BYTE* buffer, int fd) {
509   return CHILD_STDIO_HANDLE(buffer, fd);
510 }
511