blob: 7ccdbd3baaae7b25d4709d9f76b3562ee7181cef [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>
Willy Tarreau5d9ddc52021-10-06 19:54:09 +020029#include <haproxy/activity.h>
Willy Tarreau18b7df72020-08-28 12:07:22 +020030#include <haproxy/connection.h>
Willy Tarreaua74cb382020-10-15 21:29:49 +020031#include <haproxy/listener.h>
Willy Tarreauf1dc9f22020-10-15 09:21:31 +020032#include <haproxy/log.h>
Willy Tarreau18b7df72020-08-28 12:07:22 +020033#include <haproxy/namespace.h>
William Lallemand2be557f2021-11-24 18:45:37 +010034#include <haproxy/proto_sockpair.h>
Willy Tarreau18b7df72020-08-28 12:07:22 +020035#include <haproxy/sock.h>
Willy Tarreau2d34a712020-08-28 16:49:41 +020036#include <haproxy/sock_inet.h>
Willy Tarreau18b7df72020-08-28 12:07:22 +020037#include <haproxy/tools.h>
38
Willy Tarreaub5101162022-01-28 18:28:18 +010039#define SOCK_XFER_OPT_FOREIGN 0x000000001
40#define SOCK_XFER_OPT_V6ONLY 0x000000002
41#define SOCK_XFER_OPT_DGRAM 0x000000004
42
Willy Tarreau063d47d2020-08-28 16:29:53 +020043/* the list of remaining sockets transferred from an older process */
Willy Tarreaub5101162022-01-28 18:28:18 +010044struct xfer_sock_list {
45 int fd;
46 int options; /* socket options as SOCK_XFER_OPT_* */
47 char *iface;
48 char *namespace;
49 int if_namelen;
50 int ns_namelen;
51 struct xfer_sock_list *prev;
52 struct xfer_sock_list *next;
53 struct sockaddr_storage addr;
54};
55
56static struct xfer_sock_list *xfer_sock_list;
Willy Tarreau18b7df72020-08-28 12:07:22 +020057
Willy Tarreauf1dc9f22020-10-15 09:21:31 +020058
59/* Accept an incoming connection from listener <l>, and return it, as well as
60 * a CO_AC_* status code into <status> if not null. Null is returned on error.
61 * <l> must be a valid listener with a valid frontend.
62 */
63struct connection *sock_accept_conn(struct listener *l, int *status)
64{
65#ifdef USE_ACCEPT4
66 static int accept4_broken;
67#endif
68 struct proxy *p = l->bind_conf->frontend;
Willy Tarreau344b8fc2020-10-15 09:43:31 +020069 struct connection *conn = NULL;
70 struct sockaddr_storage *addr = NULL;
Willy Tarreauf1dc9f22020-10-15 09:21:31 +020071 socklen_t laddr;
72 int ret;
73 int cfd;
74
Willy Tarreau344b8fc2020-10-15 09:43:31 +020075 if (!sockaddr_alloc(&addr, NULL, 0))
Willy Tarreauf1dc9f22020-10-15 09:21:31 +020076 goto fail_addr;
77
78 /* accept() will mark all accepted FDs O_NONBLOCK and the ones accepted
79 * in the master process as FD_CLOEXEC. It's not done for workers
80 * because 1) workers are not supposed to execute anything so there's
81 * no reason for uselessly slowing down everything, and 2) that would
82 * prevent us from implementing fd passing in the future.
83 */
84#ifdef USE_ACCEPT4
85 laddr = sizeof(*conn->src);
86
87 /* only call accept4() if it's known to be safe, otherwise fallback to
88 * the legacy accept() + fcntl().
89 */
90 if (unlikely(accept4_broken) ||
Willy Tarreau344b8fc2020-10-15 09:43:31 +020091 (((cfd = accept4(l->rx.fd, (struct sockaddr*)addr, &laddr,
Willy Tarreauf1dc9f22020-10-15 09:21:31 +020092 SOCK_NONBLOCK | (master ? SOCK_CLOEXEC : 0))) == -1) &&
93 (errno == ENOSYS || errno == EINVAL || errno == EBADF) &&
Tim Duesterhusf897fc92021-11-20 14:39:47 +010094 ((accept4_broken = 1))))
Willy Tarreauf1dc9f22020-10-15 09:21:31 +020095#endif
96 {
97 laddr = sizeof(*conn->src);
Willy Tarreau344b8fc2020-10-15 09:43:31 +020098 if ((cfd = accept(l->rx.fd, (struct sockaddr*)addr, &laddr)) != -1) {
Willy Tarreauf1dc9f22020-10-15 09:21:31 +020099 fcntl(cfd, F_SETFL, O_NONBLOCK);
100 if (master)
101 fcntl(cfd, F_SETFD, FD_CLOEXEC);
102 }
103 }
104
105 if (likely(cfd != -1)) {
Willy Tarreaue4d09ce2022-04-11 15:01:37 +0200106 if (unlikely(cfd >= global.maxsock)) {
Willy Tarreaue4d09ce2022-04-11 15:01:37 +0200107 send_log(p, LOG_EMERG,
108 "Proxy %s reached the configured maximum connection limit. Please check the global 'maxconn' value.\n",
109 p->id);
110 goto fail_conn;
111 }
112
Willy Tarreauf1dc9f22020-10-15 09:21:31 +0200113 /* Perfect, the connection was accepted */
Willy Tarreau344b8fc2020-10-15 09:43:31 +0200114 conn = conn_new(&l->obj_type);
115 if (!conn)
116 goto fail_conn;
117
118 conn->src = addr;
Willy Tarreauf1dc9f22020-10-15 09:21:31 +0200119 conn->handle.fd = cfd;
120 conn->flags |= CO_FL_ADDR_FROM_SET;
121 ret = CO_AC_DONE;
122 goto done;
123 }
124
125 /* error conditions below */
Willy Tarreau344b8fc2020-10-15 09:43:31 +0200126 sockaddr_free(&addr);
Willy Tarreauf1dc9f22020-10-15 09:21:31 +0200127
128 switch (errno) {
129 case EAGAIN:
130 ret = CO_AC_DONE; /* nothing more to accept */
Willy Tarreauf5090652021-04-06 17:23:40 +0200131 if (fdtab[l->rx.fd].state & (FD_POLL_HUP|FD_POLL_ERR)) {
Willy Tarreauf1dc9f22020-10-15 09:21:31 +0200132 /* the listening socket might have been disabled in a shared
133 * process and we're a collateral victim. We'll just pause for
134 * a while in case it comes back. In the mean time, we need to
135 * clear this sticky flag.
136 */
Willy Tarreauf5090652021-04-06 17:23:40 +0200137 _HA_ATOMIC_AND(&fdtab[l->rx.fd].state, ~(FD_POLL_HUP|FD_POLL_ERR));
Willy Tarreauf1dc9f22020-10-15 09:21:31 +0200138 ret = CO_AC_PAUSE;
139 }
140 fd_cant_recv(l->rx.fd);
141 break;
142
143 case EINVAL:
144 /* might be trying to accept on a shut fd (eg: soft stop) */
145 ret = CO_AC_PAUSE;
146 break;
147
148 case EINTR:
149 case ECONNABORTED:
150 ret = CO_AC_RETRY;
151 break;
152
153 case ENFILE:
154 if (p)
155 send_log(p, LOG_EMERG,
156 "Proxy %s reached system FD limit (maxsock=%d). Please check system tunables.\n",
157 p->id, global.maxsock);
158 ret = CO_AC_PAUSE;
159 break;
160
161 case EMFILE:
162 if (p)
163 send_log(p, LOG_EMERG,
164 "Proxy %s reached process FD limit (maxsock=%d). Please check 'ulimit-n' and restart.\n",
165 p->id, global.maxsock);
166 ret = CO_AC_PAUSE;
167 break;
168
169 case ENOBUFS:
170 case ENOMEM:
171 if (p)
172 send_log(p, LOG_EMERG,
173 "Proxy %s reached system memory limit (maxsock=%d). Please check system tunables.\n",
174 p->id, global.maxsock);
175 ret = CO_AC_PAUSE;
176 break;
177
178 default:
179 /* unexpected result, let's give up and let other tasks run */
180 ret = CO_AC_YIELD;
181 }
182 done:
183 if (status)
184 *status = ret;
185 return conn;
186
Willy Tarreauf1dc9f22020-10-15 09:21:31 +0200187 fail_conn:
Willy Tarreau344b8fc2020-10-15 09:43:31 +0200188 sockaddr_free(&addr);
Remi Tricot-Le Breton25dd0ad2021-01-14 15:26:24 +0100189 /* The accept call already succeeded by the time we try to allocate the connection,
190 * we need to close it in case of failure. */
191 close(cfd);
Willy Tarreau344b8fc2020-10-15 09:43:31 +0200192 fail_addr:
Willy Tarreauf1dc9f22020-10-15 09:21:31 +0200193 ret = CO_AC_PAUSE;
194 goto done;
195}
196
Willy Tarreau18b7df72020-08-28 12:07:22 +0200197/* Create a socket to connect to the server in conn->dst (which MUST be valid),
198 * using the configured namespace if needed, or the one passed by the proxy
199 * protocol if required to do so. It ultimately calls socket() or socketat()
200 * and returns the FD or error code.
201 */
202int sock_create_server_socket(struct connection *conn)
203{
204 const struct netns_entry *ns = NULL;
205
206#ifdef USE_NS
207 if (objt_server(conn->target)) {
208 if (__objt_server(conn->target)->flags & SRV_F_USE_NS_FROM_PP)
209 ns = conn->proxy_netns;
210 else
211 ns = __objt_server(conn->target)->netns;
212 }
213#endif
214 return my_socketat(ns, conn->dst->ss_family, SOCK_STREAM, 0);
215}
216
Willy Tarreaua4380b22020-11-04 13:59:04 +0100217/* Enables receiving on receiver <rx> once already bound. */
Willy Tarreaue70c7972020-09-25 19:00:01 +0200218void sock_enable(struct receiver *rx)
219{
Willy Tarreaua4380b22020-11-04 13:59:04 +0100220 if (rx->flags & RX_F_BOUND)
221 fd_want_recv_safe(rx->fd);
Willy Tarreaue70c7972020-09-25 19:00:01 +0200222}
223
Willy Tarreaua4380b22020-11-04 13:59:04 +0100224/* Disables receiving on receiver <rx> once already bound. */
Willy Tarreaue70c7972020-09-25 19:00:01 +0200225void sock_disable(struct receiver *rx)
226{
Willy Tarreaua4380b22020-11-04 13:59:04 +0100227 if (rx->flags & RX_F_BOUND)
Willy Tarreaue70c7972020-09-25 19:00:01 +0200228 fd_stop_recv(rx->fd);
229}
230
Willy Tarreauf58b8db2020-10-09 16:32:08 +0200231/* stops, unbinds and possibly closes the FD associated with receiver rx */
232void sock_unbind(struct receiver *rx)
233{
234 /* There are a number of situations where we prefer to keep the FD and
235 * not to close it (unless we're stopping, of course):
236 * - worker process unbinding from a worker's FD with socket transfer enabled => keep
237 * - master process unbinding from a master's inherited FD => keep
238 * - master process unbinding from a master's FD => close
Willy Tarreau22ccd5e2020-11-03 18:38:05 +0100239 * - master process unbinding from a worker's inherited FD => keep
Willy Tarreauf58b8db2020-10-09 16:32:08 +0200240 * - master process unbinding from a worker's FD => close
241 * - worker process unbinding from a master's FD => close
242 * - worker process unbinding from a worker's FD => close
243 */
244 if (rx->flags & RX_F_BOUND)
245 rx->proto->rx_disable(rx);
246
247 if (!stopping && !master &&
248 !(rx->flags & RX_F_MWORKER) &&
249 (global.tune.options & GTUNE_SOCKET_TRANSFER))
250 return;
251
252 if (!stopping && master &&
Willy Tarreauf58b8db2020-10-09 16:32:08 +0200253 rx->flags & RX_F_INHERITED)
254 return;
255
256 rx->flags &= ~RX_F_BOUND;
257 if (rx->fd != -1)
258 fd_delete(rx->fd);
259 rx->fd = -1;
260}
261
Willy Tarreau18b7df72020-08-28 12:07:22 +0200262/*
263 * Retrieves the source address for the socket <fd>, with <dir> indicating
264 * if we're a listener (=0) or an initiator (!=0). It returns 0 in case of
265 * success, -1 in case of error. The socket's source address is stored in
266 * <sa> for <salen> bytes.
267 */
268int sock_get_src(int fd, struct sockaddr *sa, socklen_t salen, int dir)
269{
270 if (dir)
271 return getsockname(fd, sa, &salen);
272 else
273 return getpeername(fd, sa, &salen);
274}
275
276/*
277 * Retrieves the original destination address for the socket <fd>, with <dir>
278 * indicating if we're a listener (=0) or an initiator (!=0). It returns 0 in
279 * case of success, -1 in case of error. The socket's source address is stored
280 * in <sa> for <salen> bytes.
281 */
282int sock_get_dst(int fd, struct sockaddr *sa, socklen_t salen, int dir)
283{
284 if (dir)
285 return getpeername(fd, sa, &salen);
286 else
287 return getsockname(fd, sa, &salen);
288}
289
Willy Tarreau42961742020-08-28 18:42:45 +0200290/* Try to retrieve exported sockets from worker at CLI <unixsocket>. These
291 * ones will be placed into the xfer_sock_list for later use by function
292 * sock_find_compatible_fd(). Returns 0 on success, -1 on failure.
293 */
294int sock_get_old_sockets(const char *unixsocket)
295{
296 char *cmsgbuf = NULL, *tmpbuf = NULL;
297 int *tmpfd = NULL;
298 struct sockaddr_un addr;
299 struct cmsghdr *cmsg;
300 struct msghdr msghdr;
301 struct iovec iov;
302 struct xfer_sock_list *xfer_sock = NULL;
303 struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
304 int sock = -1;
305 int ret = -1;
306 int ret2 = -1;
307 int fd_nb;
308 int got_fd = 0;
309 int cur_fd = 0;
310 size_t maxoff = 0, curoff = 0;
311
William Lallemand2be557f2021-11-24 18:45:37 +0100312 if (strncmp("sockpair@", unixsocket, strlen("sockpair@")) == 0) {
313 /* sockpair for master-worker usage */
314 int sv[2];
315 int dst_fd;
316
317 dst_fd = strtoll(unixsocket + strlen("sockpair@"), NULL, 0);
318
319 if (socketpair(PF_UNIX, SOCK_STREAM, 0, sv) == -1) {
320 ha_warning("socketpair(): Cannot create socketpair. Giving up.\n");
321 }
322
323 if (send_fd_uxst(dst_fd, sv[0]) == -1) {
324 ha_alert("socketpair: cannot transfer socket.\n");
325 close(sv[0]);
326 close(sv[1]);
327 goto out;
328 }
329
330 close(sv[0]); /* we don't need this side anymore */
331 sock = sv[1];
332
333 } else {
334 /* Unix socket */
335
336 sock = socket(PF_UNIX, SOCK_STREAM, 0);
337 if (sock < 0) {
338 ha_warning("Failed to connect to the old process socket '%s'\n", unixsocket);
339 goto out;
340 }
341
342 strncpy(addr.sun_path, unixsocket, sizeof(addr.sun_path) - 1);
343 addr.sun_path[sizeof(addr.sun_path) - 1] = 0;
344 addr.sun_family = PF_UNIX;
345
346 ret = connect(sock, (struct sockaddr *)&addr, sizeof(addr));
347 if (ret < 0) {
348 ha_warning("Failed to connect to the old process socket '%s'\n", unixsocket);
349 goto out;
350 }
351
352 }
Willy Tarreau42961742020-08-28 18:42:45 +0200353 memset(&msghdr, 0, sizeof(msghdr));
354 cmsgbuf = malloc(CMSG_SPACE(sizeof(int)) * MAX_SEND_FD);
355 if (!cmsgbuf) {
356 ha_warning("Failed to allocate memory to send sockets\n");
357 goto out;
358 }
359
Willy Tarreau42961742020-08-28 18:42:45 +0200360 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (void *)&tv, sizeof(tv));
361 iov.iov_base = &fd_nb;
362 iov.iov_len = sizeof(fd_nb);
363 msghdr.msg_iov = &iov;
364 msghdr.msg_iovlen = 1;
365
366 if (send(sock, "_getsocks\n", strlen("_getsocks\n"), 0) != strlen("_getsocks\n")) {
367 ha_warning("Failed to get the number of sockets to be transferred !\n");
368 goto out;
369 }
370
371 /* First, get the number of file descriptors to be received */
372 if (recvmsg(sock, &msghdr, MSG_WAITALL) != sizeof(fd_nb)) {
373 ha_warning("Failed to get the number of sockets to be transferred !\n");
374 goto out;
375 }
376
377 if (fd_nb == 0) {
378 ret2 = 0;
379 goto out;
380 }
381
382 tmpbuf = malloc(fd_nb * (1 + MAXPATHLEN + 1 + IFNAMSIZ + sizeof(int)));
383 if (tmpbuf == NULL) {
384 ha_warning("Failed to allocate memory while receiving sockets\n");
385 goto out;
386 }
387
388 tmpfd = malloc(fd_nb * sizeof(int));
389 if (tmpfd == NULL) {
390 ha_warning("Failed to allocate memory while receiving sockets\n");
391 goto out;
392 }
393
394 msghdr.msg_control = cmsgbuf;
395 msghdr.msg_controllen = CMSG_SPACE(sizeof(int)) * MAX_SEND_FD;
396 iov.iov_len = MAX_SEND_FD * (1 + MAXPATHLEN + 1 + IFNAMSIZ + sizeof(int));
397
398 do {
399 int ret3;
400
401 iov.iov_base = tmpbuf + curoff;
402
403 ret = recvmsg(sock, &msghdr, 0);
404
405 if (ret == -1 && errno == EINTR)
406 continue;
407
408 if (ret <= 0)
409 break;
410
411 /* Send an ack to let the sender know we got the sockets
412 * and it can send some more
413 */
414 do {
415 ret3 = send(sock, &got_fd, sizeof(got_fd), 0);
416 } while (ret3 == -1 && errno == EINTR);
417
418 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg != NULL; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
419 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
420 size_t totlen = cmsg->cmsg_len - CMSG_LEN(0);
421
422 if (totlen / sizeof(int) + got_fd > fd_nb) {
423 ha_warning("Got to many sockets !\n");
424 goto out;
425 }
426
427 /*
428 * Be paranoid and use memcpy() to avoid any
429 * potential alignment issue.
430 */
431 memcpy(&tmpfd[got_fd], CMSG_DATA(cmsg), totlen);
432 got_fd += totlen / sizeof(int);
433 }
434 }
435 curoff += ret;
436 } while (got_fd < fd_nb);
437
438 if (got_fd != fd_nb) {
439 ha_warning("We didn't get the expected number of sockets (expecting %d got %d)\n",
440 fd_nb, got_fd);
441 goto out;
442 }
443
444 maxoff = curoff;
445 curoff = 0;
446
447 for (cur_fd = 0; cur_fd < got_fd; cur_fd++) {
448 int fd = tmpfd[cur_fd];
449 socklen_t socklen;
450 int val;
451 int len;
452
453 xfer_sock = calloc(1, sizeof(*xfer_sock));
454 if (!xfer_sock) {
455 ha_warning("Failed to allocate memory in get_old_sockets() !\n");
456 break;
457 }
458 xfer_sock->fd = -1;
459
460 socklen = sizeof(xfer_sock->addr);
461 if (getsockname(fd, (struct sockaddr *)&xfer_sock->addr, &socklen) != 0) {
462 ha_warning("Failed to get socket address\n");
Willy Tarreau61cfdf42021-02-20 10:46:51 +0100463 ha_free(&xfer_sock);
Willy Tarreau42961742020-08-28 18:42:45 +0200464 continue;
465 }
466
467 if (curoff >= maxoff) {
468 ha_warning("Inconsistency while transferring sockets\n");
469 goto out;
470 }
471
472 len = tmpbuf[curoff++];
473 if (len > 0) {
474 /* We have a namespace */
475 if (curoff + len > maxoff) {
476 ha_warning("Inconsistency while transferring sockets\n");
477 goto out;
478 }
479 xfer_sock->namespace = malloc(len + 1);
480 if (!xfer_sock->namespace) {
481 ha_warning("Failed to allocate memory while transferring sockets\n");
482 goto out;
483 }
484 memcpy(xfer_sock->namespace, &tmpbuf[curoff], len);
485 xfer_sock->namespace[len] = 0;
486 xfer_sock->ns_namelen = len;
487 curoff += len;
488 }
489
490 if (curoff >= maxoff) {
491 ha_warning("Inconsistency while transferring sockets\n");
492 goto out;
493 }
494
495 len = tmpbuf[curoff++];
496 if (len > 0) {
497 /* We have an interface */
498 if (curoff + len > maxoff) {
499 ha_warning("Inconsistency while transferring sockets\n");
500 goto out;
501 }
502 xfer_sock->iface = malloc(len + 1);
503 if (!xfer_sock->iface) {
504 ha_warning("Failed to allocate memory while transferring sockets\n");
505 goto out;
506 }
507 memcpy(xfer_sock->iface, &tmpbuf[curoff], len);
508 xfer_sock->iface[len] = 0;
509 xfer_sock->if_namelen = len;
510 curoff += len;
511 }
512
513 if (curoff + sizeof(int) > maxoff) {
514 ha_warning("Inconsistency while transferring sockets\n");
515 goto out;
516 }
517
518 /* we used to have 32 bits of listener options here but we don't
519 * use them anymore.
520 */
521 curoff += sizeof(int);
522
523 /* determine the foreign status directly from the socket itself */
524 if (sock_inet_is_foreign(fd, xfer_sock->addr.ss_family))
Willy Tarreaua2c17872020-08-28 19:09:19 +0200525 xfer_sock->options |= SOCK_XFER_OPT_FOREIGN;
Willy Tarreau42961742020-08-28 18:42:45 +0200526
Willy Tarreau9dbb6c42020-08-28 19:20:23 +0200527 socklen = sizeof(val);
528 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &val, &socklen) == 0 && val == SOCK_DGRAM)
529 xfer_sock->options |= SOCK_XFER_OPT_DGRAM;
530
Willy Tarreau42961742020-08-28 18:42:45 +0200531#if defined(IPV6_V6ONLY)
532 /* keep only the v6only flag depending on what's currently
533 * active on the socket, and always drop the v4v6 one.
534 */
535 socklen = sizeof(val);
536 if (xfer_sock->addr.ss_family == AF_INET6 &&
537 getsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &val, &socklen) == 0 && val > 0)
Willy Tarreaua2c17872020-08-28 19:09:19 +0200538 xfer_sock->options |= SOCK_XFER_OPT_V6ONLY;
Willy Tarreau42961742020-08-28 18:42:45 +0200539#endif
540
541 xfer_sock->fd = fd;
542 if (xfer_sock_list)
543 xfer_sock_list->prev = xfer_sock;
544 xfer_sock->next = xfer_sock_list;
545 xfer_sock->prev = NULL;
546 xfer_sock_list = xfer_sock;
547 xfer_sock = NULL;
548 }
549
550 ret2 = 0;
551out:
552 /* If we failed midway make sure to close the remaining
553 * file descriptors
554 */
555 if (tmpfd != NULL && cur_fd < got_fd) {
556 for (; cur_fd < got_fd; cur_fd++) {
557 close(tmpfd[cur_fd]);
558 }
559 }
560
561 free(tmpbuf);
562 free(tmpfd);
563 free(cmsgbuf);
564
565 if (sock != -1)
566 close(sock);
567
568 if (xfer_sock) {
569 free(xfer_sock->namespace);
570 free(xfer_sock->iface);
571 if (xfer_sock->fd != -1)
572 close(xfer_sock->fd);
573 free(xfer_sock);
574 }
575 return (ret2);
576}
577
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200578/* When binding the receivers, check if a socket has been sent to us by the
Willy Tarreau2d34a712020-08-28 16:49:41 +0200579 * previous process that we could reuse, instead of creating a new one. Note
580 * that some address family-specific options are checked on the listener and
581 * on the socket. Typically for AF_INET and AF_INET6, we check for transparent
582 * mode, and for AF_INET6 we also check for "v4v6" or "v6only". The reused
583 * socket is automatically removed from the list so that it's not proposed
584 * anymore.
585 */
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200586int sock_find_compatible_fd(const struct receiver *rx)
Willy Tarreau2d34a712020-08-28 16:49:41 +0200587{
588 struct xfer_sock_list *xfer_sock = xfer_sock_list;
Willy Tarreaua2c17872020-08-28 19:09:19 +0200589 int options = 0;
Willy Tarreau2d34a712020-08-28 16:49:41 +0200590 int if_namelen = 0;
591 int ns_namelen = 0;
592 int ret = -1;
593
Willy Tarreauf1f66092020-09-04 08:15:31 +0200594 if (!rx->proto->fam->addrcmp)
Willy Tarreau2d34a712020-08-28 16:49:41 +0200595 return -1;
596
Willy Tarreaue3b45182021-10-27 17:28:55 +0200597 if (rx->proto->proto_type == PROTO_TYPE_DGRAM)
Willy Tarreau9dbb6c42020-08-28 19:20:23 +0200598 options |= SOCK_XFER_OPT_DGRAM;
599
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200600 if (rx->settings->options & RX_O_FOREIGN)
Willy Tarreaua2c17872020-08-28 19:09:19 +0200601 options |= SOCK_XFER_OPT_FOREIGN;
602
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200603 if (rx->addr.ss_family == AF_INET6) {
Willy Tarreau2d34a712020-08-28 16:49:41 +0200604 /* Prepare to match the v6only option against what we really want. Note
605 * that sadly the two options are not exclusive to each other and that
606 * v6only is stronger than v4v6.
607 */
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200608 if ((rx->settings->options & RX_O_V6ONLY) ||
609 (sock_inet6_v6only_default && !(rx->settings->options & RX_O_V4V6)))
Willy Tarreaua2c17872020-08-28 19:09:19 +0200610 options |= SOCK_XFER_OPT_V6ONLY;
Willy Tarreau2d34a712020-08-28 16:49:41 +0200611 }
Willy Tarreau2d34a712020-08-28 16:49:41 +0200612
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200613 if (rx->settings->interface)
614 if_namelen = strlen(rx->settings->interface);
Willy Tarreau2d34a712020-08-28 16:49:41 +0200615#ifdef USE_NS
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200616 if (rx->settings->netns)
617 ns_namelen = rx->settings->netns->name_len;
Willy Tarreau2d34a712020-08-28 16:49:41 +0200618#endif
619
620 while (xfer_sock) {
Willy Tarreaua2c17872020-08-28 19:09:19 +0200621 if ((options == xfer_sock->options) &&
Willy Tarreau2d34a712020-08-28 16:49:41 +0200622 (if_namelen == xfer_sock->if_namelen) &&
623 (ns_namelen == xfer_sock->ns_namelen) &&
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200624 (!if_namelen || strcmp(rx->settings->interface, xfer_sock->iface) == 0) &&
Willy Tarreau2d34a712020-08-28 16:49:41 +0200625#ifdef USE_NS
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200626 (!ns_namelen || strcmp(rx->settings->netns->node.key, xfer_sock->namespace) == 0) &&
Willy Tarreau2d34a712020-08-28 16:49:41 +0200627#endif
Willy Tarreauf1f66092020-09-04 08:15:31 +0200628 rx->proto->fam->addrcmp(&xfer_sock->addr, &rx->addr) == 0)
Willy Tarreau2d34a712020-08-28 16:49:41 +0200629 break;
630 xfer_sock = xfer_sock->next;
631 }
632
633 if (xfer_sock != NULL) {
634 ret = xfer_sock->fd;
635 if (xfer_sock == xfer_sock_list)
636 xfer_sock_list = xfer_sock->next;
637 if (xfer_sock->prev)
638 xfer_sock->prev->next = xfer_sock->next;
639 if (xfer_sock->next)
640 xfer_sock->next->prev = xfer_sock->prev;
641 free(xfer_sock->iface);
642 free(xfer_sock->namespace);
643 free(xfer_sock);
644 }
645 return ret;
646}
647
Willy Tarreaub5101162022-01-28 18:28:18 +0100648/* After all protocols are bound, there may remain some old sockets that have
649 * been removed between the previous config and the new one. These ones must
650 * be dropped, otherwise they will remain open and may prevent a service from
651 * restarting.
652 */
653void sock_drop_unused_old_sockets()
654{
655 while (xfer_sock_list != NULL) {
656 struct xfer_sock_list *tmpxfer = xfer_sock_list->next;
657
658 close(xfer_sock_list->fd);
659 free(xfer_sock_list->iface);
660 free(xfer_sock_list->namespace);
661 free(xfer_sock_list);
662 xfer_sock_list = tmpxfer;
663 }
664}
665
Willy Tarreau5ced3e82020-10-13 17:06:12 +0200666/* Tests if the receiver supports accepting connections. Returns positive on
667 * success, 0 if not possible, negative if the socket is non-recoverable. The
668 * rationale behind this is that inherited FDs may be broken and that shared
669 * FDs might have been paused by another process.
670 */
Willy Tarreau7d053e42020-10-15 09:19:43 +0200671int sock_accepting_conn(const struct receiver *rx)
Willy Tarreau5ced3e82020-10-13 17:06:12 +0200672{
673 int opt_val = 0;
674 socklen_t opt_len = sizeof(opt_val);
675
676 if (getsockopt(rx->fd, SOL_SOCKET, SO_ACCEPTCONN, &opt_val, &opt_len) == -1)
677 return -1;
678
679 return opt_val;
680}
681
Willy Tarreaua74cb382020-10-15 21:29:49 +0200682/* This is the FD handler IO callback for stream sockets configured for
683 * accepting incoming connections. It's a pass-through to listener_accept()
684 * which will iterate over the listener protocol's accept_conn() function.
685 * The FD's owner must be a listener.
686 */
687void sock_accept_iocb(int fd)
688{
689 struct listener *l = fdtab[fd].owner;
690
691 if (!l)
692 return;
693
Willy Tarreaub4daeeb2020-11-04 14:58:36 +0100694 BUG_ON(!!master != !!(l->rx.flags & RX_F_MWORKER));
Willy Tarreaua74cb382020-10-15 21:29:49 +0200695 listener_accept(l);
696}
697
Willy Tarreaude471c42020-12-08 15:50:56 +0100698/* This completes the initialization of connection <conn> by inserting its FD
699 * into the fdtab, associating it with the regular connection handler. It will
700 * be bound to the current thread only. This call cannot fail.
701 */
702void sock_conn_ctrl_init(struct connection *conn)
703{
Willy Tarreau07ecfc52022-04-11 18:07:03 +0200704 BUG_ON(conn->flags & CO_FL_FDLESS);
Willy Tarreau586f71b2020-12-11 15:54:36 +0100705 fd_insert(conn->handle.fd, conn, sock_conn_iocb, tid_bit);
Willy Tarreaude471c42020-12-08 15:50:56 +0100706}
707
708/* This completes the release of connection <conn> by removing its FD from the
709 * fdtab and deleting it. The connection must not use the FD anymore past this
710 * point. The FD may be modified in the connection.
711 */
712void sock_conn_ctrl_close(struct connection *conn)
713{
Willy Tarreau07ecfc52022-04-11 18:07:03 +0200714 BUG_ON(conn->flags & CO_FL_FDLESS);
Willy Tarreaude471c42020-12-08 15:50:56 +0100715 fd_delete(conn->handle.fd);
716 conn->handle.fd = DEAD_FD_MAGIC;
717}
718
Willy Tarreau586f71b2020-12-11 15:54:36 +0100719/* This is the callback which is set when a connection establishment is pending
720 * and we have nothing to send. It may update the FD polling status to indicate
721 * !READY. It returns 0 if it fails in a fatal way or needs to poll to go
722 * further, otherwise it returns non-zero and removes the CO_FL_WAIT_L4_CONN
723 * flag from the connection's flags. In case of error, it sets CO_FL_ERROR and
724 * leaves the error code in errno.
725 */
726int sock_conn_check(struct connection *conn)
727{
728 struct sockaddr_storage *addr;
729 int fd = conn->handle.fd;
730
731 if (conn->flags & CO_FL_ERROR)
732 return 0;
733
734 if (!conn_ctrl_ready(conn))
735 return 0;
736
737 if (!(conn->flags & CO_FL_WAIT_L4_CONN))
738 return 1; /* strange we were called while ready */
739
Willy Tarreau07ecfc52022-04-11 18:07:03 +0200740 BUG_ON(conn->flags & CO_FL_FDLESS);
741
Willy Tarreau5a9c6372021-07-06 08:29:20 +0200742 if (!fd_send_ready(fd) && !(fdtab[fd].state & (FD_POLL_ERR|FD_POLL_HUP)))
Willy Tarreau586f71b2020-12-11 15:54:36 +0100743 return 0;
744
745 /* Here we have 2 cases :
746 * - modern pollers, able to report ERR/HUP. If these ones return any
747 * of these flags then it's likely a failure, otherwise it possibly
748 * is a success (i.e. there may have been data received just before
749 * the error was reported).
750 * - select, which doesn't report these and with which it's always
751 * necessary either to try connect() again or to check for SO_ERROR.
752 * In order to simplify everything, we double-check using connect() as
753 * soon as we meet either of these delicate situations. Note that
754 * SO_ERROR would clear the error after reporting it!
755 */
756 if (cur_poller.flags & HAP_POLL_F_ERRHUP) {
757 /* modern poller, able to report ERR/HUP */
Willy Tarreauf5090652021-04-06 17:23:40 +0200758 if ((fdtab[fd].state & (FD_POLL_IN|FD_POLL_ERR|FD_POLL_HUP)) == FD_POLL_IN)
Willy Tarreau586f71b2020-12-11 15:54:36 +0100759 goto done;
Willy Tarreauf5090652021-04-06 17:23:40 +0200760 if ((fdtab[fd].state & (FD_POLL_OUT|FD_POLL_ERR|FD_POLL_HUP)) == FD_POLL_OUT)
Willy Tarreau586f71b2020-12-11 15:54:36 +0100761 goto done;
Willy Tarreauf5090652021-04-06 17:23:40 +0200762 if (!(fdtab[fd].state & (FD_POLL_ERR|FD_POLL_HUP)))
Willy Tarreau586f71b2020-12-11 15:54:36 +0100763 goto wait;
764 /* error present, fall through common error check path */
765 }
766
767 /* Use connect() to check the state of the socket. This has the double
768 * advantage of *not* clearing the error (so that health checks can
769 * still use getsockopt(SO_ERROR)) and giving us the following info :
770 * - error
771 * - connecting (EALREADY, EINPROGRESS)
772 * - connected (EISCONN, 0)
773 */
774 addr = conn->dst;
775 if ((conn->flags & CO_FL_SOCKS4) && obj_type(conn->target) == OBJ_TYPE_SERVER)
776 addr = &objt_server(conn->target)->socks4_addr;
777
778 if (connect(fd, (const struct sockaddr *)addr, get_addr_len(addr)) == -1) {
779 if (errno == EALREADY || errno == EINPROGRESS)
780 goto wait;
781
782 if (errno && errno != EISCONN)
783 goto out_error;
784 }
785
786 done:
787 /* The FD is ready now, we'll mark the connection as complete and
788 * forward the event to the transport layer which will notify the
789 * data layer.
790 */
791 conn->flags &= ~CO_FL_WAIT_L4_CONN;
792 fd_may_send(fd);
793 fd_cond_recv(fd);
794 errno = 0; // make health checks happy
795 return 1;
796
797 out_error:
798 /* Write error on the file descriptor. Report it to the connection
799 * and disable polling on this FD.
800 */
Willy Tarreau586f71b2020-12-11 15:54:36 +0100801 conn->flags |= CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH;
Willy Tarreaub41a6e92021-04-06 17:49:19 +0200802 HA_ATOMIC_AND(&fdtab[fd].state, ~FD_LINGER_RISK);
Willy Tarreau586f71b2020-12-11 15:54:36 +0100803 fd_stop_both(fd);
804 return 0;
805
806 wait:
807 fd_cant_send(fd);
808 fd_want_send(fd);
809 return 0;
810}
811
812/* I/O callback for fd-based connections. It calls the read/write handlers
813 * provided by the connection's sock_ops, which must be valid.
814 */
815void sock_conn_iocb(int fd)
816{
817 struct connection *conn = fdtab[fd].owner;
818 unsigned int flags;
819 int need_wake = 0;
820
821 if (unlikely(!conn)) {
822 activity[tid].conn_dead++;
823 return;
824 }
825
826 flags = conn->flags & ~CO_FL_ERROR; /* ensure to call the wake handler upon error */
827
828 if (unlikely(conn->flags & CO_FL_WAIT_L4_CONN) &&
829 ((fd_send_ready(fd) && fd_send_active(fd)) ||
830 (fd_recv_ready(fd) && fd_recv_active(fd)))) {
831 /* Still waiting for a connection to establish and nothing was
832 * attempted yet to probe the connection. this will clear the
833 * CO_FL_WAIT_L4_CONN flag on success.
834 */
835 if (!sock_conn_check(conn))
836 goto leave;
837 need_wake = 1;
838 }
839
840 if (fd_send_ready(fd) && fd_send_active(fd)) {
841 /* force reporting of activity by clearing the previous flags :
842 * we'll have at least ERROR or CONNECTED at the end of an I/O,
843 * both of which will be detected below.
844 */
845 flags = 0;
846 if (conn->subs && conn->subs->events & SUB_RETRY_SEND) {
847 need_wake = 0; // wake will be called after this I/O
848 tasklet_wakeup(conn->subs->tasklet);
849 conn->subs->events &= ~SUB_RETRY_SEND;
850 if (!conn->subs->events)
851 conn->subs = NULL;
852 }
853 fd_stop_send(fd);
854 }
855
856 /* The data transfer starts here and stops on error and handshakes. Note
857 * that we must absolutely test conn->xprt at each step in case it suddenly
858 * changes due to a quick unexpected close().
859 */
860 if (fd_recv_ready(fd) && fd_recv_active(fd)) {
861 /* force reporting of activity by clearing the previous flags :
862 * we'll have at least ERROR or CONNECTED at the end of an I/O,
863 * both of which will be detected below.
864 */
865 flags = 0;
866 if (conn->subs && conn->subs->events & SUB_RETRY_RECV) {
867 need_wake = 0; // wake will be called after this I/O
868 tasklet_wakeup(conn->subs->tasklet);
869 conn->subs->events &= ~SUB_RETRY_RECV;
870 if (!conn->subs->events)
871 conn->subs = NULL;
872 }
873 fd_stop_recv(fd);
874 }
875
876 leave:
877 /* we may have to finish to install a mux or to wake it up based on
878 * what was just done above. It may kill the connection so we have to
879 * be prpared not to use it anymore.
880 */
881 if (conn_notify_mux(conn, flags, need_wake) < 0)
882 return;
883
884 /* commit polling changes in case of error.
885 * WT: it seems that the last case where this could still be relevant
886 * is if a mux wake function above report a connection error but does
887 * not stop polling. Shouldn't we enforce this into the mux instead of
888 * having to deal with this ?
889 */
890 if (unlikely(conn->flags & CO_FL_ERROR)) {
891 if (conn_ctrl_ready(conn))
892 fd_stop_both(fd);
893 }
894}
895
Willy Tarreau427c8462020-12-11 16:19:12 +0100896/* Drains possibly pending incoming data on the file descriptor attached to the
897 * connection. This is used to know whether we need to disable lingering on
898 * close. Returns non-zero if it is safe to close without disabling lingering,
899 * otherwise zero.
900 */
901int sock_drain(struct connection *conn)
902{
903 int turns = 2;
904 int fd = conn->handle.fd;
905 int len;
906
Willy Tarreau07ecfc52022-04-11 18:07:03 +0200907 BUG_ON(conn->flags & CO_FL_FDLESS);
908
Willy Tarreauf5090652021-04-06 17:23:40 +0200909 if (fdtab[fd].state & (FD_POLL_ERR|FD_POLL_HUP))
Willy Tarreau427c8462020-12-11 16:19:12 +0100910 goto shut;
911
Willy Tarreau20b622e2021-10-21 21:31:42 +0200912 if (!(conn->flags & CO_FL_WANT_DRAIN) && !fd_recv_ready(fd))
Willy Tarreau427c8462020-12-11 16:19:12 +0100913 return 0;
914
915 /* no drain function defined, use the generic one */
916
917 while (turns) {
918#ifdef MSG_TRUNC_CLEARS_INPUT
919 len = recv(fd, NULL, INT_MAX, MSG_DONTWAIT | MSG_NOSIGNAL | MSG_TRUNC);
920 if (len == -1 && errno == EFAULT)
921#endif
922 len = recv(fd, trash.area, trash.size, MSG_DONTWAIT | MSG_NOSIGNAL);
923
924 if (len == 0)
925 goto shut;
926
927 if (len < 0) {
928 if (errno == EAGAIN) {
929 /* connection not closed yet */
930 fd_cant_recv(fd);
931 break;
932 }
933 if (errno == EINTR) /* oops, try again */
934 continue;
935 /* other errors indicate a dead connection, fine. */
936 goto shut;
937 }
938 /* OK we read some data, let's try again once */
939 turns--;
940 }
941
942 /* some data are still present, give up */
943 return 0;
944
945 shut:
946 /* we're certain the connection was shut down */
Willy Tarreaub41a6e92021-04-06 17:49:19 +0200947 HA_ATOMIC_AND(&fdtab[fd].state, ~FD_LINGER_RISK);
Willy Tarreau427c8462020-12-11 16:19:12 +0100948 return 1;
949}
950
Willy Tarreau472125b2020-12-11 17:02:50 +0100951/* Checks the connection's FD for readiness of events <event_type>, which may
952 * only be a combination of SUB_RETRY_RECV and SUB_RETRY_SEND. Those which are
953 * ready are returned. The ones that are not ready are enabled. The caller is
954 * expected to do what is needed to handle ready events and to deal with
955 * subsequent wakeups caused by the requested events' readiness.
956 */
957int sock_check_events(struct connection *conn, int event_type)
958{
959 int ret = 0;
960
Willy Tarreau07ecfc52022-04-11 18:07:03 +0200961 BUG_ON(conn->flags & CO_FL_FDLESS);
962
Willy Tarreau472125b2020-12-11 17:02:50 +0100963 if (event_type & SUB_RETRY_RECV) {
964 if (fd_recv_ready(conn->handle.fd))
965 ret |= SUB_RETRY_RECV;
966 else
967 fd_want_recv(conn->handle.fd);
968 }
969
970 if (event_type & SUB_RETRY_SEND) {
971 if (fd_send_ready(conn->handle.fd))
972 ret |= SUB_RETRY_SEND;
973 else
974 fd_want_send(conn->handle.fd);
975 }
976
977 return ret;
978}
979
980/* Ignore readiness events from connection's FD for events of types <event_type>
981 * which may only be a combination of SUB_RETRY_RECV and SUB_RETRY_SEND.
982 */
983void sock_ignore_events(struct connection *conn, int event_type)
984{
Willy Tarreau07ecfc52022-04-11 18:07:03 +0200985 BUG_ON(conn->flags & CO_FL_FDLESS);
986
Willy Tarreau472125b2020-12-11 17:02:50 +0100987 if (event_type & SUB_RETRY_RECV)
988 fd_stop_recv(conn->handle.fd);
989
990 if (event_type & SUB_RETRY_SEND)
991 fd_stop_send(conn->handle.fd);
992}
993
Willy Tarreau18b7df72020-08-28 12:07:22 +0200994/*
995 * Local variables:
996 * c-indent-level: 8
997 * c-basic-offset: 8
998 * End:
999 */