Debian Codegraph @

src/core/lib/iomgr/tcp_server_windows.cc

raw
1 /*
2 *
3 * Copyright 2015 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 #include <grpc/support/port_platform.h>
20
21 #include "src/core/lib/iomgr/port.h"
22
23 #ifdef GRPC_WINSOCK_SOCKET
24
25 #include <inttypes.h>
26 #include <io.h>
27
28 #include <vector>
29
30 #include "absl/strings/str_cat.h"
31
32 #include <grpc/event_engine/endpoint_config.h>
33 #include <grpc/support/alloc.h>
34 #include <grpc/support/log.h>
35 #include <grpc/support/log_windows.h>
36 #include <grpc/support/string_util.h>
37 #include <grpc/support/sync.h>
38 #include <grpc/support/time.h>
39
40 #include "src/core/lib/address_utils/sockaddr_utils.h"
41 #include "src/core/lib/iomgr/iocp_windows.h"
42 #include "src/core/lib/iomgr/pollset_windows.h"
43 #include "src/core/lib/iomgr/resolve_address.h"
44 #include "src/core/lib/iomgr/sockaddr.h"
45 #include "src/core/lib/iomgr/socket_windows.h"
46 #include "src/core/lib/iomgr/tcp_server.h"
47 #include "src/core/lib/iomgr/tcp_windows.h"
48 #include "src/core/lib/resource_quota/api.h"
49 #include "src/core/lib/slice/slice_internal.h"
50
51 #define MIN_SAFE_ACCEPT_QUEUE_SIZE 100
52
53 using ::grpc_event_engine::experimental::EndpointConfig;
54
55 /* one listening port */
56 typedef struct grpc_tcp_listener grpc_tcp_listener;
57 struct grpc_tcp_listener {
58 /* This seemingly magic number comes from AcceptEx's documentation. each
59 address buffer needs to have at least 16 more bytes at their end. */
60 uint8_t addresses[(sizeof(grpc_sockaddr_in6) + 16) * 2];
61 /* This will hold the socket for the next accept. */
62 SOCKET new_socket;
63 /* The listener winsocket. */
64 grpc_winsocket* socket;
65 /* The actual TCP port number. */
66 int port;
67 unsigned port_index;
68 grpc_tcp_server* server;
69 /* The cached AcceptEx for that port. */
70 LPFN_ACCEPTEX AcceptEx;
71 int shutting_down;
72 int outstanding_calls;
73 /* closure for socket notification of accept being ready */
74 grpc_closure on_accept;
75 /* linked list */
76 struct grpc_tcp_listener* next;
77 };
78
79 /* the overall server */
80 struct grpc_tcp_server {
81 gpr_refcount refs;
82 /* Called whenever accept() succeeds on a server port. */
83 grpc_tcp_server_cb on_accept_cb;
84 void* on_accept_cb_arg;
85
86 gpr_mu mu;
87
88 /* active port count: how many ports are actually still listening */
89 int active_ports;
90
91 /* linked list of server ports */
92 grpc_tcp_listener* head;
93 grpc_tcp_listener* tail;
94
95 /* List of closures passed to shutdown_starting_add(). */
96 grpc_closure_list shutdown_starting;
97
98 /* shutdown callback */
99 grpc_closure* shutdown_complete;
100 };
101
102 /* Public function. Allocates the proper data structures to hold a
103 grpc_tcp_server. */
104 static grpc_error_handle tcp_server_create(grpc_closure* shutdown_complete,
105 const EndpointConfig& config,
106 grpc_tcp_server** server) {
107 grpc_tcp_server* s = (grpc_tcp_server*)gpr_malloc(sizeof(grpc_tcp_server));
108 gpr_ref_init(&s->refs, 1);
109 gpr_mu_init(&s->mu);
110 s->active_ports = 0;
111 s->on_accept_cb = NULL;
112 s->on_accept_cb_arg = NULL;
113 s->head = NULL;
114 s->tail = NULL;
115 s->shutdown_starting.head = NULL;
116 s->shutdown_starting.tail = NULL;
117 s->shutdown_complete = shutdown_complete;
118 *server = s;
119 return absl::OkStatus();
120 }
121
122 static void destroy_server(void* arg, grpc_error_handle error) {
123 grpc_tcp_server* s = (grpc_tcp_server*)arg;
124
125 /* Now that the accepts have been aborted, we can destroy the sockets.
126 The IOCP won't get notified on these, so we can flag them as already
127 closed by the system. */
128 while (s->head) {
129 grpc_tcp_listener* sp = s->head;
130 s->head = sp->next;
131 sp->next = NULL;
132 grpc_winsocket_destroy(sp->socket);
133 gpr_free(sp);
134 }
135 gpr_mu_destroy(&s->mu);
136 gpr_free(s);
137 }
138
139 static void finish_shutdown_locked(grpc_tcp_server* s) {
140 if (s->shutdown_complete != NULL) {
141 grpc_core::ExecCtx::Run(DEBUG_LOCATION, s->shutdown_complete,
142 absl::OkStatus());
143 }
144
145 grpc_core::ExecCtx::Run(
146 DEBUG_LOCATION,
147 GRPC_CLOSURE_CREATE(destroy_server, s, grpc_schedule_on_exec_ctx),
148 absl::OkStatus());
149 }
150
151 static grpc_tcp_server* tcp_server_ref(grpc_tcp_server* s) {
152 gpr_ref_non_zero(&s->refs);
153 return s;
154 }
155
156 static void tcp_server_shutdown_starting_add(grpc_tcp_server* s,
157 grpc_closure* shutdown_starting) {
158 gpr_mu_lock(&s->mu);
159 grpc_closure_list_append(&s->shutdown_starting, shutdown_starting,
160 absl::OkStatus());
161 gpr_mu_unlock(&s->mu);
162 }
163
164 static void tcp_server_destroy(grpc_tcp_server* s) {
165 grpc_tcp_listener* sp;
166 gpr_mu_lock(&s->mu);
167 /* First, shutdown all fd's. This will queue abortion calls for all
168 of the pending accepts due to the normal operation mechanism. */
169 if (s->active_ports == 0) {
170 finish_shutdown_locked(s);
171 } else {
172 for (sp = s->head; sp; sp = sp->next) {
173 sp->shutting_down = 1;
174 grpc_winsocket_shutdown(sp->socket);
175 }
176 }
177 gpr_mu_unlock(&s->mu);
178 }
179
180 static void tcp_server_unref(grpc_tcp_server* s) {
181 if (gpr_unref(&s->refs)) {
182 grpc_tcp_server_shutdown_listeners(s);
183 gpr_mu_lock(&s->mu);
184 grpc_core::ExecCtx::RunList(DEBUG_LOCATION, &s->shutdown_starting);
185 gpr_mu_unlock(&s->mu);
186 tcp_server_destroy(s);
187 }
188 }
189
190 /* Prepare (bind) a recently-created socket for listening. */
191 static grpc_error_handle prepare_socket(SOCKET sock,
192 const grpc_resolved_address* addr,
193 int* port) {
194 grpc_resolved_address sockname_temp;
195 grpc_error_handle error;
196 int sockname_temp_len;
197
198 error = grpc_tcp_prepare_socket(sock);
199 if (!error.ok()) {
200 goto failure;
201 }
202
203 if (bind(sock, (const grpc_sockaddr*)addr->addr, (int)addr->len) ==
204 SOCKET_ERROR) {
205 error = GRPC_WSA_ERROR(WSAGetLastError(), "bind");
206 goto failure;
207 }
208
209 if (listen(sock, SOMAXCONN) == SOCKET_ERROR) {
210 error = GRPC_WSA_ERROR(WSAGetLastError(), "listen");
211 goto failure;
212 }
213
214 sockname_temp_len = sizeof(struct sockaddr_storage);
215 if (getsockname(sock, (grpc_sockaddr*)sockname_temp.addr,
216 &sockname_temp_len) == SOCKET_ERROR) {
217 error = GRPC_WSA_ERROR(WSAGetLastError(), "getsockname");
218 goto failure;
219 }
220 sockname_temp.len = (size_t)sockname_temp_len;
221
222 *port = grpc_sockaddr_get_port(&sockname_temp);
223 return absl::OkStatus();
224
225 failure:
226 GPR_ASSERT(!error.ok());
227 auto addr_uri = grpc_sockaddr_to_uri(addr);
228 grpc_error_set_int(
229 grpc_error_set_str(
230 GRPC_ERROR_CREATE_REFERENCING("Failed to prepare server socket",
231 &error, 1),
232 grpc_core::StatusStrProperty::kTargetAddress,
233 addr_uri.ok() ? *addr_uri : addr_uri.status().ToString()),
234 grpc_core::StatusIntProperty::kFd, (intptr_t)sock);
235 if (sock != INVALID_SOCKET) closesocket(sock);
236 return error;
237 }
238
239 static void decrement_active_ports_and_notify_locked(grpc_tcp_listener* sp) {
240 sp->shutting_down = 0;
241 GPR_ASSERT(sp->server->active_ports > 0);
242 if (0 == --sp->server->active_ports) {
243 finish_shutdown_locked(sp->server);
244 }
245 }
246
247 /* In order to do an async accept, we need to create a socket first which
248 will be the one assigned to the new incoming connection. */
249 static grpc_error_handle start_accept_locked(grpc_tcp_listener* port) {
250 SOCKET sock = INVALID_SOCKET;
251 BOOL success;
252 DWORD addrlen = sizeof(grpc_sockaddr_in6) + 16;
253 DWORD bytes_received = 0;
254 grpc_error_handle error;
255
256 if (port->shutting_down) {
257 return absl::OkStatus();
258 }
259
260 sock = WSASocket(AF_INET6, SOCK_STREAM, IPPROTO_TCP, NULL, 0,
261 grpc_get_default_wsa_socket_flags());
262 if (sock == INVALID_SOCKET) {
263 error = GRPC_WSA_ERROR(WSAGetLastError(), "WSASocket");
264 goto failure;
265 }
266
267 error = grpc_tcp_prepare_socket(sock);
268 if (!error.ok()) goto failure;
269
270 /* Start the "accept" asynchronously. */
271 success = port->AcceptEx(port->socket->socket, sock, port->addresses, 0,
272 addrlen, addrlen, &bytes_received,
273 &port->socket->read_info.overlapped);
274
275 /* It is possible to get an accept immediately without delay. However, we
276 will still get an IOCP notification for it. So let's just ignore it. */
277 if (!success) {
278 int last_error = WSAGetLastError();
279 if (last_error != ERROR_IO_PENDING) {
280 error = GRPC_WSA_ERROR(last_error, "AcceptEx");
281 goto failure;
282 }
283 }
284
285 /* We're ready to do the accept. Calling grpc_socket_notify_on_read may
286 immediately process an accept that happened in the meantime. */
287 port->new_socket = sock;
288 grpc_socket_notify_on_read(port->socket, &port->on_accept);
289 port->outstanding_calls++;
290 return error;
291
292 failure:
293 GPR_ASSERT(!error.ok());
294 if (sock != INVALID_SOCKET) closesocket(sock);
295 return error;
296 }
297
298 /* Event manager callback when reads are ready. */
299 static void on_accept(void* arg, grpc_error_handle error) {
300 grpc_tcp_listener* sp = (grpc_tcp_listener*)arg;
301 SOCKET sock = sp->new_socket;
302 grpc_winsocket_callback_info* info = &sp->socket->read_info;
303 grpc_endpoint* ep = NULL;
304 grpc_resolved_address peer_name;
305 DWORD transfered_bytes;
306 DWORD flags;
307 BOOL wsa_success;
308 int err;
309
310 gpr_mu_lock(&sp->server->mu);
311
312 peer_name.len = sizeof(struct sockaddr_storage);
313
314 /* The general mechanism for shutting down is to queue abortion calls. While
315 this is necessary in the read/write case, it's useless for the accept
316 case. We only need to adjust the pending callback count */
317 if (!error.ok()) {
318 gpr_log(GPR_INFO, "Skipping on_accept due to error: %s",
319 grpc_core::StatusToString(error).c_str());
320
321 gpr_mu_unlock(&sp->server->mu);
322 return;
323 }
324 /* The IOCP notified us of a completed operation. Let's grab the results,
325 and act accordingly. */
326 transfered_bytes = 0;
327 wsa_success = WSAGetOverlappedResult(sock, &info->overlapped,
328 &transfered_bytes, FALSE, &flags);
329 if (!wsa_success) {
330 if (!sp->shutting_down) {
331 char* utf8_message = gpr_format_message(WSAGetLastError());
332 gpr_log(GPR_ERROR, "on_accept error: %s", utf8_message);
333 gpr_free(utf8_message);
334 }
335 closesocket(sock);
336 } else {
337 if (!sp->shutting_down) {
338 err = setsockopt(sock, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT,
339 (char*)&sp->socket->socket, sizeof(sp->socket->socket));
340 if (err) {
341 char* utf8_message = gpr_format_message(WSAGetLastError());
342 gpr_log(GPR_ERROR, "setsockopt error: %s", utf8_message);
343 gpr_free(utf8_message);
344 }
345 int peer_name_len = (int)peer_name.len;
346 err = getpeername(sock, (grpc_sockaddr*)peer_name.addr, &peer_name_len);
347 peer_name.len = (size_t)peer_name_len;
348 std::string peer_name_string;
349 if (!err) {
350 auto addr_uri = grpc_sockaddr_to_uri(&peer_name);
351 if (addr_uri.ok()) {
352 peer_name_string = addr_uri.value();
353 } else {
354 gpr_log(GPR_ERROR, "invalid peer name: %s",
355 addr_uri.status().ToString().c_str());
356 }
357 } else {
358 char* utf8_message = gpr_format_message(WSAGetLastError());
359 gpr_log(GPR_ERROR, "getpeername error: %s", utf8_message);
360 gpr_free(utf8_message);
361 }
362 std::string fd_name = absl::StrCat("tcp_server:", peer_name_string);
363 ep = grpc_tcp_create(grpc_winsocket_create(sock, fd_name.c_str()),
364 peer_name_string);
365 } else {
366 closesocket(sock);
367 }
368 }
369
370 /* The only time we should call our callback, is where we successfully
371 managed to accept a connection, and created an endpoint. */
372 if (ep) {
373 // Create acceptor.
374 grpc_tcp_server_acceptor* acceptor =
375 (grpc_tcp_server_acceptor*)gpr_malloc(sizeof(*acceptor));
376 acceptor->from_server = sp->server;
377 acceptor->port_index = sp->port_index;
378 acceptor->fd_index = 0;
379 acceptor->external_connection = false;
380 sp->server->on_accept_cb(sp->server->on_accept_cb_arg, ep, NULL, acceptor);
381 }
382 /* As we were notified from the IOCP of one and exactly one accept,
383 the former socked we created has now either been destroy or assigned
384 to the new connection. We need to create a new one for the next
385 connection. */
386 GPR_ASSERT(GRPC_LOG_IF_ERROR("start_accept", start_accept_locked(sp)));
387 if (0 == --sp->outstanding_calls) {
388 decrement_active_ports_and_notify_locked(sp);
389 }
390 gpr_mu_unlock(&sp->server->mu);
391 }
392
393 static grpc_error_handle add_socket_to_server(grpc_tcp_server* s, SOCKET sock,
394 const grpc_resolved_address* addr,
395 unsigned port_index,
396 grpc_tcp_listener** listener) {
397 grpc_tcp_listener* sp = NULL;
398 int port = -1;
399 int status;
400 GUID guid = WSAID_ACCEPTEX;
401 DWORD ioctl_num_bytes;
402 LPFN_ACCEPTEX AcceptEx;
403 grpc_error_handle error;
404
405 /* We need to grab the AcceptEx pointer for that port, as it may be
406 interface-dependent. We'll cache it to avoid doing that again. */
407 status =
408 WSAIoctl(sock, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid, sizeof(guid),
409 &AcceptEx, sizeof(AcceptEx), &ioctl_num_bytes, NULL, NULL);
410
411 if (status != 0) {
412 char* utf8_message = gpr_format_message(WSAGetLastError());
413 gpr_log(GPR_ERROR, "on_connect error: %s", utf8_message);
414 gpr_free(utf8_message);
415 closesocket(sock);
416 return absl::OkStatus();
417 }
418
419 error = prepare_socket(sock, addr, &port);
420 if (!error.ok()) {
421 return error;
422 }
423
424 GPR_ASSERT(port >= 0);
425 gpr_mu_lock(&s->mu);
426 GPR_ASSERT(!s->on_accept_cb && "must add ports before starting server");
427 sp = (grpc_tcp_listener*)gpr_malloc(sizeof(grpc_tcp_listener));
428 sp->next = NULL;
429 if (s->head == NULL) {
430 s->head = sp;
431 } else {
432 s->tail->next = sp;
433 }
434 s->tail = sp;
435 sp->server = s;
436 sp->socket = grpc_winsocket_create(sock, "listener");
437 sp->shutting_down = 0;
438 sp->outstanding_calls = 0;
439 sp->AcceptEx = AcceptEx;
440 sp->new_socket = INVALID_SOCKET;
441 sp->port = port;
442 sp->port_index = port_index;
443 GRPC_CLOSURE_INIT(&sp->on_accept, on_accept, sp, grpc_schedule_on_exec_ctx);
444 GPR_ASSERT(sp->socket);
445 gpr_mu_unlock(&s->mu);
446 *listener = sp;
447
448 return absl::OkStatus();
449 }
450
451 static grpc_error_handle tcp_server_add_port(grpc_tcp_server* s,
452 const grpc_resolved_address* addr,
453 int* port) {
454 grpc_tcp_listener* sp = NULL;
455 SOCKET sock;
456 grpc_resolved_address addr6_v4mapped;
457 grpc_resolved_address wildcard;
458 grpc_resolved_address* allocated_addr = NULL;
459 grpc_resolved_address sockname_temp;
460 unsigned port_index = 0;
461 grpc_error_handle error;
462
463 if (s->tail != NULL) {
464 port_index = s->tail->port_index + 1;
465 }
466
467 /* Check if this is a wildcard port, and if so, try to keep the port the same
468 as some previously created listener. */
469 if (grpc_sockaddr_get_port(addr) == 0) {
470 for (sp = s->head; sp; sp = sp->next) {
471 int sockname_temp_len = sizeof(struct sockaddr_storage);
472 if (0 == getsockname(sp->socket->socket,
473 (grpc_sockaddr*)sockname_temp.addr,
474 &sockname_temp_len)) {
475 sockname_temp.len = (size_t)sockname_temp_len;
476 *port = grpc_sockaddr_get_port(&sockname_temp);
477 if (*port > 0) {
478 allocated_addr =
479 (grpc_resolved_address*)gpr_malloc(sizeof(grpc_resolved_address));
480 memcpy(allocated_addr, addr, sizeof(grpc_resolved_address));
481 grpc_sockaddr_set_port(allocated_addr, *port);
482 addr = allocated_addr;
483 break;
484 }
485 }
486 }
487 }
488
489 if (grpc_sockaddr_to_v4mapped(addr, &addr6_v4mapped)) {
490 addr = &addr6_v4mapped;
491 }
492
493 /* Treat :: or 0.0.0.0 as a family-agnostic wildcard. */
494 if (grpc_sockaddr_is_wildcard(addr, port)) {
495 grpc_sockaddr_make_wildcard6(*port, &wildcard);
496
497 addr = &wildcard;
498 }
499
500 sock = WSASocket(AF_INET6, SOCK_STREAM, IPPROTO_TCP, NULL, 0,
501 grpc_get_default_wsa_socket_flags());
502 if (sock == INVALID_SOCKET) {
503 error = GRPC_WSA_ERROR(WSAGetLastError(), "WSASocket");
504 goto done;
505 }
506
507 error = add_socket_to_server(s, sock, addr, port_index, &sp);
508
509 done:
510 gpr_free(allocated_addr);
511
512 if (!error.ok()) {
513 grpc_error_handle error_out = GRPC_ERROR_CREATE_REFERENCING(
514 "Failed to add port to server", &error, 1);
515 error = error_out;
516 *port = -1;
517 } else {
518 GPR_ASSERT(sp != NULL);
519 *port = sp->port;
520 }
521 return error;
522 }
523
524 static void tcp_server_start(grpc_tcp_server* s,
525 const std::vector<grpc_pollset*>* /*pollsets*/,
526 grpc_tcp_server_cb on_accept_cb,
527 void* on_accept_cb_arg) {
528 grpc_tcp_listener* sp;
529 GPR_ASSERT(on_accept_cb);
530 gpr_mu_lock(&s->mu);
531 GPR_ASSERT(!s->on_accept_cb);
532 GPR_ASSERT(s->active_ports == 0);
533 s->on_accept_cb = on_accept_cb;
534 s->on_accept_cb_arg = on_accept_cb_arg;
535 for (sp = s->head; sp; sp = sp->next) {
536 GPR_ASSERT(GRPC_LOG_IF_ERROR("start_accept", start_accept_locked(sp)));
537 s->active_ports++;
538 }
539 gpr_mu_unlock(&s->mu);
540 }
541
542 static unsigned tcp_server_port_fd_count(grpc_tcp_server* s,
543 unsigned port_index) {
544 return 0;
545 }
546
547 static int tcp_server_port_fd(grpc_tcp_server* s, unsigned port_index,
548 unsigned fd_index) {
549 return -1;
550 }
551
552 static grpc_core::TcpServerFdHandler* tcp_server_create_fd_handler(
553 grpc_tcp_server* s) {
554 return nullptr;
555 }
556
557 static void tcp_server_shutdown_listeners(grpc_tcp_server* s) {}
558
559 grpc_tcp_server_vtable grpc_windows_tcp_server_vtable = {
560 tcp_server_create, tcp_server_start,
561 tcp_server_add_port, tcp_server_create_fd_handler,
562 tcp_server_port_fd_count, tcp_server_port_fd,
563 tcp_server_ref, tcp_server_shutdown_starting_add,
564 tcp_server_unref, tcp_server_shutdown_listeners};
565 #endif /* GRPC_WINSOCK_SOCKET */