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