Debian Codegraph @

src/core/lib/iomgr/socket_utils_common_posix.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_POSIX_SOCKET_UTILS_COMMON
24
25 #include <arpa/inet.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <netinet/in.h>
30
31 #include "src/core/lib/iomgr/socket_utils.h"
32 #include "src/core/lib/iomgr/socket_utils_posix.h"
33 #ifdef GRPC_LINUX_TCP_H
34 #include <linux/tcp.h>
35 #else
36 #include <netinet/tcp.h>
37 #endif
38 #include <stdio.h>
39 #include <string.h>
40 #include <sys/socket.h>
41 #include <sys/types.h>
42 #include <unistd.h>
43
44 #include <string>
45
46 #include <grpc/event_engine/endpoint_config.h>
47 #include <grpc/support/alloc.h>
48 #include <grpc/support/log.h>
49 #include <grpc/support/sync.h>
50
51 #include "src/core/lib/address_utils/sockaddr_utils.h"
52 #include "src/core/lib/gpr/string.h"
53 #include "src/core/lib/gprpp/strerror.h"
54 #include "src/core/lib/iomgr/sockaddr.h"
55
56 /* set a socket to use zerocopy */
57 grpc_error_handle grpc_set_socket_zerocopy(int fd) {
58 #ifdef GRPC_LINUX_ERRQUEUE
59 const int enable = 1;
60 auto err = setsockopt(fd, SOL_SOCKET, SO_ZEROCOPY, &enable, sizeof(enable));
61 if (err != 0) {
62 return GRPC_OS_ERROR(errno, "setsockopt(SO_ZEROCOPY)");
63 }
64 return absl::OkStatus();
65 #else
66 (void)fd;
67 return GRPC_OS_ERROR(ENOSYS, "setsockopt(SO_ZEROCOPY)");
68 #endif
69 }
70
71 /* set a socket to non blocking mode */
72 grpc_error_handle grpc_set_socket_nonblocking(int fd, int non_blocking) {
73 int oldflags = fcntl(fd, F_GETFL, 0);
74 if (oldflags < 0) {
75 return GRPC_OS_ERROR(errno, "fcntl");
76 }
77
78 if (non_blocking) {
79 oldflags |= O_NONBLOCK;
80 } else {
81 oldflags &= ~O_NONBLOCK;
82 }
83
84 if (fcntl(fd, F_SETFL, oldflags) != 0) {
85 return GRPC_OS_ERROR(errno, "fcntl");
86 }
87
88 return absl::OkStatus();
89 }
90
91 grpc_error_handle grpc_set_socket_no_sigpipe_if_possible(int fd) {
92 #ifdef GRPC_HAVE_SO_NOSIGPIPE
93 int val = 1;
94 int newval;
95 socklen_t intlen = sizeof(newval);
96 if (0 != setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &val, sizeof(val))) {
97 return GRPC_OS_ERROR(errno, "setsockopt(SO_NOSIGPIPE)");
98 }
99 if (0 != getsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &newval, &intlen)) {
100 return GRPC_OS_ERROR(errno, "getsockopt(SO_NOSIGPIPE)");
101 }
102 if ((newval != 0) != (val != 0)) {
103 return GRPC_ERROR_CREATE("Failed to set SO_NOSIGPIPE");
104 }
105 #else
106 // Avoid unused parameter warning for conditional parameter
107 (void)fd;
108 #endif
109 return absl::OkStatus();
110 }
111
112 grpc_error_handle grpc_set_socket_ip_pktinfo_if_possible(int fd) {
113 // Use conditionally-important parameter to avoid warning
114 (void)fd;
115 #ifdef GRPC_HAVE_IP_PKTINFO
116 int get_local_ip = 1;
117 if (0 != setsockopt(fd, IPPROTO_IP, IP_PKTINFO, &get_local_ip,
118 sizeof(get_local_ip))) {
119 return GRPC_OS_ERROR(errno, "setsockopt(IP_PKTINFO)");
120 }
121 #endif
122 return absl::OkStatus();
123 }
124
125 grpc_error_handle grpc_set_socket_ipv6_recvpktinfo_if_possible(int fd) {
126 // Use conditionally-important parameter to avoid warning
127 (void)fd;
128 #ifdef GRPC_HAVE_IPV6_RECVPKTINFO
129 int get_local_ip = 1;
130 if (0 != setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &get_local_ip,
131 sizeof(get_local_ip))) {
132 return GRPC_OS_ERROR(errno, "setsockopt(IPV6_RECVPKTINFO)");
133 }
134 #endif
135 return absl::OkStatus();
136 }
137
138 grpc_error_handle grpc_set_socket_sndbuf(int fd, int buffer_size_bytes) {
139 return 0 == setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &buffer_size_bytes,
140 sizeof(buffer_size_bytes))
141 ? absl::OkStatus()
142 : GRPC_OS_ERROR(errno, "setsockopt(SO_SNDBUF)");
143 }
144
145 grpc_error_handle grpc_set_socket_rcvbuf(int fd, int buffer_size_bytes) {
146 return 0 == setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &buffer_size_bytes,
147 sizeof(buffer_size_bytes))
148 ? absl::OkStatus()
149 : GRPC_OS_ERROR(errno, "setsockopt(SO_RCVBUF)");
150 }
151
152 /* set a socket to close on exec */
153 grpc_error_handle grpc_set_socket_cloexec(int fd, int close_on_exec) {
154 int oldflags = fcntl(fd, F_GETFD, 0);
155 if (oldflags < 0) {
156 return GRPC_OS_ERROR(errno, "fcntl");
157 }
158
159 if (close_on_exec) {
160 oldflags |= FD_CLOEXEC;
161 } else {
162 oldflags &= ~FD_CLOEXEC;
163 }
164
165 if (fcntl(fd, F_SETFD, oldflags) != 0) {
166 return GRPC_OS_ERROR(errno, "fcntl");
167 }
168
169 return absl::OkStatus();
170 }
171
172 /* set a socket to reuse old addresses */
173 grpc_error_handle grpc_set_socket_reuse_addr(int fd, int reuse) {
174 int val = (reuse != 0);
175 int newval;
176 socklen_t intlen = sizeof(newval);
177 if (0 != setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val))) {
178 return GRPC_OS_ERROR(errno, "setsockopt(SO_REUSEADDR)");
179 }
180 if (0 != getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &newval, &intlen)) {
181 return GRPC_OS_ERROR(errno, "getsockopt(SO_REUSEADDR)");
182 }
183 if ((newval != 0) != val) {
184 return GRPC_ERROR_CREATE("Failed to set SO_REUSEADDR");
185 }
186
187 return absl::OkStatus();
188 }
189
190 /* set a socket to reuse old addresses */
191 grpc_error_handle grpc_set_socket_reuse_port(int fd, int reuse) {
192 #ifndef SO_REUSEPORT
193 return GRPC_ERROR_CREATE("SO_REUSEPORT unavailable on compiling system");
194 #else
195 int val = (reuse != 0);
196 int newval;
197 socklen_t intlen = sizeof(newval);
198 if (0 != setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &val, sizeof(val))) {
199 return GRPC_OS_ERROR(errno, "setsockopt(SO_REUSEPORT)");
200 }
201 if (0 != getsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &newval, &intlen)) {
202 return GRPC_OS_ERROR(errno, "getsockopt(SO_REUSEPORT)");
203 }
204 if ((newval != 0) != val) {
205 return GRPC_ERROR_CREATE("Failed to set SO_REUSEPORT");
206 }
207
208 return absl::OkStatus();
209 #endif
210 }
211
212 static gpr_once g_probe_so_reuesport_once = GPR_ONCE_INIT;
213 static int g_support_so_reuseport = false;
214
215 void probe_so_reuseport_once(void) {
216 int s = socket(AF_INET, SOCK_STREAM, 0);
217 if (s < 0) {
218 /* This might be an ipv6-only environment in which case 'socket(AF_INET,..)'
219 call would fail. Try creating IPv6 socket in that case */
220 s = socket(AF_INET6, SOCK_STREAM, 0);
221 }
222 if (s >= 0) {
223 g_support_so_reuseport = GRPC_LOG_IF_ERROR(
224 "check for SO_REUSEPORT", grpc_set_socket_reuse_port(s, 1));
225 close(s);
226 }
227 }
228
229 bool grpc_is_socket_reuse_port_supported() {
230 gpr_once_init(&g_probe_so_reuesport_once, probe_so_reuseport_once);
231 return g_support_so_reuseport;
232 }
233
234 /* disable nagle */
235 grpc_error_handle grpc_set_socket_low_latency(int fd, int low_latency) {
236 int val = (low_latency != 0);
237 int newval;
238 socklen_t intlen = sizeof(newval);
239 if (0 != setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val))) {
240 return GRPC_OS_ERROR(errno, "setsockopt(TCP_NODELAY)");
241 }
242 if (0 != getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &newval, &intlen)) {
243 return GRPC_OS_ERROR(errno, "getsockopt(TCP_NODELAY)");
244 }
245 if ((newval != 0) != val) {
246 return GRPC_ERROR_CREATE("Failed to set TCP_NODELAY");
247 }
248 return absl::OkStatus();
249 }
250
251 /* The default values for TCP_USER_TIMEOUT are currently configured to be in
252 * line with the default values of KEEPALIVE_TIMEOUT as proposed in
253 * https://github.com/grpc/proposal/blob/master/A18-tcp-user-timeout.md */
254 #define DEFAULT_CLIENT_TCP_USER_TIMEOUT_MS 20000 /* 20 seconds */
255 #define DEFAULT_SERVER_TCP_USER_TIMEOUT_MS 20000 /* 20 seconds */
256
257 static int g_default_client_tcp_user_timeout_ms =
258 DEFAULT_CLIENT_TCP_USER_TIMEOUT_MS;
259 static int g_default_server_tcp_user_timeout_ms =
260 DEFAULT_SERVER_TCP_USER_TIMEOUT_MS;
261 static bool g_default_client_tcp_user_timeout_enabled = false;
262 static bool g_default_server_tcp_user_timeout_enabled = true;
263
264 #if GPR_LINUX == 1
265 // For Linux, it will be detected to support TCP_USER_TIMEOUT
266 #ifndef TCP_USER_TIMEOUT
267 #define TCP_USER_TIMEOUT 18
268 #endif
269 #define SOCKET_SUPPORTS_TCP_USER_TIMEOUT_DEFAULT 0
270 #else
271 // For non-Linux, TCP_USER_TIMEOUT will be used if TCP_USER_TIMEOUT is defined.
272 #ifdef TCP_USER_TIMEOUT
273 #define SOCKET_SUPPORTS_TCP_USER_TIMEOUT_DEFAULT 0
274 #else
275 #define TCP_USER_TIMEOUT 0
276 #define SOCKET_SUPPORTS_TCP_USER_TIMEOUT_DEFAULT -1
277 #endif // TCP_USER_TIMEOUT
278 #endif // GPR_LINUX == 1
279
280 // Whether the socket supports TCP_USER_TIMEOUT option.
281 // (0: don't know, 1: support, -1: not support)
282 static std::atomic<int> g_socket_supports_tcp_user_timeout(
283 SOCKET_SUPPORTS_TCP_USER_TIMEOUT_DEFAULT);
284
285 void config_default_tcp_user_timeout(bool enable, int timeout, bool is_client) {
286 if (is_client) {
287 g_default_client_tcp_user_timeout_enabled = enable;
288 if (timeout > 0) {
289 g_default_client_tcp_user_timeout_ms = timeout;
290 }
291 } else {
292 g_default_server_tcp_user_timeout_enabled = enable;
293 if (timeout > 0) {
294 g_default_server_tcp_user_timeout_ms = timeout;
295 }
296 }
297 }
298
299 /* Set TCP_USER_TIMEOUT */
300 grpc_error_handle grpc_set_socket_tcp_user_timeout(
301 int fd, const grpc_core::PosixTcpOptions& options, bool is_client) {
302 // Use conditionally-important parameter to avoid warning
303 (void)fd;
304 (void)is_client;
305 extern grpc_core::TraceFlag grpc_tcp_trace;
306 if (g_socket_supports_tcp_user_timeout.load() >= 0) {
307 bool enable;
308 int timeout;
309 if (is_client) {
310 enable = g_default_client_tcp_user_timeout_enabled;
311 timeout = g_default_client_tcp_user_timeout_ms;
312 } else {
313 enable = g_default_server_tcp_user_timeout_enabled;
314 timeout = g_default_server_tcp_user_timeout_ms;
315 }
316 int value = options.keep_alive_time_ms;
317 if (value > 0) {
318 enable = value != INT_MAX;
319 }
320 value = options.keep_alive_timeout_ms;
321 if (value > 0) {
322 timeout = value;
323 }
324 if (enable) {
325 int newval;
326 socklen_t len = sizeof(newval);
327 // If this is the first time to use TCP_USER_TIMEOUT, try to check
328 // if it is available.
329 if (g_socket_supports_tcp_user_timeout.load() == 0) {
330 if (0 != getsockopt(fd, IPPROTO_TCP, TCP_USER_TIMEOUT, &newval, &len)) {
331 gpr_log(GPR_INFO,
332 "TCP_USER_TIMEOUT is not available. TCP_USER_TIMEOUT won't "
333 "be used thereafter");
334 g_socket_supports_tcp_user_timeout.store(-1);
335 } else {
336 gpr_log(GPR_INFO,
337 "TCP_USER_TIMEOUT is available. TCP_USER_TIMEOUT will be "
338 "used thereafter");
339 g_socket_supports_tcp_user_timeout.store(1);
340 }
341 }
342 if (g_socket_supports_tcp_user_timeout.load() > 0) {
343 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
344 gpr_log(GPR_INFO, "Enabling TCP_USER_TIMEOUT with a timeout of %d ms",
345 timeout);
346 }
347 if (0 != setsockopt(fd, IPPROTO_TCP, TCP_USER_TIMEOUT, &timeout,
348 sizeof(timeout))) {
349 gpr_log(GPR_ERROR, "setsockopt(TCP_USER_TIMEOUT) %s",
350 grpc_core::StrError(errno).c_str());
351 return absl::OkStatus();
352 }
353 if (0 != getsockopt(fd, IPPROTO_TCP, TCP_USER_TIMEOUT, &newval, &len)) {
354 gpr_log(GPR_ERROR, "getsockopt(TCP_USER_TIMEOUT) %s",
355 grpc_core::StrError(errno).c_str());
356 return absl::OkStatus();
357 }
358 if (newval != timeout) {
359 /* Do not fail on failing to set TCP_USER_TIMEOUT for now. */
360 gpr_log(GPR_ERROR, "Failed to set TCP_USER_TIMEOUT");
361 return absl::OkStatus();
362 }
363 }
364 }
365 } else {
366 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
367 gpr_log(GPR_INFO, "TCP_USER_TIMEOUT not supported for this platform");
368 }
369 }
370 return absl::OkStatus();
371 }
372
373 /* set a socket using a grpc_socket_mutator */
374 grpc_error_handle grpc_set_socket_with_mutator(int fd, grpc_fd_usage usage,
375 grpc_socket_mutator* mutator) {
376 GPR_ASSERT(mutator);
377 if (!grpc_socket_mutator_mutate_fd(mutator, fd, usage)) {
378 return GRPC_ERROR_CREATE("grpc_socket_mutator failed.");
379 }
380 return absl::OkStatus();
381 }
382
383 grpc_error_handle grpc_apply_socket_mutator_in_args(
384 int fd, grpc_fd_usage usage, const grpc_core::PosixTcpOptions& options) {
385 if (options.socket_mutator == nullptr) {
386 return absl::OkStatus();
387 }
388 return grpc_set_socket_with_mutator(fd, usage, options.socket_mutator);
389 }
390
391 static gpr_once g_probe_ipv6_once = GPR_ONCE_INIT;
392 static int g_ipv6_loopback_available;
393
394 static void probe_ipv6_once(void) {
395 int fd = socket(AF_INET6, SOCK_STREAM, 0);
396 g_ipv6_loopback_available = 0;
397 if (fd < 0) {
398 gpr_log(GPR_INFO, "Disabling AF_INET6 sockets because socket() failed.");
399 } else {
400 grpc_sockaddr_in6 addr;
401 memset(&addr, 0, sizeof(addr));
402 addr.sin6_family = AF_INET6;
403 addr.sin6_addr.s6_addr[15] = 1; /* [::1]:0 */
404 if (bind(fd, reinterpret_cast<grpc_sockaddr*>(&addr), sizeof(addr)) == 0) {
405 g_ipv6_loopback_available = 1;
406 } else {
407 gpr_log(GPR_INFO,
408 "Disabling AF_INET6 sockets because ::1 is not available.");
409 }
410 close(fd);
411 }
412 }
413
414 int grpc_ipv6_loopback_available(void) {
415 gpr_once_init(&g_probe_ipv6_once, probe_ipv6_once);
416 return g_ipv6_loopback_available;
417 }
418
419 static grpc_error_handle error_for_fd(int fd,
420 const grpc_resolved_address* addr) {
421 if (fd >= 0) return absl::OkStatus();
422 auto addr_str = grpc_sockaddr_to_string(addr, false);
423 grpc_error_handle err = grpc_error_set_str(
424 GRPC_OS_ERROR(errno, "socket"),
425 grpc_core::StatusStrProperty::kTargetAddress,
426 addr_str.ok() ? addr_str.value() : addr_str.status().ToString());
427 return err;
428 }
429
430 grpc_error_handle grpc_create_dualstack_socket(
431 const grpc_resolved_address* resolved_addr, int type, int protocol,
432 grpc_dualstack_mode* dsmode, int* newfd) {
433 return grpc_create_dualstack_socket_using_factory(
434 nullptr, resolved_addr, type, protocol, dsmode, newfd);
435 }
436
437 static int create_socket(grpc_socket_factory* factory, int domain, int type,
438 int protocol) {
439 return (factory != nullptr)
440 ? grpc_socket_factory_socket(factory, domain, type, protocol)
441 : socket(domain, type, protocol);
442 }
443
444 grpc_error_handle grpc_create_dualstack_socket_using_factory(
445 grpc_socket_factory* factory, const grpc_resolved_address* resolved_addr,
446 int type, int protocol, grpc_dualstack_mode* dsmode, int* newfd) {
447 const grpc_sockaddr* addr =
448 reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr);
449 int family = addr->sa_family;
450 if (family == AF_INET6) {
451 if (grpc_ipv6_loopback_available()) {
452 *newfd = create_socket(factory, family, type, protocol);
453 } else {
454 *newfd = -1;
455 errno = EAFNOSUPPORT;
456 }
457 /* Check if we've got a valid dualstack socket. */
458 if (*newfd >= 0 && grpc_set_socket_dualstack(*newfd)) {
459 *dsmode = GRPC_DSMODE_DUALSTACK;
460 return absl::OkStatus();
461 }
462 /* If this isn't an IPv4 address, then return whatever we've got. */
463 if (!grpc_sockaddr_is_v4mapped(resolved_addr, nullptr)) {
464 *dsmode = GRPC_DSMODE_IPV6;
465 return error_for_fd(*newfd, resolved_addr);
466 }
467 /* Fall back to AF_INET. */
468 if (*newfd >= 0) {
469 close(*newfd);
470 }
471 family = AF_INET;
472 }
473 *dsmode = family == AF_INET ? GRPC_DSMODE_IPV4 : GRPC_DSMODE_NONE;
474 *newfd = create_socket(factory, family, type, protocol);
475 return error_for_fd(*newfd, resolved_addr);
476 }
477
478 #endif