Debian Codegraph @

src/core/lib/iomgr/tcp_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 <limits.h>
26
27 #include <grpc/slice_buffer.h>
28 #include <grpc/support/alloc.h>
29 #include <grpc/support/log.h>
30 #include <grpc/support/log_windows.h>
31 #include <grpc/support/string_util.h>
32
33 #include "src/core/lib/address_utils/sockaddr_utils.h"
34 #include "src/core/lib/gpr/string.h"
35 #include "src/core/lib/gpr/useful.h"
36 #include "src/core/lib/iomgr/iocp_windows.h"
37 #include "src/core/lib/iomgr/sockaddr.h"
38 #include "src/core/lib/iomgr/sockaddr_windows.h"
39 #include "src/core/lib/iomgr/socket_windows.h"
40 #include "src/core/lib/iomgr/tcp_client.h"
41 #include "src/core/lib/iomgr/tcp_windows.h"
42 #include "src/core/lib/iomgr/timer.h"
43 #include "src/core/lib/slice/slice_internal.h"
44 #include "src/core/lib/slice/slice_string_helpers.h"
45
46 #if defined(__MSYS__) && defined(GPR_ARCH_64)
47 /* Nasty workaround for nasty bug when using the 64 bits msys compiler
48 in conjunction with Microsoft Windows headers. */
49 #define GRPC_FIONBIO _IOW('f', 126, uint32_t)
50 #else
51 #define GRPC_FIONBIO FIONBIO
52 #endif
53
54 extern grpc_core::TraceFlag grpc_tcp_trace;
55
56 grpc_error_handle grpc_tcp_set_non_block(SOCKET sock) {
57 int status;
58 uint32_t param = 1;
59 DWORD ret;
60 status = WSAIoctl(sock, GRPC_FIONBIO, &param, sizeof(param), NULL, 0, &ret,
61 NULL, NULL);
62 return status == 0
63 ? absl::OkStatus()
64 : GRPC_WSA_ERROR(WSAGetLastError(), "WSAIoctl(GRPC_FIONBIO)");
65 }
66
67 static grpc_error_handle set_dualstack(SOCKET sock) {
68 int status;
69 unsigned long param = 0;
70 status = setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&param,
71 sizeof(param));
72 return status == 0
73 ? absl::OkStatus()
74 : GRPC_WSA_ERROR(WSAGetLastError(), "setsockopt(IPV6_V6ONLY)");
75 }
76
77 static grpc_error_handle enable_socket_low_latency(SOCKET sock) {
78 int status;
79 BOOL param = TRUE;
80 status = ::setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
81 reinterpret_cast<char*>(&param), sizeof(param));
82 if (status == SOCKET_ERROR) {
83 status = WSAGetLastError();
84 }
85 return status == 0 ? absl::OkStatus()
86 : GRPC_WSA_ERROR(status, "setsockopt(TCP_NODELAY)");
87 }
88
89 grpc_error_handle grpc_tcp_prepare_socket(SOCKET sock) {
90 grpc_error_handle err;
91 err = grpc_tcp_set_non_block(sock);
92 if (!err.ok()) return err;
93 err = set_dualstack(sock);
94 if (!err.ok()) return err;
95 err = enable_socket_low_latency(sock);
96 if (!err.ok()) return err;
97 return absl::OkStatus();
98 }
99
100 typedef struct grpc_tcp {
101 /* This is our C++ class derivation emulation. */
102 grpc_endpoint base;
103 /* The one socket this endpoint is using. */
104 grpc_winsocket* socket;
105 /* Refcounting how many operations are in progress. */
106 gpr_refcount refcount;
107
108 grpc_closure on_read;
109 grpc_closure on_write;
110
111 grpc_closure* read_cb;
112 grpc_closure* write_cb;
113
114 /* garbage after the last read */
115 grpc_slice_buffer last_read_buffer;
116
117 grpc_slice_buffer* write_slices;
118 grpc_slice_buffer* read_slices;
119
120 /* The IO Completion Port runs from another thread. We need some mechanism
121 to protect ourselves when requesting a shutdown. */
122 gpr_mu mu;
123 int shutting_down;
124 grpc_error_handle shutdown_error;
125
126 std::string peer_string;
127 std::string local_address;
128 } grpc_tcp;
129
130 static void tcp_free(grpc_tcp* tcp) {
131 grpc_winsocket_destroy(tcp->socket);
132 gpr_mu_destroy(&tcp->mu);
133 grpc_slice_buffer_destroy(&tcp->last_read_buffer);
134 delete tcp;
135 }
136
137 #ifndef NDEBUG
138 #define TCP_UNREF(tcp, reason) tcp_unref((tcp), (reason), __FILE__, __LINE__)
139 #define TCP_REF(tcp, reason) tcp_ref((tcp), (reason), __FILE__, __LINE__)
140 static void tcp_unref(grpc_tcp* tcp, const char* reason, const char* file,
141 int line) {
142 if (grpc_tcp_trace.enabled()) {
143 gpr_atm val = gpr_atm_no_barrier_load(&tcp->refcount.count);
144 gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG,
145 "TCP unref %p : %s %" PRIdPTR " -> %" PRIdPTR, tcp, reason, val,
146 val - 1);
147 }
148 if (gpr_unref(&tcp->refcount)) {
149 tcp_free(tcp);
150 }
151 }
152
153 static void tcp_ref(grpc_tcp* tcp, const char* reason, const char* file,
154 int line) {
155 if (grpc_tcp_trace.enabled()) {
156 gpr_atm val = gpr_atm_no_barrier_load(&tcp->refcount.count);
157 gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG,
158 "TCP ref %p : %s %" PRIdPTR " -> %" PRIdPTR, tcp, reason, val,
159 val + 1);
160 }
161 gpr_ref(&tcp->refcount);
162 }
163 #else
164 #define TCP_UNREF(tcp, reason) tcp_unref((tcp))
165 #define TCP_REF(tcp, reason) tcp_ref((tcp))
166 static void tcp_unref(grpc_tcp* tcp) {
167 if (gpr_unref(&tcp->refcount)) {
168 tcp_free(tcp);
169 }
170 }
171
172 static void tcp_ref(grpc_tcp* tcp) { gpr_ref(&tcp->refcount); }
173 #endif
174
175 /* Asynchronous callback from the IOCP, or the background thread. */
176 static void on_read(void* tcpp, grpc_error_handle error) {
177 grpc_tcp* tcp = (grpc_tcp*)tcpp;
178 grpc_closure* cb = tcp->read_cb;
179 grpc_winsocket* socket = tcp->socket;
180 grpc_winsocket_callback_info* info = &socket->read_info;
181
182 if (grpc_tcp_trace.enabled()) {
183 gpr_log(GPR_INFO, "TCP:%p on_read", tcp);
184 }
185
186 if (error.ok()) {
187 if (info->wsa_error != 0 && !tcp->shutting_down) {
188 char* utf8_message = gpr_format_message(info->wsa_error);
189 error = GRPC_ERROR_CREATE(utf8_message);
190 gpr_free(utf8_message);
191 grpc_slice_buffer_reset_and_unref(tcp->read_slices);
192 } else {
193 if (info->bytes_transferred != 0 && !tcp->shutting_down) {
194 GPR_ASSERT((size_t)info->bytes_transferred <= tcp->read_slices->length);
195 if (static_cast<size_t>(info->bytes_transferred) !=
196 tcp->read_slices->length) {
197 grpc_slice_buffer_trim_end(
198 tcp->read_slices,
199 tcp->read_slices->length -
200 static_cast<size_t>(info->bytes_transferred),
201 &tcp->last_read_buffer);
202 }
203 GPR_ASSERT((size_t)info->bytes_transferred == tcp->read_slices->length);
204
205 if (grpc_tcp_trace.enabled()) {
206 size_t i;
207 for (i = 0; i < tcp->read_slices->count; i++) {
208 char* dump = grpc_dump_slice(tcp->read_slices->slices[i],
209 GPR_DUMP_HEX | GPR_DUMP_ASCII);
210 gpr_log(GPR_INFO, "READ %p (peer=%s): %s", tcp,
211 tcp->peer_string.c_str(), dump);
212 gpr_free(dump);
213 }
214 }
215 } else {
216 if (grpc_tcp_trace.enabled()) {
217 gpr_log(GPR_INFO, "TCP:%p unref read_slice", tcp);
218 }
219 grpc_slice_buffer_reset_and_unref(tcp->read_slices);
220 error = grpc_error_set_int(
221 tcp->shutting_down
222 ? GRPC_ERROR_CREATE_REFERENCING("TCP stream shutting down",
223 &tcp->shutdown_error, 1)
224 : GRPC_ERROR_CREATE("End of TCP stream"),
225 grpc_core::StatusIntProperty::kRpcStatus, GRPC_STATUS_UNAVAILABLE);
226 }
227 }
228 }
229
230 tcp->read_cb = NULL;
231 TCP_UNREF(tcp, "read");
232 grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error);
233 }
234
235 #define DEFAULT_TARGET_READ_SIZE 8192
236 #define MAX_WSABUF_COUNT 16
237 static void win_read(grpc_endpoint* ep, grpc_slice_buffer* read_slices,
238 grpc_closure* cb, bool urgent, int /*min_progress_size*/) {
239 grpc_tcp* tcp = (grpc_tcp*)ep;
240 grpc_winsocket* handle = tcp->socket;
241 grpc_winsocket_callback_info* info = &handle->read_info;
242 int status;
243 DWORD bytes_read = 0;
244 DWORD flags = 0;
245 WSABUF buffers[MAX_WSABUF_COUNT];
246 size_t i;
247
248 if (grpc_tcp_trace.enabled()) {
249 gpr_log(GPR_INFO, "TCP:%p win_read", tcp);
250 }
251
252 if (tcp->shutting_down) {
253 grpc_core::ExecCtx::Run(
254 DEBUG_LOCATION, cb,
255 grpc_error_set_int(
256 GRPC_ERROR_CREATE_REFERENCING("TCP socket is shutting down",
257 &tcp->shutdown_error, 1),
258 grpc_core::StatusIntProperty::kRpcStatus, GRPC_STATUS_UNAVAILABLE));
259 return;
260 }
261
262 tcp->read_cb = cb;
263 tcp->read_slices = read_slices;
264 grpc_slice_buffer_reset_and_unref(read_slices);
265 grpc_slice_buffer_swap(read_slices, &tcp->last_read_buffer);
266
267 if (tcp->read_slices->length < DEFAULT_TARGET_READ_SIZE / 2 &&
268 tcp->read_slices->count < MAX_WSABUF_COUNT) {
269 // TODO(jtattermusch): slice should be allocated using resource quota
270 grpc_slice_buffer_add(tcp->read_slices,
271 GRPC_SLICE_MALLOC(DEFAULT_TARGET_READ_SIZE));
272 }
273
274 GPR_ASSERT(tcp->read_slices->count <= MAX_WSABUF_COUNT);
275 for (i = 0; i < tcp->read_slices->count; i++) {
276 buffers[i].len = (ULONG)GRPC_SLICE_LENGTH(
277 tcp->read_slices->slices[i]); // we know slice size fits in 32bit.
278 buffers[i].buf = (char*)GRPC_SLICE_START_PTR(tcp->read_slices->slices[i]);
279 }
280
281 TCP_REF(tcp, "read");
282
283 /* First let's try a synchronous, non-blocking read. */
284 status = WSARecv(tcp->socket->socket, buffers, (DWORD)tcp->read_slices->count,
285 &bytes_read, &flags, NULL, NULL);
286 info->wsa_error = status == 0 ? 0 : WSAGetLastError();
287
288 /* Did we get data immediately ? Yay. */
289 if (info->wsa_error != WSAEWOULDBLOCK) {
290 info->bytes_transferred = bytes_read;
291 grpc_core::ExecCtx::Run(DEBUG_LOCATION, &tcp->on_read, absl::OkStatus());
292 return;
293 }
294
295 /* Otherwise, let's retry, by queuing a read. */
296 memset(&tcp->socket->read_info.overlapped, 0, sizeof(OVERLAPPED));
297 status = WSARecv(tcp->socket->socket, buffers, (DWORD)tcp->read_slices->count,
298 &bytes_read, &flags, &info->overlapped, NULL);
299
300 if (status != 0) {
301 int wsa_error = WSAGetLastError();
302 if (wsa_error != WSA_IO_PENDING) {
303 info->wsa_error = wsa_error;
304 grpc_core::ExecCtx::Run(DEBUG_LOCATION, &tcp->on_read,
305 GRPC_WSA_ERROR(info->wsa_error, "WSARecv"));
306 return;
307 }
308 }
309
310 grpc_socket_notify_on_read(tcp->socket, &tcp->on_read);
311 }
312
313 /* Asynchronous callback from the IOCP, or the background thread. */
314 static void on_write(void* tcpp, grpc_error_handle error) {
315 grpc_tcp* tcp = (grpc_tcp*)tcpp;
316 grpc_winsocket* handle = tcp->socket;
317 grpc_winsocket_callback_info* info = &handle->write_info;
318 grpc_closure* cb;
319
320 if (grpc_tcp_trace.enabled()) {
321 gpr_log(GPR_INFO, "TCP:%p on_write", tcp);
322 }
323
324 gpr_mu_lock(&tcp->mu);
325 cb = tcp->write_cb;
326 tcp->write_cb = NULL;
327 gpr_mu_unlock(&tcp->mu);
328
329 if (error.ok()) {
330 if (info->wsa_error != 0) {
331 error = GRPC_WSA_ERROR(info->wsa_error, "WSASend");
332 } else {
333 GPR_ASSERT(info->bytes_transferred == tcp->write_slices->length);
334 }
335 }
336
337 TCP_UNREF(tcp, "write");
338 grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error);
339 }
340
341 /* Initiates a write. */
342 static void win_write(grpc_endpoint* ep, grpc_slice_buffer* slices,
343 grpc_closure* cb, void* arg, int /*max_frame_size*/) {
344 grpc_tcp* tcp = (grpc_tcp*)ep;
345 grpc_winsocket* socket = tcp->socket;
346 grpc_winsocket_callback_info* info = &socket->write_info;
347 unsigned i;
348 DWORD bytes_sent;
349 int status;
350 WSABUF local_buffers[MAX_WSABUF_COUNT];
351 WSABUF* allocated = NULL;
352 WSABUF* buffers = local_buffers;
353 size_t len;
354
355 if (grpc_tcp_trace.enabled()) {
356 size_t i;
357 for (i = 0; i < slices->count; i++) {
358 char* data =
359 grpc_dump_slice(slices->slices[i], GPR_DUMP_HEX | GPR_DUMP_ASCII);
360 gpr_log(GPR_INFO, "WRITE %p (peer=%s): %s", tcp, tcp->peer_string.c_str(),
361 data);
362 gpr_free(data);
363 }
364 }
365
366 if (tcp->shutting_down) {
367 grpc_core::ExecCtx::Run(
368 DEBUG_LOCATION, cb,
369 grpc_error_set_int(
370 GRPC_ERROR_CREATE_REFERENCING("TCP socket is shutting down",
371 &tcp->shutdown_error, 1),
372 grpc_core::StatusIntProperty::kRpcStatus, GRPC_STATUS_UNAVAILABLE));
373 return;
374 }
375
376 tcp->write_cb = cb;
377 tcp->write_slices = slices;
378 GPR_ASSERT(tcp->write_slices->count <= UINT_MAX);
379 if (tcp->write_slices->count > GPR_ARRAY_SIZE(local_buffers)) {
380 buffers = (WSABUF*)gpr_malloc(sizeof(WSABUF) * tcp->write_slices->count);
381 allocated = buffers;
382 }
383
384 for (i = 0; i < tcp->write_slices->count; i++) {
385 len = GRPC_SLICE_LENGTH(tcp->write_slices->slices[i]);
386 GPR_ASSERT(len <= ULONG_MAX);
387 buffers[i].len = (ULONG)len;
388 buffers[i].buf = (char*)GRPC_SLICE_START_PTR(tcp->write_slices->slices[i]);
389 }
390
391 /* First, let's try a synchronous, non-blocking write. */
392 status = WSASend(socket->socket, buffers, (DWORD)tcp->write_slices->count,
393 &bytes_sent, 0, NULL, NULL);
394 info->wsa_error = status == 0 ? 0 : WSAGetLastError();
395
396 /* We would kind of expect to get a WSAEWOULDBLOCK here, especially on a busy
397 connection that has its send queue filled up. But if we don't, then we can
398 avoid doing an async write operation at all. */
399 if (info->wsa_error != WSAEWOULDBLOCK) {
400 grpc_error_handle error = status == 0
401 ? absl::OkStatus()
402 : GRPC_WSA_ERROR(info->wsa_error, "WSASend");
403 grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error);
404 if (allocated) gpr_free(allocated);
405 return;
406 }
407
408 TCP_REF(tcp, "write");
409
410 /* If we got a WSAEWOULDBLOCK earlier, then we need to re-do the same
411 operation, this time asynchronously. */
412 memset(&socket->write_info.overlapped, 0, sizeof(OVERLAPPED));
413 status = WSASend(socket->socket, buffers, (DWORD)tcp->write_slices->count,
414 &bytes_sent, 0, &socket->write_info.overlapped, NULL);
415 if (allocated) gpr_free(allocated);
416
417 if (status != 0) {
418 int wsa_error = WSAGetLastError();
419 if (wsa_error != WSA_IO_PENDING) {
420 TCP_UNREF(tcp, "write");
421 grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb,
422 GRPC_WSA_ERROR(wsa_error, "WSASend"));
423 return;
424 }
425 }
426
427 /* As all is now setup, we can now ask for the IOCP notification. It may
428 trigger the callback immediately however, but no matter. */
429 grpc_socket_notify_on_write(socket, &tcp->on_write);
430 }
431
432 static void win_add_to_pollset(grpc_endpoint* ep, grpc_pollset* ps) {
433 grpc_tcp* tcp;
434 (void)ps;
435 tcp = (grpc_tcp*)ep;
436 grpc_iocp_add_socket(tcp->socket);
437 }
438
439 static void win_add_to_pollset_set(grpc_endpoint* ep, grpc_pollset_set* pss) {
440 grpc_tcp* tcp;
441 (void)pss;
442 tcp = (grpc_tcp*)ep;
443 grpc_iocp_add_socket(tcp->socket);
444 }
445
446 static void win_delete_from_pollset_set(grpc_endpoint* ep,
447 grpc_pollset_set* pss) {}
448
449 /* Initiates a shutdown of the TCP endpoint. This will queue abort callbacks
450 for the potential read and write operations. It is up to the caller to
451 guarantee this isn't called in parallel to a read or write request, so
452 we're not going to protect against these. However the IO Completion Port
453 callback will happen from another thread, so we need to protect against
454 concurrent access of the data structure in that regard. */
455 static void win_shutdown(grpc_endpoint* ep, grpc_error_handle why) {
456 grpc_tcp* tcp = (grpc_tcp*)ep;
457 gpr_mu_lock(&tcp->mu);
458 /* At that point, what may happen is that we're already inside the IOCP
459 callback. See the comments in on_read and on_write. */
460 if (!tcp->shutting_down) {
461 tcp->shutting_down = 1;
462 tcp->shutdown_error = why;
463 }
464 grpc_winsocket_shutdown(tcp->socket);
465 gpr_mu_unlock(&tcp->mu);
466 }
467
468 static void win_destroy(grpc_endpoint* ep) {
469 grpc_tcp* tcp = (grpc_tcp*)ep;
470 grpc_slice_buffer_reset_and_unref(&tcp->last_read_buffer);
471 TCP_UNREF(tcp, "destroy");
472 }
473
474 static absl::string_view win_get_peer(grpc_endpoint* ep) {
475 grpc_tcp* tcp = (grpc_tcp*)ep;
476 return tcp->peer_string;
477 }
478
479 static absl::string_view win_get_local_address(grpc_endpoint* ep) {
480 grpc_tcp* tcp = (grpc_tcp*)ep;
481 return tcp->local_address;
482 }
483
484 static int win_get_fd(grpc_endpoint* ep) { return -1; }
485
486 static bool win_can_track_err(grpc_endpoint* ep) { return false; }
487
488 static grpc_endpoint_vtable vtable = {win_read,
489 win_write,
490 win_add_to_pollset,
491 win_add_to_pollset_set,
492 win_delete_from_pollset_set,
493 win_shutdown,
494 win_destroy,
495 win_get_peer,
496 win_get_local_address,
497 win_get_fd,
498 win_can_track_err};
499
500 grpc_endpoint* grpc_tcp_create(grpc_winsocket* socket,
501 absl::string_view peer_string) {
502 // TODO(jtattermusch): C++ize grpc_tcp and its dependencies (i.e. add
503 // constructors) to ensure proper initialization
504 grpc_tcp* tcp = new grpc_tcp{};
505 tcp->base.vtable = &vtable;
506 tcp->socket = socket;
507 gpr_mu_init(&tcp->mu);
508 gpr_ref_init(&tcp->refcount, 1);
509 GRPC_CLOSURE_INIT(&tcp->on_read, on_read, tcp, grpc_schedule_on_exec_ctx);
510 GRPC_CLOSURE_INIT(&tcp->on_write, on_write, tcp, grpc_schedule_on_exec_ctx);
511 grpc_resolved_address resolved_local_addr;
512 resolved_local_addr.len = sizeof(resolved_local_addr.addr);
513 absl::StatusOr<std::string> addr_uri;
514 if (getsockname(tcp->socket->socket,
515 reinterpret_cast<sockaddr*>(resolved_local_addr.addr),
516 &resolved_local_addr.len) < 0 ||
517 !(addr_uri = grpc_sockaddr_to_uri(&resolved_local_addr)).ok()) {
518 tcp->local_address = "";
519 } else {
520 tcp->local_address = grpc_sockaddr_to_uri(&resolved_local_addr).value();
521 }
522 tcp->peer_string = std::string(peer_string);
523 grpc_slice_buffer_init(&tcp->last_read_buffer);
524 return &tcp->base;
525 }
526
527 #endif /* GRPC_WINSOCK_SOCKET */