blob: 399f7b76e69058edd77a8f384b753e560b2d998e [file] [log] [blame]
Willy Tarreau18b7df72020-08-28 12:07:22 +02001/*
2 * Generic code for native (BSD-compatible) sockets
3 *
4 * Copyright 2000-2020 Willy Tarreau <w@1wt.eu>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Willy Tarreauf1dc9f22020-10-15 09:21:31 +020013#define _GNU_SOURCE
Willy Tarreau18b7df72020-08-28 12:07:22 +020014#include <ctype.h>
15#include <errno.h>
16#include <fcntl.h>
17#include <stdio.h>
18#include <stdlib.h>
19#include <string.h>
20#include <time.h>
21
22#include <sys/param.h>
23#include <sys/socket.h>
24#include <sys/types.h>
25
Willy Tarreau42961742020-08-28 18:42:45 +020026#include <net/if.h>
27
Willy Tarreau18b7df72020-08-28 12:07:22 +020028#include <haproxy/api.h>
29#include <haproxy/connection.h>
Willy Tarreaua74cb382020-10-15 21:29:49 +020030#include <haproxy/listener.h>
Willy Tarreauf1dc9f22020-10-15 09:21:31 +020031#include <haproxy/log.h>
Willy Tarreau18b7df72020-08-28 12:07:22 +020032#include <haproxy/namespace.h>
33#include <haproxy/sock.h>
Willy Tarreau2d34a712020-08-28 16:49:41 +020034#include <haproxy/sock_inet.h>
Willy Tarreau18b7df72020-08-28 12:07:22 +020035#include <haproxy/tools.h>
36
Willy Tarreau9f775762022-01-28 18:28:18 +010037#define SOCK_XFER_OPT_FOREIGN 0x000000001
38#define SOCK_XFER_OPT_V6ONLY 0x000000002
39#define SOCK_XFER_OPT_DGRAM 0x000000004
40
Willy Tarreau063d47d2020-08-28 16:29:53 +020041/* the list of remaining sockets transferred from an older process */
Willy Tarreau9f775762022-01-28 18:28:18 +010042struct xfer_sock_list {
43 int fd;
44 int options; /* socket options as SOCK_XFER_OPT_* */
45 char *iface;
46 char *namespace;
47 int if_namelen;
48 int ns_namelen;
49 struct xfer_sock_list *prev;
50 struct xfer_sock_list *next;
51 struct sockaddr_storage addr;
52};
53
54static struct xfer_sock_list *xfer_sock_list;
Willy Tarreau18b7df72020-08-28 12:07:22 +020055
Willy Tarreauf1dc9f22020-10-15 09:21:31 +020056
57/* Accept an incoming connection from listener <l>, and return it, as well as
58 * a CO_AC_* status code into <status> if not null. Null is returned on error.
59 * <l> must be a valid listener with a valid frontend.
60 */
61struct connection *sock_accept_conn(struct listener *l, int *status)
62{
63#ifdef USE_ACCEPT4
64 static int accept4_broken;
65#endif
66 struct proxy *p = l->bind_conf->frontend;
Willy Tarreau344b8fc2020-10-15 09:43:31 +020067 struct connection *conn = NULL;
68 struct sockaddr_storage *addr = NULL;
Willy Tarreauf1dc9f22020-10-15 09:21:31 +020069 socklen_t laddr;
70 int ret;
71 int cfd;
72
Willy Tarreau344b8fc2020-10-15 09:43:31 +020073 if (!sockaddr_alloc(&addr, NULL, 0))
Willy Tarreauf1dc9f22020-10-15 09:21:31 +020074 goto fail_addr;
75
76 /* accept() will mark all accepted FDs O_NONBLOCK and the ones accepted
77 * in the master process as FD_CLOEXEC. It's not done for workers
78 * because 1) workers are not supposed to execute anything so there's
79 * no reason for uselessly slowing down everything, and 2) that would
80 * prevent us from implementing fd passing in the future.
81 */
82#ifdef USE_ACCEPT4
83 laddr = sizeof(*conn->src);
84
85 /* only call accept4() if it's known to be safe, otherwise fallback to
86 * the legacy accept() + fcntl().
87 */
88 if (unlikely(accept4_broken) ||
Willy Tarreau344b8fc2020-10-15 09:43:31 +020089 (((cfd = accept4(l->rx.fd, (struct sockaddr*)addr, &laddr,
Willy Tarreauf1dc9f22020-10-15 09:21:31 +020090 SOCK_NONBLOCK | (master ? SOCK_CLOEXEC : 0))) == -1) &&
91 (errno == ENOSYS || errno == EINVAL || errno == EBADF) &&
92 (accept4_broken = 1)))
93#endif
94 {
95 laddr = sizeof(*conn->src);
Willy Tarreau344b8fc2020-10-15 09:43:31 +020096 if ((cfd = accept(l->rx.fd, (struct sockaddr*)addr, &laddr)) != -1) {
Willy Tarreauf1dc9f22020-10-15 09:21:31 +020097 fcntl(cfd, F_SETFL, O_NONBLOCK);
98 if (master)
99 fcntl(cfd, F_SETFD, FD_CLOEXEC);
100 }
101 }
102
103 if (likely(cfd != -1)) {
104 /* Perfect, the connection was accepted */
Willy Tarreau344b8fc2020-10-15 09:43:31 +0200105 conn = conn_new(&l->obj_type);
106 if (!conn)
107 goto fail_conn;
108
109 conn->src = addr;
Willy Tarreauf1dc9f22020-10-15 09:21:31 +0200110 conn->handle.fd = cfd;
111 conn->flags |= CO_FL_ADDR_FROM_SET;
112 ret = CO_AC_DONE;
113 goto done;
114 }
115
116 /* error conditions below */
Willy Tarreau344b8fc2020-10-15 09:43:31 +0200117 sockaddr_free(&addr);
Willy Tarreauf1dc9f22020-10-15 09:21:31 +0200118
119 switch (errno) {
120 case EAGAIN:
121 ret = CO_AC_DONE; /* nothing more to accept */
Willy Tarreauf5090652021-04-06 17:23:40 +0200122 if (fdtab[l->rx.fd].state & (FD_POLL_HUP|FD_POLL_ERR)) {
Willy Tarreauf1dc9f22020-10-15 09:21:31 +0200123 /* the listening socket might have been disabled in a shared
124 * process and we're a collateral victim. We'll just pause for
125 * a while in case it comes back. In the mean time, we need to
126 * clear this sticky flag.
127 */
Willy Tarreauf5090652021-04-06 17:23:40 +0200128 _HA_ATOMIC_AND(&fdtab[l->rx.fd].state, ~(FD_POLL_HUP|FD_POLL_ERR));
Willy Tarreauf1dc9f22020-10-15 09:21:31 +0200129 ret = CO_AC_PAUSE;
130 }
131 fd_cant_recv(l->rx.fd);
132 break;
133
134 case EINVAL:
135 /* might be trying to accept on a shut fd (eg: soft stop) */
136 ret = CO_AC_PAUSE;
137 break;
138
139 case EINTR:
140 case ECONNABORTED:
141 ret = CO_AC_RETRY;
142 break;
143
144 case ENFILE:
145 if (p)
146 send_log(p, LOG_EMERG,
147 "Proxy %s reached system FD limit (maxsock=%d). Please check system tunables.\n",
148 p->id, global.maxsock);
149 ret = CO_AC_PAUSE;
150 break;
151
152 case EMFILE:
153 if (p)
154 send_log(p, LOG_EMERG,
155 "Proxy %s reached process FD limit (maxsock=%d). Please check 'ulimit-n' and restart.\n",
156 p->id, global.maxsock);
157 ret = CO_AC_PAUSE;
158 break;
159
160 case ENOBUFS:
161 case ENOMEM:
162 if (p)
163 send_log(p, LOG_EMERG,
164 "Proxy %s reached system memory limit (maxsock=%d). Please check system tunables.\n",
165 p->id, global.maxsock);
166 ret = CO_AC_PAUSE;
167 break;
168
169 default:
170 /* unexpected result, let's give up and let other tasks run */
171 ret = CO_AC_YIELD;
172 }
173 done:
174 if (status)
175 *status = ret;
176 return conn;
177
Willy Tarreauf1dc9f22020-10-15 09:21:31 +0200178 fail_conn:
Willy Tarreau344b8fc2020-10-15 09:43:31 +0200179 sockaddr_free(&addr);
Remi Tricot-Le Breton25dd0ad2021-01-14 15:26:24 +0100180 /* The accept call already succeeded by the time we try to allocate the connection,
181 * we need to close it in case of failure. */
182 close(cfd);
Willy Tarreau344b8fc2020-10-15 09:43:31 +0200183 fail_addr:
Willy Tarreauf1dc9f22020-10-15 09:21:31 +0200184 ret = CO_AC_PAUSE;
185 goto done;
186}
187
Willy Tarreau18b7df72020-08-28 12:07:22 +0200188/* Create a socket to connect to the server in conn->dst (which MUST be valid),
189 * using the configured namespace if needed, or the one passed by the proxy
190 * protocol if required to do so. It ultimately calls socket() or socketat()
191 * and returns the FD or error code.
192 */
193int sock_create_server_socket(struct connection *conn)
194{
195 const struct netns_entry *ns = NULL;
196
197#ifdef USE_NS
198 if (objt_server(conn->target)) {
199 if (__objt_server(conn->target)->flags & SRV_F_USE_NS_FROM_PP)
200 ns = conn->proxy_netns;
201 else
202 ns = __objt_server(conn->target)->netns;
203 }
204#endif
205 return my_socketat(ns, conn->dst->ss_family, SOCK_STREAM, 0);
206}
207
Willy Tarreaua4380b22020-11-04 13:59:04 +0100208/* Enables receiving on receiver <rx> once already bound. */
Willy Tarreaue70c7972020-09-25 19:00:01 +0200209void sock_enable(struct receiver *rx)
210{
Willy Tarreaua4380b22020-11-04 13:59:04 +0100211 if (rx->flags & RX_F_BOUND)
212 fd_want_recv_safe(rx->fd);
Willy Tarreaue70c7972020-09-25 19:00:01 +0200213}
214
Willy Tarreaua4380b22020-11-04 13:59:04 +0100215/* Disables receiving on receiver <rx> once already bound. */
Willy Tarreaue70c7972020-09-25 19:00:01 +0200216void sock_disable(struct receiver *rx)
217{
Willy Tarreaua4380b22020-11-04 13:59:04 +0100218 if (rx->flags & RX_F_BOUND)
Willy Tarreaue70c7972020-09-25 19:00:01 +0200219 fd_stop_recv(rx->fd);
220}
221
Willy Tarreauf58b8db2020-10-09 16:32:08 +0200222/* stops, unbinds and possibly closes the FD associated with receiver rx */
223void sock_unbind(struct receiver *rx)
224{
225 /* There are a number of situations where we prefer to keep the FD and
226 * not to close it (unless we're stopping, of course):
227 * - worker process unbinding from a worker's FD with socket transfer enabled => keep
228 * - master process unbinding from a master's inherited FD => keep
229 * - master process unbinding from a master's FD => close
Willy Tarreau22ccd5e2020-11-03 18:38:05 +0100230 * - master process unbinding from a worker's inherited FD => keep
Willy Tarreauf58b8db2020-10-09 16:32:08 +0200231 * - master process unbinding from a worker's FD => close
232 * - worker process unbinding from a master's FD => close
233 * - worker process unbinding from a worker's FD => close
234 */
235 if (rx->flags & RX_F_BOUND)
236 rx->proto->rx_disable(rx);
237
238 if (!stopping && !master &&
239 !(rx->flags & RX_F_MWORKER) &&
240 (global.tune.options & GTUNE_SOCKET_TRANSFER))
241 return;
242
243 if (!stopping && master &&
Willy Tarreauf58b8db2020-10-09 16:32:08 +0200244 rx->flags & RX_F_INHERITED)
245 return;
246
247 rx->flags &= ~RX_F_BOUND;
248 if (rx->fd != -1)
249 fd_delete(rx->fd);
250 rx->fd = -1;
251}
252
Willy Tarreau18b7df72020-08-28 12:07:22 +0200253/*
254 * Retrieves the source address for the socket <fd>, with <dir> indicating
255 * if we're a listener (=0) or an initiator (!=0). It returns 0 in case of
256 * success, -1 in case of error. The socket's source address is stored in
257 * <sa> for <salen> bytes.
258 */
259int sock_get_src(int fd, struct sockaddr *sa, socklen_t salen, int dir)
260{
261 if (dir)
262 return getsockname(fd, sa, &salen);
263 else
264 return getpeername(fd, sa, &salen);
265}
266
267/*
268 * Retrieves the original destination address for the socket <fd>, with <dir>
269 * indicating if we're a listener (=0) or an initiator (!=0). It returns 0 in
270 * case of success, -1 in case of error. The socket's source address is stored
271 * in <sa> for <salen> bytes.
272 */
273int sock_get_dst(int fd, struct sockaddr *sa, socklen_t salen, int dir)
274{
275 if (dir)
276 return getpeername(fd, sa, &salen);
277 else
278 return getsockname(fd, sa, &salen);
279}
280
Willy Tarreau42961742020-08-28 18:42:45 +0200281/* Try to retrieve exported sockets from worker at CLI <unixsocket>. These
282 * ones will be placed into the xfer_sock_list for later use by function
283 * sock_find_compatible_fd(). Returns 0 on success, -1 on failure.
284 */
285int sock_get_old_sockets(const char *unixsocket)
286{
287 char *cmsgbuf = NULL, *tmpbuf = NULL;
288 int *tmpfd = NULL;
289 struct sockaddr_un addr;
290 struct cmsghdr *cmsg;
291 struct msghdr msghdr;
292 struct iovec iov;
293 struct xfer_sock_list *xfer_sock = NULL;
294 struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
295 int sock = -1;
296 int ret = -1;
297 int ret2 = -1;
298 int fd_nb;
299 int got_fd = 0;
300 int cur_fd = 0;
301 size_t maxoff = 0, curoff = 0;
302
303 memset(&msghdr, 0, sizeof(msghdr));
304 cmsgbuf = malloc(CMSG_SPACE(sizeof(int)) * MAX_SEND_FD);
305 if (!cmsgbuf) {
306 ha_warning("Failed to allocate memory to send sockets\n");
307 goto out;
308 }
309
310 sock = socket(PF_UNIX, SOCK_STREAM, 0);
311 if (sock < 0) {
312 ha_warning("Failed to connect to the old process socket '%s'\n", unixsocket);
313 goto out;
314 }
315
316 strncpy(addr.sun_path, unixsocket, sizeof(addr.sun_path) - 1);
317 addr.sun_path[sizeof(addr.sun_path) - 1] = 0;
318 addr.sun_family = PF_UNIX;
319
320 ret = connect(sock, (struct sockaddr *)&addr, sizeof(addr));
321 if (ret < 0) {
322 ha_warning("Failed to connect to the old process socket '%s'\n", unixsocket);
323 goto out;
324 }
325
326 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (void *)&tv, sizeof(tv));
327 iov.iov_base = &fd_nb;
328 iov.iov_len = sizeof(fd_nb);
329 msghdr.msg_iov = &iov;
330 msghdr.msg_iovlen = 1;
331
332 if (send(sock, "_getsocks\n", strlen("_getsocks\n"), 0) != strlen("_getsocks\n")) {
333 ha_warning("Failed to get the number of sockets to be transferred !\n");
334 goto out;
335 }
336
337 /* First, get the number of file descriptors to be received */
338 if (recvmsg(sock, &msghdr, MSG_WAITALL) != sizeof(fd_nb)) {
339 ha_warning("Failed to get the number of sockets to be transferred !\n");
340 goto out;
341 }
342
343 if (fd_nb == 0) {
344 ret2 = 0;
345 goto out;
346 }
347
348 tmpbuf = malloc(fd_nb * (1 + MAXPATHLEN + 1 + IFNAMSIZ + sizeof(int)));
349 if (tmpbuf == NULL) {
350 ha_warning("Failed to allocate memory while receiving sockets\n");
351 goto out;
352 }
353
354 tmpfd = malloc(fd_nb * sizeof(int));
355 if (tmpfd == NULL) {
356 ha_warning("Failed to allocate memory while receiving sockets\n");
357 goto out;
358 }
359
360 msghdr.msg_control = cmsgbuf;
361 msghdr.msg_controllen = CMSG_SPACE(sizeof(int)) * MAX_SEND_FD;
362 iov.iov_len = MAX_SEND_FD * (1 + MAXPATHLEN + 1 + IFNAMSIZ + sizeof(int));
363
364 do {
365 int ret3;
366
367 iov.iov_base = tmpbuf + curoff;
368
369 ret = recvmsg(sock, &msghdr, 0);
370
371 if (ret == -1 && errno == EINTR)
372 continue;
373
374 if (ret <= 0)
375 break;
376
377 /* Send an ack to let the sender know we got the sockets
378 * and it can send some more
379 */
380 do {
381 ret3 = send(sock, &got_fd, sizeof(got_fd), 0);
382 } while (ret3 == -1 && errno == EINTR);
383
384 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg != NULL; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
385 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
386 size_t totlen = cmsg->cmsg_len - CMSG_LEN(0);
387
388 if (totlen / sizeof(int) + got_fd > fd_nb) {
389 ha_warning("Got to many sockets !\n");
390 goto out;
391 }
392
393 /*
394 * Be paranoid and use memcpy() to avoid any
395 * potential alignment issue.
396 */
397 memcpy(&tmpfd[got_fd], CMSG_DATA(cmsg), totlen);
398 got_fd += totlen / sizeof(int);
399 }
400 }
401 curoff += ret;
402 } while (got_fd < fd_nb);
403
404 if (got_fd != fd_nb) {
405 ha_warning("We didn't get the expected number of sockets (expecting %d got %d)\n",
406 fd_nb, got_fd);
407 goto out;
408 }
409
410 maxoff = curoff;
411 curoff = 0;
412
413 for (cur_fd = 0; cur_fd < got_fd; cur_fd++) {
414 int fd = tmpfd[cur_fd];
415 socklen_t socklen;
416 int val;
417 int len;
418
419 xfer_sock = calloc(1, sizeof(*xfer_sock));
420 if (!xfer_sock) {
421 ha_warning("Failed to allocate memory in get_old_sockets() !\n");
422 break;
423 }
424 xfer_sock->fd = -1;
425
426 socklen = sizeof(xfer_sock->addr);
427 if (getsockname(fd, (struct sockaddr *)&xfer_sock->addr, &socklen) != 0) {
428 ha_warning("Failed to get socket address\n");
Willy Tarreau61cfdf42021-02-20 10:46:51 +0100429 ha_free(&xfer_sock);
Willy Tarreau42961742020-08-28 18:42:45 +0200430 continue;
431 }
432
433 if (curoff >= maxoff) {
434 ha_warning("Inconsistency while transferring sockets\n");
435 goto out;
436 }
437
438 len = tmpbuf[curoff++];
439 if (len > 0) {
440 /* We have a namespace */
441 if (curoff + len > maxoff) {
442 ha_warning("Inconsistency while transferring sockets\n");
443 goto out;
444 }
445 xfer_sock->namespace = malloc(len + 1);
446 if (!xfer_sock->namespace) {
447 ha_warning("Failed to allocate memory while transferring sockets\n");
448 goto out;
449 }
450 memcpy(xfer_sock->namespace, &tmpbuf[curoff], len);
451 xfer_sock->namespace[len] = 0;
452 xfer_sock->ns_namelen = len;
453 curoff += len;
454 }
455
456 if (curoff >= maxoff) {
457 ha_warning("Inconsistency while transferring sockets\n");
458 goto out;
459 }
460
461 len = tmpbuf[curoff++];
462 if (len > 0) {
463 /* We have an interface */
464 if (curoff + len > maxoff) {
465 ha_warning("Inconsistency while transferring sockets\n");
466 goto out;
467 }
468 xfer_sock->iface = malloc(len + 1);
469 if (!xfer_sock->iface) {
470 ha_warning("Failed to allocate memory while transferring sockets\n");
471 goto out;
472 }
473 memcpy(xfer_sock->iface, &tmpbuf[curoff], len);
474 xfer_sock->iface[len] = 0;
475 xfer_sock->if_namelen = len;
476 curoff += len;
477 }
478
479 if (curoff + sizeof(int) > maxoff) {
480 ha_warning("Inconsistency while transferring sockets\n");
481 goto out;
482 }
483
484 /* we used to have 32 bits of listener options here but we don't
485 * use them anymore.
486 */
487 curoff += sizeof(int);
488
489 /* determine the foreign status directly from the socket itself */
490 if (sock_inet_is_foreign(fd, xfer_sock->addr.ss_family))
Willy Tarreaua2c17872020-08-28 19:09:19 +0200491 xfer_sock->options |= SOCK_XFER_OPT_FOREIGN;
Willy Tarreau42961742020-08-28 18:42:45 +0200492
Willy Tarreau9dbb6c42020-08-28 19:20:23 +0200493 socklen = sizeof(val);
494 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &val, &socklen) == 0 && val == SOCK_DGRAM)
495 xfer_sock->options |= SOCK_XFER_OPT_DGRAM;
496
Willy Tarreau42961742020-08-28 18:42:45 +0200497#if defined(IPV6_V6ONLY)
498 /* keep only the v6only flag depending on what's currently
499 * active on the socket, and always drop the v4v6 one.
500 */
501 socklen = sizeof(val);
502 if (xfer_sock->addr.ss_family == AF_INET6 &&
503 getsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &val, &socklen) == 0 && val > 0)
Willy Tarreaua2c17872020-08-28 19:09:19 +0200504 xfer_sock->options |= SOCK_XFER_OPT_V6ONLY;
Willy Tarreau42961742020-08-28 18:42:45 +0200505#endif
506
507 xfer_sock->fd = fd;
508 if (xfer_sock_list)
509 xfer_sock_list->prev = xfer_sock;
510 xfer_sock->next = xfer_sock_list;
511 xfer_sock->prev = NULL;
512 xfer_sock_list = xfer_sock;
513 xfer_sock = NULL;
514 }
515
516 ret2 = 0;
517out:
518 /* If we failed midway make sure to close the remaining
519 * file descriptors
520 */
521 if (tmpfd != NULL && cur_fd < got_fd) {
522 for (; cur_fd < got_fd; cur_fd++) {
523 close(tmpfd[cur_fd]);
524 }
525 }
526
527 free(tmpbuf);
528 free(tmpfd);
529 free(cmsgbuf);
530
531 if (sock != -1)
532 close(sock);
533
534 if (xfer_sock) {
535 free(xfer_sock->namespace);
536 free(xfer_sock->iface);
537 if (xfer_sock->fd != -1)
538 close(xfer_sock->fd);
539 free(xfer_sock);
540 }
541 return (ret2);
542}
543
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200544/* When binding the receivers, check if a socket has been sent to us by the
Willy Tarreau2d34a712020-08-28 16:49:41 +0200545 * previous process that we could reuse, instead of creating a new one. Note
546 * that some address family-specific options are checked on the listener and
547 * on the socket. Typically for AF_INET and AF_INET6, we check for transparent
548 * mode, and for AF_INET6 we also check for "v4v6" or "v6only". The reused
549 * socket is automatically removed from the list so that it's not proposed
550 * anymore.
551 */
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200552int sock_find_compatible_fd(const struct receiver *rx)
Willy Tarreau2d34a712020-08-28 16:49:41 +0200553{
554 struct xfer_sock_list *xfer_sock = xfer_sock_list;
Willy Tarreaua2c17872020-08-28 19:09:19 +0200555 int options = 0;
Willy Tarreau2d34a712020-08-28 16:49:41 +0200556 int if_namelen = 0;
557 int ns_namelen = 0;
558 int ret = -1;
559
Willy Tarreauf1f66092020-09-04 08:15:31 +0200560 if (!rx->proto->fam->addrcmp)
Willy Tarreau2d34a712020-08-28 16:49:41 +0200561 return -1;
562
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200563 if (rx->proto->sock_type == SOCK_DGRAM)
Willy Tarreau9dbb6c42020-08-28 19:20:23 +0200564 options |= SOCK_XFER_OPT_DGRAM;
565
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200566 if (rx->settings->options & RX_O_FOREIGN)
Willy Tarreaua2c17872020-08-28 19:09:19 +0200567 options |= SOCK_XFER_OPT_FOREIGN;
568
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200569 if (rx->addr.ss_family == AF_INET6) {
Willy Tarreau2d34a712020-08-28 16:49:41 +0200570 /* Prepare to match the v6only option against what we really want. Note
571 * that sadly the two options are not exclusive to each other and that
572 * v6only is stronger than v4v6.
573 */
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200574 if ((rx->settings->options & RX_O_V6ONLY) ||
575 (sock_inet6_v6only_default && !(rx->settings->options & RX_O_V4V6)))
Willy Tarreaua2c17872020-08-28 19:09:19 +0200576 options |= SOCK_XFER_OPT_V6ONLY;
Willy Tarreau2d34a712020-08-28 16:49:41 +0200577 }
Willy Tarreau2d34a712020-08-28 16:49:41 +0200578
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200579 if (rx->settings->interface)
580 if_namelen = strlen(rx->settings->interface);
Willy Tarreau2d34a712020-08-28 16:49:41 +0200581#ifdef USE_NS
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200582 if (rx->settings->netns)
583 ns_namelen = rx->settings->netns->name_len;
Willy Tarreau2d34a712020-08-28 16:49:41 +0200584#endif
585
586 while (xfer_sock) {
Willy Tarreaua2c17872020-08-28 19:09:19 +0200587 if ((options == xfer_sock->options) &&
Willy Tarreau2d34a712020-08-28 16:49:41 +0200588 (if_namelen == xfer_sock->if_namelen) &&
589 (ns_namelen == xfer_sock->ns_namelen) &&
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200590 (!if_namelen || strcmp(rx->settings->interface, xfer_sock->iface) == 0) &&
Willy Tarreau2d34a712020-08-28 16:49:41 +0200591#ifdef USE_NS
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200592 (!ns_namelen || strcmp(rx->settings->netns->node.key, xfer_sock->namespace) == 0) &&
Willy Tarreau2d34a712020-08-28 16:49:41 +0200593#endif
Willy Tarreauf1f66092020-09-04 08:15:31 +0200594 rx->proto->fam->addrcmp(&xfer_sock->addr, &rx->addr) == 0)
Willy Tarreau2d34a712020-08-28 16:49:41 +0200595 break;
596 xfer_sock = xfer_sock->next;
597 }
598
599 if (xfer_sock != NULL) {
600 ret = xfer_sock->fd;
601 if (xfer_sock == xfer_sock_list)
602 xfer_sock_list = xfer_sock->next;
603 if (xfer_sock->prev)
604 xfer_sock->prev->next = xfer_sock->next;
605 if (xfer_sock->next)
606 xfer_sock->next->prev = xfer_sock->prev;
607 free(xfer_sock->iface);
608 free(xfer_sock->namespace);
609 free(xfer_sock);
610 }
611 return ret;
612}
613
Willy Tarreau9f775762022-01-28 18:28:18 +0100614/* After all protocols are bound, there may remain some old sockets that have
615 * been removed between the previous config and the new one. These ones must
616 * be dropped, otherwise they will remain open and may prevent a service from
617 * restarting.
618 */
619void sock_drop_unused_old_sockets()
620{
621 while (xfer_sock_list != NULL) {
622 struct xfer_sock_list *tmpxfer = xfer_sock_list->next;
623
624 close(xfer_sock_list->fd);
625 free(xfer_sock_list->iface);
626 free(xfer_sock_list->namespace);
627 free(xfer_sock_list);
628 xfer_sock_list = tmpxfer;
629 }
630}
631
Willy Tarreau5ced3e82020-10-13 17:06:12 +0200632/* Tests if the receiver supports accepting connections. Returns positive on
633 * success, 0 if not possible, negative if the socket is non-recoverable. The
634 * rationale behind this is that inherited FDs may be broken and that shared
635 * FDs might have been paused by another process.
636 */
Willy Tarreau7d053e42020-10-15 09:19:43 +0200637int sock_accepting_conn(const struct receiver *rx)
Willy Tarreau5ced3e82020-10-13 17:06:12 +0200638{
639 int opt_val = 0;
640 socklen_t opt_len = sizeof(opt_val);
641
642 if (getsockopt(rx->fd, SOL_SOCKET, SO_ACCEPTCONN, &opt_val, &opt_len) == -1)
643 return -1;
644
645 return opt_val;
646}
647
Willy Tarreaua74cb382020-10-15 21:29:49 +0200648/* This is the FD handler IO callback for stream sockets configured for
649 * accepting incoming connections. It's a pass-through to listener_accept()
650 * which will iterate over the listener protocol's accept_conn() function.
651 * The FD's owner must be a listener.
652 */
653void sock_accept_iocb(int fd)
654{
655 struct listener *l = fdtab[fd].owner;
656
657 if (!l)
658 return;
659
Willy Tarreaub4daeeb2020-11-04 14:58:36 +0100660 BUG_ON(!!master != !!(l->rx.flags & RX_F_MWORKER));
Willy Tarreaua74cb382020-10-15 21:29:49 +0200661 listener_accept(l);
662}
663
Willy Tarreaude471c42020-12-08 15:50:56 +0100664/* This completes the initialization of connection <conn> by inserting its FD
665 * into the fdtab, associating it with the regular connection handler. It will
666 * be bound to the current thread only. This call cannot fail.
667 */
668void sock_conn_ctrl_init(struct connection *conn)
669{
Willy Tarreau586f71b2020-12-11 15:54:36 +0100670 fd_insert(conn->handle.fd, conn, sock_conn_iocb, tid_bit);
Willy Tarreaude471c42020-12-08 15:50:56 +0100671}
672
673/* This completes the release of connection <conn> by removing its FD from the
674 * fdtab and deleting it. The connection must not use the FD anymore past this
675 * point. The FD may be modified in the connection.
676 */
677void sock_conn_ctrl_close(struct connection *conn)
678{
679 fd_delete(conn->handle.fd);
680 conn->handle.fd = DEAD_FD_MAGIC;
681}
682
Willy Tarreau586f71b2020-12-11 15:54:36 +0100683/* This is the callback which is set when a connection establishment is pending
684 * and we have nothing to send. It may update the FD polling status to indicate
685 * !READY. It returns 0 if it fails in a fatal way or needs to poll to go
686 * further, otherwise it returns non-zero and removes the CO_FL_WAIT_L4_CONN
687 * flag from the connection's flags. In case of error, it sets CO_FL_ERROR and
688 * leaves the error code in errno.
689 */
690int sock_conn_check(struct connection *conn)
691{
692 struct sockaddr_storage *addr;
693 int fd = conn->handle.fd;
694
695 if (conn->flags & CO_FL_ERROR)
696 return 0;
697
698 if (!conn_ctrl_ready(conn))
699 return 0;
700
701 if (!(conn->flags & CO_FL_WAIT_L4_CONN))
702 return 1; /* strange we were called while ready */
703
Willy Tarreau95473382021-07-06 08:29:20 +0200704 if (!fd_send_ready(fd) && !(fdtab[fd].state & (FD_POLL_ERR|FD_POLL_HUP)))
Willy Tarreau586f71b2020-12-11 15:54:36 +0100705 return 0;
706
707 /* Here we have 2 cases :
708 * - modern pollers, able to report ERR/HUP. If these ones return any
709 * of these flags then it's likely a failure, otherwise it possibly
710 * is a success (i.e. there may have been data received just before
711 * the error was reported).
712 * - select, which doesn't report these and with which it's always
713 * necessary either to try connect() again or to check for SO_ERROR.
714 * In order to simplify everything, we double-check using connect() as
715 * soon as we meet either of these delicate situations. Note that
716 * SO_ERROR would clear the error after reporting it!
717 */
718 if (cur_poller.flags & HAP_POLL_F_ERRHUP) {
719 /* modern poller, able to report ERR/HUP */
Willy Tarreauf5090652021-04-06 17:23:40 +0200720 if ((fdtab[fd].state & (FD_POLL_IN|FD_POLL_ERR|FD_POLL_HUP)) == FD_POLL_IN)
Willy Tarreau586f71b2020-12-11 15:54:36 +0100721 goto done;
Willy Tarreauf5090652021-04-06 17:23:40 +0200722 if ((fdtab[fd].state & (FD_POLL_OUT|FD_POLL_ERR|FD_POLL_HUP)) == FD_POLL_OUT)
Willy Tarreau586f71b2020-12-11 15:54:36 +0100723 goto done;
Willy Tarreauf5090652021-04-06 17:23:40 +0200724 if (!(fdtab[fd].state & (FD_POLL_ERR|FD_POLL_HUP)))
Willy Tarreau586f71b2020-12-11 15:54:36 +0100725 goto wait;
726 /* error present, fall through common error check path */
727 }
728
729 /* Use connect() to check the state of the socket. This has the double
730 * advantage of *not* clearing the error (so that health checks can
731 * still use getsockopt(SO_ERROR)) and giving us the following info :
732 * - error
733 * - connecting (EALREADY, EINPROGRESS)
734 * - connected (EISCONN, 0)
735 */
736 addr = conn->dst;
737 if ((conn->flags & CO_FL_SOCKS4) && obj_type(conn->target) == OBJ_TYPE_SERVER)
738 addr = &objt_server(conn->target)->socks4_addr;
739
740 if (connect(fd, (const struct sockaddr *)addr, get_addr_len(addr)) == -1) {
741 if (errno == EALREADY || errno == EINPROGRESS)
742 goto wait;
743
744 if (errno && errno != EISCONN)
745 goto out_error;
746 }
747
748 done:
749 /* The FD is ready now, we'll mark the connection as complete and
750 * forward the event to the transport layer which will notify the
751 * data layer.
752 */
753 conn->flags &= ~CO_FL_WAIT_L4_CONN;
754 fd_may_send(fd);
755 fd_cond_recv(fd);
756 errno = 0; // make health checks happy
757 return 1;
758
759 out_error:
760 /* Write error on the file descriptor. Report it to the connection
761 * and disable polling on this FD.
762 */
Willy Tarreau586f71b2020-12-11 15:54:36 +0100763 conn->flags |= CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH;
Willy Tarreaub41a6e92021-04-06 17:49:19 +0200764 HA_ATOMIC_AND(&fdtab[fd].state, ~FD_LINGER_RISK);
Willy Tarreau586f71b2020-12-11 15:54:36 +0100765 fd_stop_both(fd);
766 return 0;
767
768 wait:
769 fd_cant_send(fd);
770 fd_want_send(fd);
771 return 0;
772}
773
774/* I/O callback for fd-based connections. It calls the read/write handlers
775 * provided by the connection's sock_ops, which must be valid.
776 */
777void sock_conn_iocb(int fd)
778{
779 struct connection *conn = fdtab[fd].owner;
780 unsigned int flags;
781 int need_wake = 0;
782
783 if (unlikely(!conn)) {
784 activity[tid].conn_dead++;
785 return;
786 }
787
788 flags = conn->flags & ~CO_FL_ERROR; /* ensure to call the wake handler upon error */
789
790 if (unlikely(conn->flags & CO_FL_WAIT_L4_CONN) &&
791 ((fd_send_ready(fd) && fd_send_active(fd)) ||
792 (fd_recv_ready(fd) && fd_recv_active(fd)))) {
793 /* Still waiting for a connection to establish and nothing was
794 * attempted yet to probe the connection. this will clear the
795 * CO_FL_WAIT_L4_CONN flag on success.
796 */
797 if (!sock_conn_check(conn))
798 goto leave;
799 need_wake = 1;
800 }
801
802 if (fd_send_ready(fd) && fd_send_active(fd)) {
803 /* force reporting of activity by clearing the previous flags :
804 * we'll have at least ERROR or CONNECTED at the end of an I/O,
805 * both of which will be detected below.
806 */
807 flags = 0;
808 if (conn->subs && conn->subs->events & SUB_RETRY_SEND) {
809 need_wake = 0; // wake will be called after this I/O
810 tasklet_wakeup(conn->subs->tasklet);
811 conn->subs->events &= ~SUB_RETRY_SEND;
812 if (!conn->subs->events)
813 conn->subs = NULL;
814 }
815 fd_stop_send(fd);
816 }
817
818 /* The data transfer starts here and stops on error and handshakes. Note
819 * that we must absolutely test conn->xprt at each step in case it suddenly
820 * changes due to a quick unexpected close().
821 */
822 if (fd_recv_ready(fd) && fd_recv_active(fd)) {
823 /* force reporting of activity by clearing the previous flags :
824 * we'll have at least ERROR or CONNECTED at the end of an I/O,
825 * both of which will be detected below.
826 */
827 flags = 0;
828 if (conn->subs && conn->subs->events & SUB_RETRY_RECV) {
829 need_wake = 0; // wake will be called after this I/O
830 tasklet_wakeup(conn->subs->tasklet);
831 conn->subs->events &= ~SUB_RETRY_RECV;
832 if (!conn->subs->events)
833 conn->subs = NULL;
834 }
835 fd_stop_recv(fd);
836 }
837
838 leave:
839 /* we may have to finish to install a mux or to wake it up based on
840 * what was just done above. It may kill the connection so we have to
841 * be prpared not to use it anymore.
842 */
843 if (conn_notify_mux(conn, flags, need_wake) < 0)
844 return;
845
846 /* commit polling changes in case of error.
847 * WT: it seems that the last case where this could still be relevant
848 * is if a mux wake function above report a connection error but does
849 * not stop polling. Shouldn't we enforce this into the mux instead of
850 * having to deal with this ?
851 */
852 if (unlikely(conn->flags & CO_FL_ERROR)) {
853 if (conn_ctrl_ready(conn))
854 fd_stop_both(fd);
855 }
856}
857
Willy Tarreau427c8462020-12-11 16:19:12 +0100858/* Drains possibly pending incoming data on the file descriptor attached to the
859 * connection. This is used to know whether we need to disable lingering on
860 * close. Returns non-zero if it is safe to close without disabling lingering,
861 * otherwise zero.
862 */
863int sock_drain(struct connection *conn)
864{
865 int turns = 2;
866 int fd = conn->handle.fd;
867 int len;
868
Willy Tarreauf5090652021-04-06 17:23:40 +0200869 if (fdtab[fd].state & (FD_POLL_ERR|FD_POLL_HUP))
Willy Tarreau427c8462020-12-11 16:19:12 +0100870 goto shut;
871
Willy Tarreaub17952c2021-10-21 21:31:42 +0200872 if (!(conn->flags & CO_FL_WANT_DRAIN) && !fd_recv_ready(fd))
Willy Tarreau427c8462020-12-11 16:19:12 +0100873 return 0;
874
875 /* no drain function defined, use the generic one */
876
877 while (turns) {
878#ifdef MSG_TRUNC_CLEARS_INPUT
879 len = recv(fd, NULL, INT_MAX, MSG_DONTWAIT | MSG_NOSIGNAL | MSG_TRUNC);
880 if (len == -1 && errno == EFAULT)
881#endif
882 len = recv(fd, trash.area, trash.size, MSG_DONTWAIT | MSG_NOSIGNAL);
883
884 if (len == 0)
885 goto shut;
886
887 if (len < 0) {
888 if (errno == EAGAIN) {
889 /* connection not closed yet */
890 fd_cant_recv(fd);
891 break;
892 }
893 if (errno == EINTR) /* oops, try again */
894 continue;
895 /* other errors indicate a dead connection, fine. */
896 goto shut;
897 }
898 /* OK we read some data, let's try again once */
899 turns--;
900 }
901
902 /* some data are still present, give up */
903 return 0;
904
905 shut:
906 /* we're certain the connection was shut down */
Willy Tarreaub41a6e92021-04-06 17:49:19 +0200907 HA_ATOMIC_AND(&fdtab[fd].state, ~FD_LINGER_RISK);
Willy Tarreau427c8462020-12-11 16:19:12 +0100908 return 1;
909}
910
Willy Tarreau472125b2020-12-11 17:02:50 +0100911/* Checks the connection's FD for readiness of events <event_type>, which may
912 * only be a combination of SUB_RETRY_RECV and SUB_RETRY_SEND. Those which are
913 * ready are returned. The ones that are not ready are enabled. The caller is
914 * expected to do what is needed to handle ready events and to deal with
915 * subsequent wakeups caused by the requested events' readiness.
916 */
917int sock_check_events(struct connection *conn, int event_type)
918{
919 int ret = 0;
920
921 if (event_type & SUB_RETRY_RECV) {
922 if (fd_recv_ready(conn->handle.fd))
923 ret |= SUB_RETRY_RECV;
924 else
925 fd_want_recv(conn->handle.fd);
926 }
927
928 if (event_type & SUB_RETRY_SEND) {
929 if (fd_send_ready(conn->handle.fd))
930 ret |= SUB_RETRY_SEND;
931 else
932 fd_want_send(conn->handle.fd);
933 }
934
935 return ret;
936}
937
938/* Ignore readiness events from connection's FD for events of types <event_type>
939 * which may only be a combination of SUB_RETRY_RECV and SUB_RETRY_SEND.
940 */
941void sock_ignore_events(struct connection *conn, int event_type)
942{
943 if (event_type & SUB_RETRY_RECV)
944 fd_stop_recv(conn->handle.fd);
945
946 if (event_type & SUB_RETRY_SEND)
947 fd_stop_send(conn->handle.fd);
948}
949
Willy Tarreau18b7df72020-08-28 12:07:22 +0200950/*
951 * Local variables:
952 * c-indent-level: 8
953 * c-basic-offset: 8
954 * End:
955 */