Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mark sockets as non-inheritable on Windows #2782

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions app/src/sys/win/process.c
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ sc_process_execute_p(const char *const argv[], HANDLE *handle,
HANDLE *pin, HANDLE *pout, HANDLE *perr) {
enum sc_process_result ret = SC_PROCESS_ERROR_GENERIC;

bool inherit_handles = pin || pout || perr;

SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
Expand Down Expand Up @@ -69,7 +71,7 @@ sc_process_execute_p(const char *const argv[], HANDLE *handle,
PROCESS_INFORMATION pi;
memset(&si, 0, sizeof(si));
si.cb = sizeof(si);
if (pin || pout || perr) {
if (inherit_handles) {
si.dwFlags = STARTF_USESTDHANDLES;
if (pin) {
si.hStdInput = stdin_read_handle;
Expand All @@ -95,8 +97,8 @@ sc_process_execute_p(const char *const argv[], HANDLE *handle,
goto error_close_stderr;
}

if (!CreateProcessW(NULL, wide, NULL, NULL, TRUE, 0, NULL, NULL, &si,
&pi)) {
if (!CreateProcessW(NULL, wide, NULL, NULL, inherit_handles, 0, NULL, NULL,
&si, &pi)) {
free(wide);
*handle = NULL;

Expand Down
21 changes: 21 additions & 0 deletions app/src/util/net.c
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,27 @@ net_perror(const char *s) {
sc_socket
net_socket(void) {
sc_raw_socket raw_sock = socket(AF_INET, SOCK_STREAM, 0);

#ifdef _WIN32
/* To be able to communicate with a child process via stdin, stdout and
* stderr, the CreateProcess() parameter bInheritHandles must be set to
* TRUE. But this causes *all* handles to be inherited, including sockets.
*
* One possibility could be to use an extended API to set extra attributes
* on process creation:
* - <https://stackoverflow.com/a/28185363/1987178>
* - <https://devblogs.microsoft.com/oldnewthing/20111216-00/?p=8873>
* But it seems that this API is not available on MinGW (it does not
* compile).
*
* As an alternative, explicitly mark all sockets as non-inheritable.
*/
if (!SetHandleInformation((HANDLE) raw_sock, HANDLE_FLAG_INHERIT, 0)) {
closesocket(raw_sock);
return SC_SOCKET_NONE;
}
#endif

sc_socket sock = wrap(raw_sock);
if (sock == SC_SOCKET_NONE) {
net_perror("socket");
Expand Down