Debian Codegraph @

test/core/event_engine/windows/create_sockpair.cc

raw
1 // Copyright 2022 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 #include <grpc/support/port_platform.h>
15 #ifdef GPR_WINDOWS
16
17 #include <winsock2.h>
18 #include <ws2tcpip.h>
19
20 #include "absl/status/status.h"
21
22 #include "src/core/lib/event_engine/windows/win_socket.h"
23 #include "src/core/lib/iomgr/error.h"
24 #include "test/core/event_engine/windows/create_sockpair.h"
25
26 namespace grpc_event_engine {
27 namespace experimental {
28
29 void CreateSockpair(SOCKET sockpair[2], DWORD flags) {
30 SOCKET svr_sock = INVALID_SOCKET;
31 SOCKET lst_sock = INVALID_SOCKET;
32 SOCKET cli_sock = INVALID_SOCKET;
33 SOCKADDR_IN addr;
34 int addr_len = sizeof(addr);
35
36 lst_sock = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, flags);
37 GPR_ASSERT(lst_sock != INVALID_SOCKET);
38
39 memset(&addr, 0, sizeof(addr));
40 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
41 addr.sin_family = AF_INET;
42 GPR_ASSERT(bind(lst_sock, (sockaddr*)&addr, sizeof(addr)) != SOCKET_ERROR);
43 GPR_ASSERT(listen(lst_sock, SOMAXCONN) != SOCKET_ERROR);
44 GPR_ASSERT(getsockname(lst_sock, (sockaddr*)&addr, &addr_len) !=
45 SOCKET_ERROR);
46
47 cli_sock = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, flags);
48 GPR_ASSERT(cli_sock != INVALID_SOCKET);
49
50 GPR_ASSERT(WSAConnect(cli_sock, (sockaddr*)&addr, addr_len, NULL, NULL, NULL,
51 NULL) == 0);
52 svr_sock = accept(lst_sock, (sockaddr*)&addr, &addr_len);
53 GPR_ASSERT(svr_sock != INVALID_SOCKET);
54
55 closesocket(lst_sock);
56 // TODO(hork): see if we can migrate this to IPv6, or break up the socket prep
57 // stages.
58 // Historical note: This method creates an ipv4 sockpair, which cannot
59 // be made dual stack. This was silently preventing TCP_NODELAY from being
60 // enabled, but not causing an unrecoverable error. So this is left as a
61 // logged status. WSAEINVAL is expected.
62 auto status = PrepareSocket(cli_sock);
63 // if (!status.ok()) {
64 // gpr_log(GPR_DEBUG, "Error preparing client socket: %s",
65 // status.ToString().c_str());
66 // }
67 status = PrepareSocket(svr_sock);
68 // if (!status.ok()) {
69 // gpr_log(GPR_DEBUG, "Error preparing server socket: %s",
70 // status.ToString().c_str());
71 // }
72
73 sockpair[0] = svr_sock;
74 sockpair[1] = cli_sock;
75 }
76
77 } // namespace experimental
78 } // namespace grpc_event_engine
79
80 #endif // GPR_WINDOWS