Skip to content

Windows: replace socket with WSASocket and set WSA_FLAG_NO_HANDLE_INHERIT - #10809

Merged
nojb merged 2 commits into
ocaml:trunkfrom
MisterDA:windows-socket-WSASocket-WSA_FLAG_NO_HANDLE_INHERIT
Apr 5, 2022
Merged

nojb merged 2 commits into
ocaml:trunkfrom
MisterDA:windows-socket-WSASocket-WSA_FLAG_NO_HANDLE_INHERIT

Conversation

@MisterDA

@MisterDA MisterDA commented Dec 3, 2021

Copy link
Copy Markdown
Contributor

The call to

socket(domain, type, protocol);

is equivalent to

WSASocket(domain, type, protocol, NULL, 0, WSA_FLAG_OVERLAPPED);

the latter offering more (needed) control over the creation of
sockets.

On Windows, in order to mark sockets non-inheritable (close-on-exec),
it is sometimes not sufficient to use SetHandleInformation. There's
some explanation why in 1 and KB2398202.

Introduced in the hotfix KB2398202 and supported on Windows 7 with
SP1, Windows Server 2008 R2 with SP1, and later, the flag
WSA_FLAG_NO_HANDLE_INHERIT can be used with WSASocket to create a
non-inheritable socket.

We can still call SetHandleInformation to clear the inheritable flag
on the socket in case the flag isn't supported (running on an early
Windows Vista or 7).

@MisterDA
MisterDA force-pushed the windows-socket-WSASocket-WSA_FLAG_NO_HANDLE_INHERIT branch from 8b7dbfe to cadb0cf Compare December 3, 2021 14:21
MisterDA added a commit to MisterDA/lwt that referenced this pull request Dec 6, 2021
On Windows, in order to mark sockets non-inheritable (close-on-exec),
it is sometimes not sufficient to use SetHandleInformation. There's
some explanation why in [1] and [KB2398202].

Introduced in the hotfix [KB2398202] and supported on Windows 7 with
SP1, Windows Server 2008 R2 with SP1, and later, the flag
WSA_FLAG_NO_HANDLE_INHERIT can be used with WSASocket to create a
non-inheritable socket.

We can still call SetHandleInformation to clear the inheritable flag
on the socket in case the flag isn't supported (running on an early
Windows Vista or 7).

Related OCaml PR:
- ocaml/ocaml#10809.

[1]: https://stackoverflow.com/questions/12058911/can-tcp-socket-handles-be-set-not-inheritable
[KB2398202]: https://support.microsoft.com/en-us/topic/an-application-may-stop-responding-when-the-application-closes-a-socket-connection-or-shuts-down-41321a1f-d80c-6975-98df-ae499d63133c

@xavierleroy xavierleroy left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like the idea. But could you please clarify when WAS_FLAG_NO_HANDLE_INHERIT is expected to work, and when it is expected to not work and the old implementation should be used instead?

Comment thread otherlibs/win32unix/dup.c Outdated
Comment on lines +50 to +58
if (! inherit)
flags |= WSA_FLAG_NO_HANDLE_INHERIT;

newsock = WSASocket(info.iAddressFamily, info.iSocketType, info.iProtocol,
&info, 0, WSA_FLAG_OVERLAPPED);
&info, 0, flags);
if (INVALID_SOCKET == newsock)
win32_maperr(WSAGetLastError());
else
win_set_inherit((HANDLE) newsock, inherit);
else if (! inherit)
win_set_inherit((HANDLE) newsock, FALSE);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we really need to set WAS_FLAG_NO_HANDLE_INHERIT and to call win_set_inherit afterwards?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For old systems not supporting the flag, we still need to call win_set_inherit.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, but I would expect these old systems not supporting the flag to fail in WSASocket...

In other words, the code I was expecting is something like

  if WSA_FLAG_NO_HANDLE_INHERIT is supported:
    add it to flags if necessary
    call WSASocket
  else:
    call WSASocket
    call win_set_inherit

@MisterDA MisterDA Dec 20, 2021 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, but I would expect these old systems not supporting the flag to fail in WSASocket...

You're probably right: I have tested calling WSASocket with high, undefined values of the flag parameter. I was expecting that it would ignore undefined values, but it fails as you expected with WSAEPROTOTYPE. I have tested it on Windows 10, I wasn't able to test on a older system (finding the VM images is tricky).
I was inspired by the code in libuv which also IIUC assumes WSASocket ignores the parameter, or it means that even with the flag, WSASocket could return an inheritable socket (and that would be very scary). You may have found a bug in libuv!

It's also possible that OCaml is build on a system defining WSA_FLAG_NO_HANDLE_INHERIT but run on an old system where winsock2 doesn't support this flag, or the opposite, OCaml may be build on an old system without the definition but run on a newer system.

What scenario do we want to support? I don't see a good way to tell at runtime whether the flag is supported or not, I think the best we can do is to try WSASocket with the flag and if it fails, retry without and use SetHandleInformation.

If we support old ⇋ new the wrapper may look like this, where we're forced to use both the flag and SetHandleInformation:
SOCKET win32_socket(int domain, int type, int protocol,
                    LPWSAPROTOCOL_INFO info,
                    BOOL inherit)
{
  SOCKET s;
  DWORD flags = WSA_FLAG_OVERLAPPED;

#ifndef WSA_FLAG_NO_HANDLE_INHERIT
#define WSA_FLAG_NO_HANDLE_INHERIT 0x80
#endif

  if (! inherit)
    flags |= WSA_FLAG_NO_HANDLE_INHERIT;

  s = WSASocket(domain, type, protocol, info, 0, flags);
  if (s == INVALID_SOCKET) {
    if (! inherit && WSAGetLastError() == WSAEPROTOTYPE) {
      /* WSASocket probably doesn't suport WSA_FLAG_NO_HANDLE_INHERIT,
       * retry without. */
      flags &= ~(DWORD)WSA_FLAG_NO_HANDLE_INHERIT;
      s = WSASocket(domain, type, protocol, info, 0, flags);
      if (s == INVALID_SOCKET)
        goto err;
      win_set_inherit((HANDLE) s, FALSE);
      return s;
    }
    goto err;
  }

  if (! inherit)
    win_set_inherit((HANDLE) s, FALSE);

  return s;

err:
  win32_maperr(WSAGetLastError());
  return INVALID_SOCKET;
}
If however we support only new → old we could do:
SOCKET win32_socket(int domain, int type, int protocol,
                    LPWSAPROTOCOL_INFO info,
                    BOOL inherit)
{
  SOCKET s;
  DWORD flags = WSA_FLAG_OVERLAPPED;

#ifdef WSA_FLAG_NO_HANDLE_INHERIT
  if (! inherit)
    flags |= WSA_FLAG_NO_HANDLE_INHERIT;
#endif

  s = WSASocket(domain, type, protocol, info, 0, flags);
  if (s == INVALID_SOCKET) {
#ifdef WSA_FLAG_NO_HANDLE_INHERIT
    if (! inherit && WSAGetLastError() == WSAEPROTOTYPE) {
      /* WSASocket probably doesn't suport WSA_FLAG_NO_HANDLE_INHERIT,
       * retry without. */
      flags &= ~(DWORD)WSA_FLAG_NO_HANDLE_INHERIT;
      s = WSASocket(domain, type, protocol, info, 0, flags);
      if (s == INVALID_SOCKET)
        goto err;
      win_set_inherit((HANDLE) s, FALSE);
      return s;
    }
#endif
    goto err;
  }

#ifndef WSA_FLAG_NO_HANDLE_INHERIT
  if (! inherit)
    win_set_inherit((HANDLE) s, FALSE);
#endif

  return s;

err:
  win32_maperr(WSAGetLastError());
  return INVALID_SOCKET;
}

I don't think we want to test at startup whether the runtime supports the flag by creating a dummy socket, but that's a possibility too.

@MisterDA
MisterDA force-pushed the windows-socket-WSASocket-WSA_FLAG_NO_HANDLE_INHERIT branch from cadb0cf to 4995884 Compare December 17, 2021 15:07
@MisterDA

Copy link
Copy Markdown
Contributor Author

I've rewritten the commit message with (I hope) more precise information:

On Windows, creating a socket then using SetHandleInformation on it
to make it non-inheritable (close-on-exec) is prone to a race
condition: the socket isn't created atomically non-inheritable and a
child process could inherit the socket between its creation and the
call to SetHandleInformation. This can lead to a deadlock of the
parent process, as explained in KB2398202.

The hotfix KB2398202 introduced the WSA_FLAG_NO_HANDLE_INHERIT to
be used with WSASocket to create non-inheritable sockets
atomically. It serves the same purpose as SOCK_CLOEXEC for
socket(2) on Unix systems.

This flag is supported on Windows 7 with SP1, Windows Server 2008 R2
with SP1, and later. On these newer systems, we don't need the old
implementation, but for older systems there's no way to prevent the
race condition. If we keep the old implementation and set the
non-inheritable bit with SetHandleInformation the closest to the
WSASocket call we're doing the maximum to protect against the race
condition. It's also the only way to make the socket non-inheritable.

@MisterDA
MisterDA force-pushed the windows-socket-WSASocket-WSA_FLAG_NO_HANDLE_INHERIT branch 2 times, most recently from ff177ce to d2741d5 Compare January 11, 2022 12:20
@MisterDA

Copy link
Copy Markdown
Contributor Author

Thanks to @dra27 extensive testing, we now know that WSASocket
errors with WSAEINVAL when it doesn't recognize
WSA_FLAG_NO_HANDLE_INHERIT from Windows XP to Windows 7 pre-SP1, on
x86 and x64. Your instinct @xavierleroy was right!

I've updated and simplified the code: if the socket is to be created
non-inheritable (cloexec), try WSASocket with the flag. If it fails
with WSAEINVAL, retry without the flag and use SetHandleInformation.

MisterDA added a commit to MisterDA/lwt that referenced this pull request Feb 1, 2022
On Windows, in order to mark sockets non-inheritable (close-on-exec),
it is sometimes not sufficient to use SetHandleInformation. There's
some explanation why in [1] and [KB2398202].

Introduced in the hotfix [KB2398202] and supported on Windows 7 with
SP1, Windows Server 2008 R2 with SP1, and later, the flag
WSA_FLAG_NO_HANDLE_INHERIT can be used with WSASocket to create a
non-inheritable socket.

We can still call SetHandleInformation to clear the inheritable flag
on the socket in case the flag isn't supported (running on an early
Windows Vista or 7).

Related OCaml PR:
- ocaml/ocaml#10809.

[1]: https://stackoverflow.com/questions/12058911/can-tcp-socket-handles-be-set-not-inheritable
[KB2398202]: https://support.microsoft.com/en-us/topic/an-application-may-stop-responding-when-the-application-closes-a-socket-connection-or-shuts-down-41321a1f-d80c-6975-98df-ae499d63133c
MisterDA added a commit to MisterDA/lwt that referenced this pull request Feb 8, 2022
On Windows, in order to mark sockets non-inheritable (close-on-exec),
it is sometimes not sufficient to use SetHandleInformation. There's
some explanation why in [1] and [KB2398202].

Introduced in the hotfix [KB2398202] and supported on Windows 7 with
SP1, Windows Server 2008 R2 with SP1, and later, the flag
WSA_FLAG_NO_HANDLE_INHERIT can be used with WSASocket to create a
non-inheritable socket.

We can still call SetHandleInformation to clear the inheritable flag
on the socket in case the flag isn't supported (running on an early
Windows Vista or 7).

Related OCaml PR:
- ocaml/ocaml#10809.

[1]: https://stackoverflow.com/questions/12058911/can-tcp-socket-handles-be-set-not-inheritable
[KB2398202]: https://support.microsoft.com/en-us/topic/an-application-may-stop-responding-when-the-application-closes-a-socket-connection-or-shuts-down-41321a1f-d80c-6975-98df-ae499d63133c
MisterDA added a commit to MisterDA/lwt that referenced this pull request Feb 9, 2022
On Windows, in order to mark sockets non-inheritable (close-on-exec),
it is sometimes not sufficient to use SetHandleInformation. There's
some explanation why in [1] and [KB2398202].

Introduced in the hotfix [KB2398202] and supported on Windows 7 with
SP1, Windows Server 2008 R2 with SP1, and later, the flag
WSA_FLAG_NO_HANDLE_INHERIT can be used with WSASocket to create a
non-inheritable socket.

We can still call SetHandleInformation to clear the inheritable flag
on the socket in case the flag isn't supported (running on an early
Windows Vista or 7).

Related OCaml PR:
- ocaml/ocaml#10809.

[1]: https://stackoverflow.com/questions/12058911/can-tcp-socket-handles-be-set-not-inheritable
[KB2398202]: https://support.microsoft.com/en-us/topic/an-application-may-stop-responding-when-the-application-closes-a-socket-connection-or-shuts-down-41321a1f-d80c-6975-98df-ae499d63133c
MisterDA added a commit to MisterDA/lwt that referenced this pull request Feb 9, 2022
On Windows, in order to mark sockets non-inheritable (close-on-exec),
it is sometimes not sufficient to use SetHandleInformation. There's
some explanation why in [1] and [KB2398202].

Introduced in the hotfix [KB2398202] and supported on Windows 7 with
SP1, Windows Server 2008 R2 with SP1, and later, the flag
WSA_FLAG_NO_HANDLE_INHERIT can be used with WSASocket to create a
non-inheritable socket.

We can still call SetHandleInformation to clear the inheritable flag
on the socket in case the flag isn't supported (running on an early
Windows Vista or 7).

Related OCaml PR:
- ocaml/ocaml#10809.

[1]: https://stackoverflow.com/questions/12058911/can-tcp-socket-handles-be-set-not-inheritable
[KB2398202]: https://support.microsoft.com/en-us/topic/an-application-may-stop-responding-when-the-application-closes-a-socket-connection-or-shuts-down-41321a1f-d80c-6975-98df-ae499d63133c
@MisterDA
MisterDA force-pushed the windows-socket-WSASocket-WSA_FLAG_NO_HANDLE_INHERIT branch from d2741d5 to a091b98 Compare February 28, 2022 16:10
@MisterDA
MisterDA force-pushed the windows-socket-WSASocket-WSA_FLAG_NO_HANDLE_INHERIT branch from a091b98 to dedfb41 Compare March 17, 2022 16:20

@xavierleroy xavierleroy left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had a second look. Globally it looks good to me, but I would suggest to declare win32_socket in unixsupport.h rather than in dup.c and in socketpair.c, it's less error-prone this way.

Also, it would be good to have a review from @dra27 or @nojb .

The call to

    socket(domain, type, protocol);

is equivalent to

    WSASocket(domain, type, protocol, NULL, 0, WSA_FLAG_OVERLAPPED);

the latter offering more (needed) control over the creation of
sockets.
@MisterDA
MisterDA force-pushed the windows-socket-WSASocket-WSA_FLAG_NO_HANDLE_INHERIT branch from dedfb41 to 9e06847 Compare March 25, 2022 11:09
On Windows, creating a socket then using `SetHandleInformation` on it
to make it non-inheritable (close-on-exec) is prone to a race
condition: the socket isn't created atomically non-inheritable and a
child process could inherit the socket between its creation and the
call to `SetHandleInformation`. This can lead to a deadlock of the
parent process, as explained in [KB2398202].

The hotfix [KB2398202] introduced the `WSA_FLAG_NO_HANDLE_INHERIT` to
be used with `WSASocket` to create non-inheritable sockets
atomically. It serves the same purpose as `SOCK_CLOEXEC` for
`socket(2)` on Unix systems.

This flag is supported on Windows 7 with SP1, Windows Server 2008 R2
with SP1, and later. On older systems, if `WSASocket` fails with
`WSAEINVAL` when using the flag, we can fallback to
`SetHandleInformation`.

Wrap `WSASocket` in new `win32_socket` to share the common inheritance
code.

[KB2398202]: https://support.microsoft.com/en-us/topic/an-application-may-stop-responding-when-the-application-closes-a-socket-connection-or-shuts-down-41321a1f-d80c-6975-98df-ae499d63133c
@MisterDA

Copy link
Copy Markdown
Contributor Author

Thanks for the new review.

I would suggest to declare win32_socket in unixsupport.h rather than in dup.c and in socketpair.c, it's less error-prone this way.

Done!

MisterDA added a commit to MisterDA/lwt that referenced this pull request Mar 28, 2022
On Windows, in order to mark sockets non-inheritable (close-on-exec),
it is sometimes not sufficient to use SetHandleInformation. There's
some explanation why in [1] and [KB2398202].

Introduced in the hotfix [KB2398202] and supported on Windows 7 with
SP1, Windows Server 2008 R2 with SP1, and later, the flag
WSA_FLAG_NO_HANDLE_INHERIT can be used with WSASocket to create a
non-inheritable socket.

We can still call SetHandleInformation to clear the inheritable flag
on the socket in case the flag isn't supported (running on an early
Windows Vista or 7).

Related OCaml PR:
- ocaml/ocaml#10809.

[1]: https://stackoverflow.com/questions/12058911/can-tcp-socket-handles-be-set-not-inheritable
[KB2398202]: https://support.microsoft.com/en-us/topic/an-application-may-stop-responding-when-the-application-closes-a-socket-connection-or-shuts-down-41321a1f-d80c-6975-98df-ae499d63133c

@nojb nojb left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

if (! inherit && WSAGetLastError() == WSAEINVAL) {
/* WSASocket probably doesn't suport WSA_FLAG_NO_HANDLE_INHERIT,
* retry without. */
flags &= ~(DWORD)WSA_FLAG_NO_HANDLE_INHERIT;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there an issue with the simpler

Suggested change
flags &= ~(DWORD)WSA_FLAG_NO_HANDLE_INHERIT;
flags &= ~WSA_FLAG_NO_HANDLE_INHERIT;

?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, it should work. DWORD flags is 4 bytes long, the constant is an int, so that shouldn't be a problem. I've taken up the habit of casting constants to the type of the result when fiddling with bits to avoid integer promotion, signedness, and size issues.

BOOL inherit)
{
SOCKET s;
DWORD flags = WSA_FLAG_OVERLAPPED;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do I understand well that socket is roughly equivalent to WSASocket + WSA_FLAG_OVERLAPPED?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. The socket() doc reads:

The socket that is created will have the overlapped attribute as a default.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants