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