Debian Codegraph @

test/core/util/fake_udp_and_tcp_server.cc

raw
1 //
2 // Copyright 2018 gRPC authors.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16
17 #include <grpc/support/port_platform.h>
18
19 #include "test/core/util/fake_udp_and_tcp_server.h"
20
21 #include <errno.h>
22 #include <string.h>
23
24 #include <set>
25 #include <utility>
26 #include <vector>
27
28 #include "absl/status/statusor.h"
29 #include "absl/strings/str_cat.h"
30
31 #include <grpc/grpc.h>
32 #include <grpc/support/log.h>
33 #include <grpc/support/time.h>
34
35 #include "src/core/lib/address_utils/sockaddr_utils.h"
36 #include "src/core/lib/iomgr/resolved_address.h"
37 #include "src/core/lib/iomgr/sockaddr.h"
38 #include "test/core/util/port.h"
39
40 // IWYU pragma: no_include <arpa/inet.h>
41
42 #ifdef GPR_WINDOWS
43 #include "src/core/lib/iomgr/sockaddr_windows.h"
44 #include "src/core/lib/iomgr/socket_windows.h"
45 #include "src/core/lib/iomgr/tcp_windows.h"
46
47 #define BAD_SOCKET_RETURN_VAL INVALID_SOCKET
48 #define CLOSE_SOCKET closesocket
49 #define ERRNO WSAGetLastError()
50 #else
51 #include <fcntl.h>
52 #include <unistd.h>
53
54 #define BAD_SOCKET_RETURN_VAL (-1)
55 #define CLOSE_SOCKET close
56 #define ERRNO errno
57 #endif
58
59 namespace grpc_core {
60 namespace testing {
61
62 namespace {
63
64 bool ErrorIsRetryable(int error) {
65 #ifdef GPR_WINDOWS
66 return error == WSAEWOULDBLOCK || error == WSAEINPROGRESS;
67 #else
68 return error == EWOULDBLOCK || error == EAGAIN;
69 #endif
70 }
71
72 } // namespace
73
74 FakeUdpAndTcpServer::FakeUdpAndTcpServer(
75 AcceptMode accept_mode,
76 std::function<FakeUdpAndTcpServer::ProcessReadResult(int, int, int)>
77 process_read_cb)
78 : accept_mode_(accept_mode), process_read_cb_(std::move(process_read_cb)) {
79 port_ = grpc_pick_unused_port_or_die();
80 udp_socket_ = socket(AF_INET6, SOCK_DGRAM, 0);
81 if (udp_socket_ == BAD_SOCKET_RETURN_VAL) {
82 gpr_log(GPR_ERROR, "Failed to create UDP ipv6 socket: %d", ERRNO);
83 GPR_ASSERT(0);
84 }
85 accept_socket_ = socket(AF_INET6, SOCK_STREAM, 0);
86 address_ = absl::StrCat("[::1]:", port_);
87 if (accept_socket_ == BAD_SOCKET_RETURN_VAL) {
88 gpr_log(GPR_ERROR, "Failed to create TCP IPv6 socket: %d", ERRNO);
89 GPR_ASSERT(0);
90 }
91 #ifdef GPR_WINDOWS
92 char val = 1;
93 if (setsockopt(accept_socket_, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) ==
94 SOCKET_ERROR) {
95 gpr_log(GPR_ERROR,
96 "Failed to set SO_REUSEADDR on TCP ipv6 socket to [::1]:%d, "
97 "errno: %d",
98 port_, ERRNO);
99 GPR_ASSERT(0);
100 }
101 grpc_error_handle set_non_block_error;
102 set_non_block_error = grpc_tcp_set_non_block(udp_socket_);
103 if (!set_non_block_error.ok()) {
104 gpr_log(GPR_ERROR, "Failed to configure non-blocking socket: %s",
105 StatusToString(set_non_block_error).c_str());
106 GPR_ASSERT(0);
107 }
108 set_non_block_error = grpc_tcp_set_non_block(accept_socket_);
109 if (!set_non_block_error.ok()) {
110 gpr_log(GPR_ERROR, "Failed to configure non-blocking socket: %s",
111 StatusToString(set_non_block_error).c_str());
112 GPR_ASSERT(0);
113 }
114 #else
115 int val = 1;
116 if (setsockopt(accept_socket_, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) !=
117 0) {
118 gpr_log(GPR_ERROR, "Failed to set SO_REUSEADDR on socket [::1]:%d", port_);
119 GPR_ASSERT(0);
120 }
121 if (fcntl(udp_socket_, F_SETFL, O_NONBLOCK) != 0) {
122 gpr_log(GPR_ERROR, "Failed to set O_NONBLOCK on socket: %d", ERRNO);
123 GPR_ASSERT(0);
124 }
125 if (fcntl(accept_socket_, F_SETFL, O_NONBLOCK) != 0) {
126 gpr_log(GPR_ERROR, "Failed to set O_NONBLOCK on socket: %d", ERRNO);
127 GPR_ASSERT(0);
128 }
129 #endif
130 sockaddr_in6 addr;
131 memset(&addr, 0, sizeof(addr));
132 addr.sin6_family = AF_INET6;
133 addr.sin6_port = htons(port_);
134 (reinterpret_cast<char*>(&addr.sin6_addr))[15] = 1;
135 grpc_resolved_address resolved_addr;
136 memcpy(resolved_addr.addr, &addr, sizeof(addr));
137 resolved_addr.len = sizeof(addr);
138 std::string addr_str = grpc_sockaddr_to_string(&resolved_addr, false).value();
139 gpr_log(GPR_INFO, "Fake UDP and TCP server listening on %s",
140 addr_str.c_str());
141 if (bind(udp_socket_, reinterpret_cast<const sockaddr*>(&addr),
142 sizeof(addr)) != 0) {
143 gpr_log(GPR_ERROR, "Failed to bind UDP socket to [::1]:%d", port_);
144 GPR_ASSERT(0);
145 }
146 if (bind(accept_socket_, reinterpret_cast<const sockaddr*>(&addr),
147 sizeof(addr)) != 0) {
148 gpr_log(GPR_ERROR, "Failed to bind TCP socket to [::1]:%d : %d", port_,
149 ERRNO);
150 GPR_ASSERT(0);
151 }
152 if (listen(accept_socket_, 100)) {
153 gpr_log(GPR_ERROR, "Failed to listen on socket bound to [::1]:%d : %d",
154 port_, ERRNO);
155 GPR_ASSERT(0);
156 }
157 gpr_event_init(&stop_ev_);
158 run_server_loop_thd_ = std::make_unique<std::thread>(
159 std::bind(&FakeUdpAndTcpServer::RunServerLoop, this));
160 }
161
162 FakeUdpAndTcpServer::~FakeUdpAndTcpServer() {
163 gpr_log(GPR_DEBUG,
164 "FakeUdpAndTcpServer stop and "
165 "join server thread");
166 gpr_event_set(&stop_ev_, reinterpret_cast<void*>(1));
167 run_server_loop_thd_->join();
168 gpr_log(GPR_DEBUG,
169 "FakeUdpAndTcpServer join server "
170 "thread complete");
171 CLOSE_SOCKET(accept_socket_);
172 CLOSE_SOCKET(udp_socket_);
173 }
174
175 FakeUdpAndTcpServer::ProcessReadResult
176 FakeUdpAndTcpServer::CloseSocketUponReceivingBytesFromPeer(
177 int bytes_received_size, int read_error, int s) {
178 if (bytes_received_size < 0 && !ErrorIsRetryable(read_error)) {
179 gpr_log(GPR_ERROR, "Failed to receive from peer socket: %d. errno: %d", s,
180 read_error);
181 GPR_ASSERT(0);
182 }
183 if (bytes_received_size >= 0) {
184 gpr_log(GPR_DEBUG,
185 "Fake TCP server received %d bytes from peer socket: %d. Close "
186 "the "
187 "connection.",
188 bytes_received_size, s);
189 return FakeUdpAndTcpServer::ProcessReadResult::kCloseSocket;
190 }
191 return FakeUdpAndTcpServer::ProcessReadResult::kContinueReading;
192 }
193
194 FakeUdpAndTcpServer::ProcessReadResult
195 FakeUdpAndTcpServer::CloseSocketUponCloseFromPeer(int bytes_received_size,
196 int read_error, int s) {
197 if (bytes_received_size < 0 && !ErrorIsRetryable(read_error)) {
198 gpr_log(GPR_ERROR, "Failed to receive from peer socket: %d. errno: %d", s,
199 read_error);
200 GPR_ASSERT(0);
201 }
202 if (bytes_received_size == 0) {
203 // The peer has shut down the connection.
204 gpr_log(GPR_DEBUG,
205 "Fake TCP server received 0 bytes from peer socket: %d. Close "
206 "the "
207 "connection.",
208 s);
209 return FakeUdpAndTcpServer::ProcessReadResult::kCloseSocket;
210 }
211 return FakeUdpAndTcpServer::ProcessReadResult::kContinueReading;
212 }
213
214 FakeUdpAndTcpServer::FakeUdpAndTcpServerPeer::FakeUdpAndTcpServerPeer(int fd)
215 : fd_(fd) {}
216
217 FakeUdpAndTcpServer::FakeUdpAndTcpServerPeer::~FakeUdpAndTcpServerPeer() {
218 CLOSE_SOCKET(fd_);
219 }
220
221 void FakeUdpAndTcpServer::FakeUdpAndTcpServerPeer::
222 MaybeContinueSendingSettings() {
223 // https://tools.ietf.org/html/rfc7540#section-4.1
224 const std::vector<char> kEmptyHttp2SettingsFrame = {
225 0x00, 0x00, 0x00, // length
226 0x04, // settings type
227 0x00, // flags
228 0x00, 0x00, 0x00, 0x00 // stream identifier
229 };
230 if (total_bytes_sent_ < int(kEmptyHttp2SettingsFrame.size())) {
231 int bytes_to_send = kEmptyHttp2SettingsFrame.size() - total_bytes_sent_;
232 int bytes_sent =
233 send(fd_, kEmptyHttp2SettingsFrame.data() + total_bytes_sent_,
234 bytes_to_send, 0);
235 if (bytes_sent < 0 && !ErrorIsRetryable(ERRNO)) {
236 gpr_log(GPR_ERROR,
237 "Fake TCP server encountered unexpected error:%d "
238 "sending %d bytes on fd:%d",
239 ERRNO, bytes_to_send, fd_);
240 GPR_ASSERT(0);
241 } else if (bytes_sent > 0) {
242 total_bytes_sent_ += bytes_sent;
243 GPR_ASSERT(total_bytes_sent_ <= int(kEmptyHttp2SettingsFrame.size()));
244 }
245 }
246 }
247
248 void FakeUdpAndTcpServer::ReadFromUdpSocket() {
249 char buf[100];
250 recvfrom(udp_socket_, buf, sizeof(buf), 0, nullptr, nullptr);
251 }
252
253 void FakeUdpAndTcpServer::RunServerLoop() {
254 std::set<std::unique_ptr<FakeUdpAndTcpServerPeer>> peers;
255 while (!gpr_event_get(&stop_ev_)) {
256 // handle TCP connections
257 int p = accept(accept_socket_, nullptr, nullptr);
258 if (p != BAD_SOCKET_RETURN_VAL) {
259 gpr_log(GPR_DEBUG, "accepted peer socket: %d", p);
260 #ifdef GPR_WINDOWS
261 grpc_error_handle set_non_block_error;
262 set_non_block_error = grpc_tcp_set_non_block(p);
263 if (!set_non_block_error.ok()) {
264 gpr_log(GPR_ERROR, "Failed to configure non-blocking socket: %s",
265 StatusToString(set_non_block_error).c_str());
266 GPR_ASSERT(0);
267 }
268 #else
269 if (fcntl(p, F_SETFL, O_NONBLOCK) != 0) {
270 gpr_log(GPR_ERROR, "Failed to configure non-blocking socket, errno: %d",
271 ERRNO);
272 GPR_ASSERT(0);
273 }
274 #endif
275 peers.insert(std::make_unique<FakeUdpAndTcpServerPeer>(p));
276 }
277 auto it = peers.begin();
278 while (it != peers.end()) {
279 FakeUdpAndTcpServerPeer* peer = (*it).get();
280 if (accept_mode_ == AcceptMode::kEagerlySendSettings) {
281 peer->MaybeContinueSendingSettings();
282 }
283 char buf[100];
284 int bytes_received_size = recv(peer->fd(), buf, 100, 0);
285 FakeUdpAndTcpServer::ProcessReadResult r =
286 process_read_cb_(bytes_received_size, ERRNO, peer->fd());
287 if (r == FakeUdpAndTcpServer::ProcessReadResult::kCloseSocket) {
288 it = peers.erase(it);
289 } else {
290 GPR_ASSERT(r ==
291 FakeUdpAndTcpServer::ProcessReadResult::kContinueReading);
292 it++;
293 }
294 }
295 // read from the UDP socket
296 ReadFromUdpSocket();
297 gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
298 gpr_time_from_millis(10, GPR_TIMESPAN)));
299 }
300 }
301
302 } // namespace testing
303 } // namespace grpc_core