blob: f6ab83f55511c40670c562d1f72a15699b6c1fd0 [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)) {
106 /* Perfect, the connection was accepted */
Willy Tarreau344b8fc2020-10-15 09:43:31 +0200107 conn = conn_new(&l->obj_type);
108 if (!conn)
109 goto fail_conn;
110
111 conn->src = addr;
Willy Tarreauf1dc9f22020-10-15 09:21:31 +0200112 conn->handle.fd = cfd;
113 conn->flags |= CO_FL_ADDR_FROM_SET;
114 ret = CO_AC_DONE;
115 goto done;
116 }
117
118 /* error conditions below */
Willy Tarreau344b8fc2020-10-15 09:43:31 +0200119 sockaddr_free(&addr);
Willy Tarreauf1dc9f22020-10-15 09:21:31 +0200120
121 switch (errno) {
122 case EAGAIN:
123 ret = CO_AC_DONE; /* nothing more to accept */
Willy Tarreauf5090652021-04-06 17:23:40 +0200124 if (fdtab[l->rx.fd].state & (FD_POLL_HUP|FD_POLL_ERR)) {
Willy Tarreauf1dc9f22020-10-15 09:21:31 +0200125 /* the listening socket might have been disabled in a shared
126 * process and we're a collateral victim. We'll just pause for
127 * a while in case it comes back. In the mean time, we need to
128 * clear this sticky flag.
129 */
Willy Tarreauf5090652021-04-06 17:23:40 +0200130 _HA_ATOMIC_AND(&fdtab[l->rx.fd].state, ~(FD_POLL_HUP|FD_POLL_ERR));
Willy Tarreauf1dc9f22020-10-15 09:21:31 +0200131 ret = CO_AC_PAUSE;
132 }
133 fd_cant_recv(l->rx.fd);
134 break;
135
136 case EINVAL:
137 /* might be trying to accept on a shut fd (eg: soft stop) */
138 ret = CO_AC_PAUSE;
139 break;
140
141 case EINTR:
142 case ECONNABORTED:
143 ret = CO_AC_RETRY;
144 break;
145
146 case ENFILE:
147 if (p)
148 send_log(p, LOG_EMERG,
149 "Proxy %s reached system FD limit (maxsock=%d). Please check system tunables.\n",
150 p->id, global.maxsock);
151 ret = CO_AC_PAUSE;
152 break;
153
154 case EMFILE:
155 if (p)
156 send_log(p, LOG_EMERG,
157 "Proxy %s reached process FD limit (maxsock=%d). Please check 'ulimit-n' and restart.\n",
158 p->id, global.maxsock);
159 ret = CO_AC_PAUSE;
160 break;
161
162 case ENOBUFS:
163 case ENOMEM:
164 if (p)
165 send_log(p, LOG_EMERG,
166 "Proxy %s reached system memory limit (maxsock=%d). Please check system tunables.\n",
167 p->id, global.maxsock);
168 ret = CO_AC_PAUSE;
169 break;
170
171 default:
172 /* unexpected result, let's give up and let other tasks run */
173 ret = CO_AC_YIELD;
174 }
175 done:
176 if (status)
177 *status = ret;
178 return conn;
179
Willy Tarreauf1dc9f22020-10-15 09:21:31 +0200180 fail_conn:
Willy Tarreau344b8fc2020-10-15 09:43:31 +0200181 sockaddr_free(&addr);
Remi Tricot-Le Breton25dd0ad2021-01-14 15:26:24 +0100182 /* The accept call already succeeded by the time we try to allocate the connection,
183 * we need to close it in case of failure. */
184 close(cfd);
Willy Tarreau344b8fc2020-10-15 09:43:31 +0200185 fail_addr:
Willy Tarreauf1dc9f22020-10-15 09:21:31 +0200186 ret = CO_AC_PAUSE;
187 goto done;
188}
189
Willy Tarreau18b7df72020-08-28 12:07:22 +0200190/* Create a socket to connect to the server in conn->dst (which MUST be valid),
191 * using the configured namespace if needed, or the one passed by the proxy
192 * protocol if required to do so. It ultimately calls socket() or socketat()
193 * and returns the FD or error code.
194 */
195int sock_create_server_socket(struct connection *conn)
196{
197 const struct netns_entry *ns = NULL;
198
199#ifdef USE_NS
200 if (objt_server(conn->target)) {
201 if (__objt_server(conn->target)->flags & SRV_F_USE_NS_FROM_PP)
202 ns = conn->proxy_netns;
203 else
204 ns = __objt_server(conn->target)->netns;
205 }
206#endif
207 return my_socketat(ns, conn->dst->ss_family, SOCK_STREAM, 0);
208}
209
Willy Tarreaua4380b22020-11-04 13:59:04 +0100210/* Enables receiving on receiver <rx> once already bound. */
Willy Tarreaue70c7972020-09-25 19:00:01 +0200211void sock_enable(struct receiver *rx)
212{
Willy Tarreaua4380b22020-11-04 13:59:04 +0100213 if (rx->flags & RX_F_BOUND)
214 fd_want_recv_safe(rx->fd);
Willy Tarreaue70c7972020-09-25 19:00:01 +0200215}
216
Willy Tarreaua4380b22020-11-04 13:59:04 +0100217/* Disables receiving on receiver <rx> once already bound. */
Willy Tarreaue70c7972020-09-25 19:00:01 +0200218void sock_disable(struct receiver *rx)
219{
Willy Tarreaua4380b22020-11-04 13:59:04 +0100220 if (rx->flags & RX_F_BOUND)
Willy Tarreaue70c7972020-09-25 19:00:01 +0200221 fd_stop_recv(rx->fd);
222}
223
Willy Tarreauf58b8db2020-10-09 16:32:08 +0200224/* stops, unbinds and possibly closes the FD associated with receiver rx */
225void sock_unbind(struct receiver *rx)
226{
227 /* There are a number of situations where we prefer to keep the FD and
228 * not to close it (unless we're stopping, of course):
229 * - worker process unbinding from a worker's FD with socket transfer enabled => keep
230 * - master process unbinding from a master's inherited FD => keep
231 * - master process unbinding from a master's FD => close
Willy Tarreau22ccd5e2020-11-03 18:38:05 +0100232 * - master process unbinding from a worker's inherited FD => keep
Willy Tarreauf58b8db2020-10-09 16:32:08 +0200233 * - master process unbinding from a worker's FD => close
234 * - worker process unbinding from a master's FD => close
235 * - worker process unbinding from a worker's FD => close
236 */
237 if (rx->flags & RX_F_BOUND)
238 rx->proto->rx_disable(rx);
239
240 if (!stopping && !master &&
241 !(rx->flags & RX_F_MWORKER) &&
242 (global.tune.options & GTUNE_SOCKET_TRANSFER))
243 return;
244
245 if (!stopping && master &&
Willy Tarreauf58b8db2020-10-09 16:32:08 +0200246 rx->flags & RX_F_INHERITED)
247 return;
248
249 rx->flags &= ~RX_F_BOUND;
250 if (rx->fd != -1)
251 fd_delete(rx->fd);
252 rx->fd = -1;
253}
254
Willy Tarreau18b7df72020-08-28 12:07:22 +0200255/*
256 * Retrieves the source address for the socket <fd>, with <dir> indicating
257 * if we're a listener (=0) or an initiator (!=0). It returns 0 in case of
258 * success, -1 in case of error. The socket's source address is stored in
259 * <sa> for <salen> bytes.
260 */
261int sock_get_src(int fd, struct sockaddr *sa, socklen_t salen, int dir)
262{
263 if (dir)
264 return getsockname(fd, sa, &salen);
265 else
266 return getpeername(fd, sa, &salen);
267}
268
269/*
270 * Retrieves the original destination address for the socket <fd>, with <dir>
271 * indicating if we're a listener (=0) or an initiator (!=0). It returns 0 in
272 * case of success, -1 in case of error. The socket's source address is stored
273 * in <sa> for <salen> bytes.
274 */
275int sock_get_dst(int fd, struct sockaddr *sa, socklen_t salen, int dir)
276{
277 if (dir)
278 return getpeername(fd, sa, &salen);
279 else
280 return getsockname(fd, sa, &salen);
281}
282
Willy Tarreau42961742020-08-28 18:42:45 +0200283/* Try to retrieve exported sockets from worker at CLI <unixsocket>. These
284 * ones will be placed into the xfer_sock_list for later use by function
285 * sock_find_compatible_fd(). Returns 0 on success, -1 on failure.
286 */
287int sock_get_old_sockets(const char *unixsocket)
288{
289 char *cmsgbuf = NULL, *tmpbuf = NULL;
290 int *tmpfd = NULL;
291 struct sockaddr_un addr;
292 struct cmsghdr *cmsg;
293 struct msghdr msghdr;
294 struct iovec iov;
295 struct xfer_sock_list *xfer_sock = NULL;
296 struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
297 int sock = -1;
298 int ret = -1;
299 int ret2 = -1;
300 int fd_nb;
301 int got_fd = 0;
302 int cur_fd = 0;
303 size_t maxoff = 0, curoff = 0;
304
William Lallemand2be557f2021-11-24 18:45:37 +0100305 if (strncmp("sockpair@", unixsocket, strlen("sockpair@")) == 0) {
306 /* sockpair for master-worker usage */
307 int sv[2];
308 int dst_fd;
309
310 dst_fd = strtoll(unixsocket + strlen("sockpair@"), NULL, 0);
311
312 if (socketpair(PF_UNIX, SOCK_STREAM, 0, sv) == -1) {
313 ha_warning("socketpair(): Cannot create socketpair. Giving up.\n");
314 }
315
316 if (send_fd_uxst(dst_fd, sv[0]) == -1) {
317 ha_alert("socketpair: cannot transfer socket.\n");
318 close(sv[0]);
319 close(sv[1]);
320 goto out;
321 }
322
323 close(sv[0]); /* we don't need this side anymore */
324 sock = sv[1];
325
326 } else {
327 /* Unix socket */
328
329 sock = socket(PF_UNIX, SOCK_STREAM, 0);
330 if (sock < 0) {
331 ha_warning("Failed to connect to the old process socket '%s'\n", unixsocket);
332 goto out;
333 }
334
335 strncpy(addr.sun_path, unixsocket, sizeof(addr.sun_path) - 1);
336 addr.sun_path[sizeof(addr.sun_path) - 1] = 0;
337 addr.sun_family = PF_UNIX;
338
339 ret = connect(sock, (struct sockaddr *)&addr, sizeof(addr));
340 if (ret < 0) {
341 ha_warning("Failed to connect to the old process socket '%s'\n", unixsocket);
342 goto out;
343 }
344
345 }
Willy Tarreau42961742020-08-28 18:42:45 +0200346 memset(&msghdr, 0, sizeof(msghdr));
347 cmsgbuf = malloc(CMSG_SPACE(sizeof(int)) * MAX_SEND_FD);
348 if (!cmsgbuf) {
349 ha_warning("Failed to allocate memory to send sockets\n");
350 goto out;
351 }
352
Willy Tarreau42961742020-08-28 18:42:45 +0200353 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (void *)&tv, sizeof(tv));
354 iov.iov_base = &fd_nb;
355 iov.iov_len = sizeof(fd_nb);
356 msghdr.msg_iov = &iov;
357 msghdr.msg_iovlen = 1;
358
359 if (send(sock, "_getsocks\n", strlen("_getsocks\n"), 0) != strlen("_getsocks\n")) {
360 ha_warning("Failed to get the number of sockets to be transferred !\n");
361 goto out;
362 }
363
364 /* First, get the number of file descriptors to be received */
365 if (recvmsg(sock, &msghdr, MSG_WAITALL) != sizeof(fd_nb)) {
366 ha_warning("Failed to get the number of sockets to be transferred !\n");
367 goto out;
368 }
369
370 if (fd_nb == 0) {
371 ret2 = 0;
372 goto out;
373 }
374
375 tmpbuf = malloc(fd_nb * (1 + MAXPATHLEN + 1 + IFNAMSIZ + sizeof(int)));
376 if (tmpbuf == NULL) {
377 ha_warning("Failed to allocate memory while receiving sockets\n");
378 goto out;
379 }
380
381 tmpfd = malloc(fd_nb * sizeof(int));
382 if (tmpfd == NULL) {
383 ha_warning("Failed to allocate memory while receiving sockets\n");
384 goto out;
385 }
386
387 msghdr.msg_control = cmsgbuf;
388 msghdr.msg_controllen = CMSG_SPACE(sizeof(int)) * MAX_SEND_FD;
389 iov.iov_len = MAX_SEND_FD * (1 + MAXPATHLEN + 1 + IFNAMSIZ + sizeof(int));
390
391 do {
392 int ret3;
393
394 iov.iov_base = tmpbuf + curoff;
395
396 ret = recvmsg(sock, &msghdr, 0);
397
398 if (ret == -1 && errno == EINTR)
399 continue;
400
401 if (ret <= 0)
402 break;
403
404 /* Send an ack to let the sender know we got the sockets
405 * and it can send some more
406 */
407 do {
408 ret3 = send(sock, &got_fd, sizeof(got_fd), 0);
409 } while (ret3 == -1 && errno == EINTR);
410
411 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg != NULL; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
412 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
413 size_t totlen = cmsg->cmsg_len - CMSG_LEN(0);
414
415 if (totlen / sizeof(int) + got_fd > fd_nb) {
416 ha_warning("Got to many sockets !\n");
417 goto out;
418 }
419
420 /*
421 * Be paranoid and use memcpy() to avoid any
422 * potential alignment issue.
423 */
424 memcpy(&tmpfd[got_fd], CMSG_DATA(cmsg), totlen);
425 got_fd += totlen / sizeof(int);
426 }
427 }
428 curoff += ret;
429 } while (got_fd < fd_nb);
430
431 if (got_fd != fd_nb) {
432 ha_warning("We didn't get the expected number of sockets (expecting %d got %d)\n",
433 fd_nb, got_fd);
434 goto out;
435 }
436
437 maxoff = curoff;
438 curoff = 0;
439
440 for (cur_fd = 0; cur_fd < got_fd; cur_fd++) {
441 int fd = tmpfd[cur_fd];
442 socklen_t socklen;
443 int val;
444 int len;
445
446 xfer_sock = calloc(1, sizeof(*xfer_sock));
447 if (!xfer_sock) {
448 ha_warning("Failed to allocate memory in get_old_sockets() !\n");
449 break;
450 }
451 xfer_sock->fd = -1;
452
453 socklen = sizeof(xfer_sock->addr);
454 if (getsockname(fd, (struct sockaddr *)&xfer_sock->addr, &socklen) != 0) {
455 ha_warning("Failed to get socket address\n");
Willy Tarreau61cfdf42021-02-20 10:46:51 +0100456 ha_free(&xfer_sock);
Willy Tarreau42961742020-08-28 18:42:45 +0200457 continue;
458 }
459
460 if (curoff >= maxoff) {
461 ha_warning("Inconsistency while transferring sockets\n");
462 goto out;
463 }
464
465 len = tmpbuf[curoff++];
466 if (len > 0) {
467 /* We have a namespace */
468 if (curoff + len > maxoff) {
469 ha_warning("Inconsistency while transferring sockets\n");
470 goto out;
471 }
472 xfer_sock->namespace = malloc(len + 1);
473 if (!xfer_sock->namespace) {
474 ha_warning("Failed to allocate memory while transferring sockets\n");
475 goto out;
476 }
477 memcpy(xfer_sock->namespace, &tmpbuf[curoff], len);
478 xfer_sock->namespace[len] = 0;
479 xfer_sock->ns_namelen = len;
480 curoff += len;
481 }
482
483 if (curoff >= maxoff) {
484 ha_warning("Inconsistency while transferring sockets\n");
485 goto out;
486 }
487
488 len = tmpbuf[curoff++];
489 if (len > 0) {
490 /* We have an interface */
491 if (curoff + len > maxoff) {
492 ha_warning("Inconsistency while transferring sockets\n");
493 goto out;
494 }
495 xfer_sock->iface = malloc(len + 1);
496 if (!xfer_sock->iface) {
497 ha_warning("Failed to allocate memory while transferring sockets\n");
498 goto out;
499 }
500 memcpy(xfer_sock->iface, &tmpbuf[curoff], len);
501 xfer_sock->iface[len] = 0;
502 xfer_sock->if_namelen = len;
503 curoff += len;
504 }
505
506 if (curoff + sizeof(int) > maxoff) {
507 ha_warning("Inconsistency while transferring sockets\n");
508 goto out;
509 }
510
511 /* we used to have 32 bits of listener options here but we don't
512 * use them anymore.
513 */
514 curoff += sizeof(int);
515
516 /* determine the foreign status directly from the socket itself */
517 if (sock_inet_is_foreign(fd, xfer_sock->addr.ss_family))
Willy Tarreaua2c17872020-08-28 19:09:19 +0200518 xfer_sock->options |= SOCK_XFER_OPT_FOREIGN;
Willy Tarreau42961742020-08-28 18:42:45 +0200519
Willy Tarreau9dbb6c42020-08-28 19:20:23 +0200520 socklen = sizeof(val);
521 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &val, &socklen) == 0 && val == SOCK_DGRAM)
522 xfer_sock->options |= SOCK_XFER_OPT_DGRAM;
523
Willy Tarreau42961742020-08-28 18:42:45 +0200524#if defined(IPV6_V6ONLY)
525 /* keep only the v6only flag depending on what's currently
526 * active on the socket, and always drop the v4v6 one.
527 */
528 socklen = sizeof(val);
529 if (xfer_sock->addr.ss_family == AF_INET6 &&
530 getsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &val, &socklen) == 0 && val > 0)
Willy Tarreaua2c17872020-08-28 19:09:19 +0200531 xfer_sock->options |= SOCK_XFER_OPT_V6ONLY;
Willy Tarreau42961742020-08-28 18:42:45 +0200532#endif
533
534 xfer_sock->fd = fd;
535 if (xfer_sock_list)
536 xfer_sock_list->prev = xfer_sock;
537 xfer_sock->next = xfer_sock_list;
538 xfer_sock->prev = NULL;
539 xfer_sock_list = xfer_sock;
540 xfer_sock = NULL;
541 }
542
543 ret2 = 0;
544out:
545 /* If we failed midway make sure to close the remaining
546 * file descriptors
547 */
548 if (tmpfd != NULL && cur_fd < got_fd) {
549 for (; cur_fd < got_fd; cur_fd++) {
550 close(tmpfd[cur_fd]);
551 }
552 }
553
554 free(tmpbuf);
555 free(tmpfd);
556 free(cmsgbuf);
557
558 if (sock != -1)
559 close(sock);
560
561 if (xfer_sock) {
562 free(xfer_sock->namespace);
563 free(xfer_sock->iface);
564 if (xfer_sock->fd != -1)
565 close(xfer_sock->fd);
566 free(xfer_sock);
567 }
568 return (ret2);
569}
570
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200571/* When binding the receivers, check if a socket has been sent to us by the
Willy Tarreau2d34a712020-08-28 16:49:41 +0200572 * previous process that we could reuse, instead of creating a new one. Note
573 * that some address family-specific options are checked on the listener and
574 * on the socket. Typically for AF_INET and AF_INET6, we check for transparent
575 * mode, and for AF_INET6 we also check for "v4v6" or "v6only". The reused
576 * socket is automatically removed from the list so that it's not proposed
577 * anymore.
578 */
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200579int sock_find_compatible_fd(const struct receiver *rx)
Willy Tarreau2d34a712020-08-28 16:49:41 +0200580{
581 struct xfer_sock_list *xfer_sock = xfer_sock_list;
Willy Tarreaua2c17872020-08-28 19:09:19 +0200582 int options = 0;
Willy Tarreau2d34a712020-08-28 16:49:41 +0200583 int if_namelen = 0;
584 int ns_namelen = 0;
585 int ret = -1;
586
Willy Tarreauf1f66092020-09-04 08:15:31 +0200587 if (!rx->proto->fam->addrcmp)
Willy Tarreau2d34a712020-08-28 16:49:41 +0200588 return -1;
589
Willy Tarreaue3b45182021-10-27 17:28:55 +0200590 if (rx->proto->proto_type == PROTO_TYPE_DGRAM)
Willy Tarreau9dbb6c42020-08-28 19:20:23 +0200591 options |= SOCK_XFER_OPT_DGRAM;
592
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200593 if (rx->settings->options & RX_O_FOREIGN)
Willy Tarreaua2c17872020-08-28 19:09:19 +0200594 options |= SOCK_XFER_OPT_FOREIGN;
595
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200596 if (rx->addr.ss_family == AF_INET6) {
Willy Tarreau2d34a712020-08-28 16:49:41 +0200597 /* Prepare to match the v6only option against what we really want. Note
598 * that sadly the two options are not exclusive to each other and that
599 * v6only is stronger than v4v6.
600 */
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200601 if ((rx->settings->options & RX_O_V6ONLY) ||
602 (sock_inet6_v6only_default && !(rx->settings->options & RX_O_V4V6)))
Willy Tarreaua2c17872020-08-28 19:09:19 +0200603 options |= SOCK_XFER_OPT_V6ONLY;
Willy Tarreau2d34a712020-08-28 16:49:41 +0200604 }
Willy Tarreau2d34a712020-08-28 16:49:41 +0200605
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200606 if (rx->settings->interface)
607 if_namelen = strlen(rx->settings->interface);
Willy Tarreau2d34a712020-08-28 16:49:41 +0200608#ifdef USE_NS
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200609 if (rx->settings->netns)
610 ns_namelen = rx->settings->netns->name_len;
Willy Tarreau2d34a712020-08-28 16:49:41 +0200611#endif
612
613 while (xfer_sock) {
Willy Tarreaua2c17872020-08-28 19:09:19 +0200614 if ((options == xfer_sock->options) &&
Willy Tarreau2d34a712020-08-28 16:49:41 +0200615 (if_namelen == xfer_sock->if_namelen) &&
616 (ns_namelen == xfer_sock->ns_namelen) &&
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200617 (!if_namelen || strcmp(rx->settings->interface, xfer_sock->iface) == 0) &&
Willy Tarreau2d34a712020-08-28 16:49:41 +0200618#ifdef USE_NS
Willy Tarreauc049c0d2020-09-01 15:20:52 +0200619 (!ns_namelen || strcmp(rx->settings->netns->node.key, xfer_sock->namespace) == 0) &&
Willy Tarreau2d34a712020-08-28 16:49:41 +0200620#endif
Willy Tarreauf1f66092020-09-04 08:15:31 +0200621 rx->proto->fam->addrcmp(&xfer_sock->addr, &rx->addr) == 0)
Willy Tarreau2d34a712020-08-28 16:49:41 +0200622 break;
623 xfer_sock = xfer_sock->next;
624 }
625
626 if (xfer_sock != NULL) {
627 ret = xfer_sock->fd;
628 if (xfer_sock == xfer_sock_list)
629 xfer_sock_list = xfer_sock->next;
630 if (xfer_sock->prev)
631 xfer_sock->prev->next = xfer_sock->next;
632 if (xfer_sock->next)
633 xfer_sock->next->prev = xfer_sock->prev;
634 free(xfer_sock->iface);
635 free(xfer_sock->namespace);
636 free(xfer_sock);
637 }
638 return ret;
639}
640
Willy Tarreaub5101162022-01-28 18:28:18 +0100641/* After all protocols are bound, there may remain some old sockets that have
642 * been removed between the previous config and the new one. These ones must
643 * be dropped, otherwise they will remain open and may prevent a service from
644 * restarting.
645 */
646void sock_drop_unused_old_sockets()
647{
648 while (xfer_sock_list != NULL) {
649 struct xfer_sock_list *tmpxfer = xfer_sock_list->next;
650
651 close(xfer_sock_list->fd);
652 free(xfer_sock_list->iface);
653 free(xfer_sock_list->namespace);
654 free(xfer_sock_list);
655 xfer_sock_list = tmpxfer;
656 }
657}
658
Willy Tarreau5ced3e82020-10-13 17:06:12 +0200659/* Tests if the receiver supports accepting connections. Returns positive on
660 * success, 0 if not possible, negative if the socket is non-recoverable. The
661 * rationale behind this is that inherited FDs may be broken and that shared
662 * FDs might have been paused by another process.
663 */
Willy Tarreau7d053e42020-10-15 09:19:43 +0200664int sock_accepting_conn(const struct receiver *rx)
Willy Tarreau5ced3e82020-10-13 17:06:12 +0200665{
666 int opt_val = 0;
667 socklen_t opt_len = sizeof(opt_val);
668
669 if (getsockopt(rx->fd, SOL_SOCKET, SO_ACCEPTCONN, &opt_val, &opt_len) == -1)
670 return -1;
671
672 return opt_val;
673}
674
Willy Tarreaua74cb382020-10-15 21:29:49 +0200675/* This is the FD handler IO callback for stream sockets configured for
676 * accepting incoming connections. It's a pass-through to listener_accept()
677 * which will iterate over the listener protocol's accept_conn() function.
678 * The FD's owner must be a listener.
679 */
680void sock_accept_iocb(int fd)
681{
682 struct listener *l = fdtab[fd].owner;
683
684 if (!l)
685 return;
686
Willy Tarreaub4daeeb2020-11-04 14:58:36 +0100687 BUG_ON(!!master != !!(l->rx.flags & RX_F_MWORKER));
Willy Tarreaua74cb382020-10-15 21:29:49 +0200688 listener_accept(l);
689}
690
Willy Tarreaude471c42020-12-08 15:50:56 +0100691/* This completes the initialization of connection <conn> by inserting its FD
692 * into the fdtab, associating it with the regular connection handler. It will
693 * be bound to the current thread only. This call cannot fail.
694 */
695void sock_conn_ctrl_init(struct connection *conn)
696{
Willy Tarreau586f71b2020-12-11 15:54:36 +0100697 fd_insert(conn->handle.fd, conn, sock_conn_iocb, tid_bit);
Willy Tarreaude471c42020-12-08 15:50:56 +0100698}
699
700/* This completes the release of connection <conn> by removing its FD from the
701 * fdtab and deleting it. The connection must not use the FD anymore past this
702 * point. The FD may be modified in the connection.
703 */
704void sock_conn_ctrl_close(struct connection *conn)
705{
706 fd_delete(conn->handle.fd);
707 conn->handle.fd = DEAD_FD_MAGIC;
708}
709
Willy Tarreau586f71b2020-12-11 15:54:36 +0100710/* This is the callback which is set when a connection establishment is pending
711 * and we have nothing to send. It may update the FD polling status to indicate
712 * !READY. It returns 0 if it fails in a fatal way or needs to poll to go
713 * further, otherwise it returns non-zero and removes the CO_FL_WAIT_L4_CONN
714 * flag from the connection's flags. In case of error, it sets CO_FL_ERROR and
715 * leaves the error code in errno.
716 */
717int sock_conn_check(struct connection *conn)
718{
719 struct sockaddr_storage *addr;
720 int fd = conn->handle.fd;
721
722 if (conn->flags & CO_FL_ERROR)
723 return 0;
724
725 if (!conn_ctrl_ready(conn))
726 return 0;
727
728 if (!(conn->flags & CO_FL_WAIT_L4_CONN))
729 return 1; /* strange we were called while ready */
730
Willy Tarreau5a9c6372021-07-06 08:29:20 +0200731 if (!fd_send_ready(fd) && !(fdtab[fd].state & (FD_POLL_ERR|FD_POLL_HUP)))
Willy Tarreau586f71b2020-12-11 15:54:36 +0100732 return 0;
733
734 /* Here we have 2 cases :
735 * - modern pollers, able to report ERR/HUP. If these ones return any
736 * of these flags then it's likely a failure, otherwise it possibly
737 * is a success (i.e. there may have been data received just before
738 * the error was reported).
739 * - select, which doesn't report these and with which it's always
740 * necessary either to try connect() again or to check for SO_ERROR.
741 * In order to simplify everything, we double-check using connect() as
742 * soon as we meet either of these delicate situations. Note that
743 * SO_ERROR would clear the error after reporting it!
744 */
745 if (cur_poller.flags & HAP_POLL_F_ERRHUP) {
746 /* modern poller, able to report ERR/HUP */
Willy Tarreauf5090652021-04-06 17:23:40 +0200747 if ((fdtab[fd].state & (FD_POLL_IN|FD_POLL_ERR|FD_POLL_HUP)) == FD_POLL_IN)
Willy Tarreau586f71b2020-12-11 15:54:36 +0100748 goto done;
Willy Tarreauf5090652021-04-06 17:23:40 +0200749 if ((fdtab[fd].state & (FD_POLL_OUT|FD_POLL_ERR|FD_POLL_HUP)) == FD_POLL_OUT)
Willy Tarreau586f71b2020-12-11 15:54:36 +0100750 goto done;
Willy Tarreauf5090652021-04-06 17:23:40 +0200751 if (!(fdtab[fd].state & (FD_POLL_ERR|FD_POLL_HUP)))
Willy Tarreau586f71b2020-12-11 15:54:36 +0100752 goto wait;
753 /* error present, fall through common error check path */
754 }
755
756 /* Use connect() to check the state of the socket. This has the double
757 * advantage of *not* clearing the error (so that health checks can
758 * still use getsockopt(SO_ERROR)) and giving us the following info :
759 * - error
760 * - connecting (EALREADY, EINPROGRESS)
761 * - connected (EISCONN, 0)
762 */
763 addr = conn->dst;
764 if ((conn->flags & CO_FL_SOCKS4) && obj_type(conn->target) == OBJ_TYPE_SERVER)
765 addr = &objt_server(conn->target)->socks4_addr;
766
767 if (connect(fd, (const struct sockaddr *)addr, get_addr_len(addr)) == -1) {
768 if (errno == EALREADY || errno == EINPROGRESS)
769 goto wait;
770
771 if (errno && errno != EISCONN)
772 goto out_error;
773 }
774
775 done:
776 /* The FD is ready now, we'll mark the connection as complete and
777 * forward the event to the transport layer which will notify the
778 * data layer.
779 */
780 conn->flags &= ~CO_FL_WAIT_L4_CONN;
781 fd_may_send(fd);
782 fd_cond_recv(fd);
783 errno = 0; // make health checks happy
784 return 1;
785
786 out_error:
787 /* Write error on the file descriptor. Report it to the connection
788 * and disable polling on this FD.
789 */
Willy Tarreau586f71b2020-12-11 15:54:36 +0100790 conn->flags |= CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH;
Willy Tarreaub41a6e92021-04-06 17:49:19 +0200791 HA_ATOMIC_AND(&fdtab[fd].state, ~FD_LINGER_RISK);
Willy Tarreau586f71b2020-12-11 15:54:36 +0100792 fd_stop_both(fd);
793 return 0;
794
795 wait:
796 fd_cant_send(fd);
797 fd_want_send(fd);
798 return 0;
799}
800
801/* I/O callback for fd-based connections. It calls the read/write handlers
802 * provided by the connection's sock_ops, which must be valid.
803 */
804void sock_conn_iocb(int fd)
805{
806 struct connection *conn = fdtab[fd].owner;
807 unsigned int flags;
808 int need_wake = 0;
809
810 if (unlikely(!conn)) {
811 activity[tid].conn_dead++;
812 return;
813 }
814
815 flags = conn->flags & ~CO_FL_ERROR; /* ensure to call the wake handler upon error */
816
817 if (unlikely(conn->flags & CO_FL_WAIT_L4_CONN) &&
818 ((fd_send_ready(fd) && fd_send_active(fd)) ||
819 (fd_recv_ready(fd) && fd_recv_active(fd)))) {
820 /* Still waiting for a connection to establish and nothing was
821 * attempted yet to probe the connection. this will clear the
822 * CO_FL_WAIT_L4_CONN flag on success.
823 */
824 if (!sock_conn_check(conn))
825 goto leave;
826 need_wake = 1;
827 }
828
829 if (fd_send_ready(fd) && fd_send_active(fd)) {
830 /* force reporting of activity by clearing the previous flags :
831 * we'll have at least ERROR or CONNECTED at the end of an I/O,
832 * both of which will be detected below.
833 */
834 flags = 0;
835 if (conn->subs && conn->subs->events & SUB_RETRY_SEND) {
836 need_wake = 0; // wake will be called after this I/O
837 tasklet_wakeup(conn->subs->tasklet);
838 conn->subs->events &= ~SUB_RETRY_SEND;
839 if (!conn->subs->events)
840 conn->subs = NULL;
841 }
842 fd_stop_send(fd);
843 }
844
845 /* The data transfer starts here and stops on error and handshakes. Note
846 * that we must absolutely test conn->xprt at each step in case it suddenly
847 * changes due to a quick unexpected close().
848 */
849 if (fd_recv_ready(fd) && fd_recv_active(fd)) {
850 /* force reporting of activity by clearing the previous flags :
851 * we'll have at least ERROR or CONNECTED at the end of an I/O,
852 * both of which will be detected below.
853 */
854 flags = 0;
855 if (conn->subs && conn->subs->events & SUB_RETRY_RECV) {
856 need_wake = 0; // wake will be called after this I/O
857 tasklet_wakeup(conn->subs->tasklet);
858 conn->subs->events &= ~SUB_RETRY_RECV;
859 if (!conn->subs->events)
860 conn->subs = NULL;
861 }
862 fd_stop_recv(fd);
863 }
864
865 leave:
866 /* we may have to finish to install a mux or to wake it up based on
867 * what was just done above. It may kill the connection so we have to
868 * be prpared not to use it anymore.
869 */
870 if (conn_notify_mux(conn, flags, need_wake) < 0)
871 return;
872
873 /* commit polling changes in case of error.
874 * WT: it seems that the last case where this could still be relevant
875 * is if a mux wake function above report a connection error but does
876 * not stop polling. Shouldn't we enforce this into the mux instead of
877 * having to deal with this ?
878 */
879 if (unlikely(conn->flags & CO_FL_ERROR)) {
880 if (conn_ctrl_ready(conn))
881 fd_stop_both(fd);
882 }
883}
884
Willy Tarreau427c8462020-12-11 16:19:12 +0100885/* Drains possibly pending incoming data on the file descriptor attached to the
886 * connection. This is used to know whether we need to disable lingering on
887 * close. Returns non-zero if it is safe to close without disabling lingering,
888 * otherwise zero.
889 */
890int sock_drain(struct connection *conn)
891{
892 int turns = 2;
893 int fd = conn->handle.fd;
894 int len;
895
Willy Tarreauf5090652021-04-06 17:23:40 +0200896 if (fdtab[fd].state & (FD_POLL_ERR|FD_POLL_HUP))
Willy Tarreau427c8462020-12-11 16:19:12 +0100897 goto shut;
898
Willy Tarreau20b622e2021-10-21 21:31:42 +0200899 if (!(conn->flags & CO_FL_WANT_DRAIN) && !fd_recv_ready(fd))
Willy Tarreau427c8462020-12-11 16:19:12 +0100900 return 0;
901
902 /* no drain function defined, use the generic one */
903
904 while (turns) {
905#ifdef MSG_TRUNC_CLEARS_INPUT
906 len = recv(fd, NULL, INT_MAX, MSG_DONTWAIT | MSG_NOSIGNAL | MSG_TRUNC);
907 if (len == -1 && errno == EFAULT)
908#endif
909 len = recv(fd, trash.area, trash.size, MSG_DONTWAIT | MSG_NOSIGNAL);
910
911 if (len == 0)
912 goto shut;
913
914 if (len < 0) {
915 if (errno == EAGAIN) {
916 /* connection not closed yet */
917 fd_cant_recv(fd);
918 break;
919 }
920 if (errno == EINTR) /* oops, try again */
921 continue;
922 /* other errors indicate a dead connection, fine. */
923 goto shut;
924 }
925 /* OK we read some data, let's try again once */
926 turns--;
927 }
928
929 /* some data are still present, give up */
930 return 0;
931
932 shut:
933 /* we're certain the connection was shut down */
Willy Tarreaub41a6e92021-04-06 17:49:19 +0200934 HA_ATOMIC_AND(&fdtab[fd].state, ~FD_LINGER_RISK);
Willy Tarreau427c8462020-12-11 16:19:12 +0100935 return 1;
936}
937
Willy Tarreau472125b2020-12-11 17:02:50 +0100938/* Checks the connection's FD for readiness of events <event_type>, which may
939 * only be a combination of SUB_RETRY_RECV and SUB_RETRY_SEND. Those which are
940 * ready are returned. The ones that are not ready are enabled. The caller is
941 * expected to do what is needed to handle ready events and to deal with
942 * subsequent wakeups caused by the requested events' readiness.
943 */
944int sock_check_events(struct connection *conn, int event_type)
945{
946 int ret = 0;
947
948 if (event_type & SUB_RETRY_RECV) {
949 if (fd_recv_ready(conn->handle.fd))
950 ret |= SUB_RETRY_RECV;
951 else
952 fd_want_recv(conn->handle.fd);
953 }
954
955 if (event_type & SUB_RETRY_SEND) {
956 if (fd_send_ready(conn->handle.fd))
957 ret |= SUB_RETRY_SEND;
958 else
959 fd_want_send(conn->handle.fd);
960 }
961
962 return ret;
963}
964
965/* Ignore readiness events from connection's FD for events of types <event_type>
966 * which may only be a combination of SUB_RETRY_RECV and SUB_RETRY_SEND.
967 */
968void sock_ignore_events(struct connection *conn, int event_type)
969{
970 if (event_type & SUB_RETRY_RECV)
971 fd_stop_recv(conn->handle.fd);
972
973 if (event_type & SUB_RETRY_SEND)
974 fd_stop_send(conn->handle.fd);
975}
976
Willy Tarreau18b7df72020-08-28 12:07:22 +0200977/*
978 * Local variables:
979 * c-indent-level: 8
980 * c-basic-offset: 8
981 * End:
982 */