1 /*
2 * AF_INET/AF_INET6 SOCK_STREAM protocol layer (tcp)
3 *
4 * Copyright 2000-2013 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
13 /* this is to have tcp_info defined on systems using musl
14 * library, such as Alpine Linux
15 */
16 #define _GNU_SOURCE
17
18 #include <ctype.h>
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <time.h>
25
26 #include <sys/param.h>
27 #include <sys/socket.h>
28 #include <sys/types.h>
29
30 #include <netinet/tcp.h>
31 #include <netinet/in.h>
32
33 #include <common/compat.h>
34 #include <common/config.h>
35 #include <common/debug.h>
36 #include <common/errors.h>
37 #include <common/initcall.h>
38 #include <common/mini-clist.h>
39 #include <common/standard.h>
40 #include <common/namespace.h>
41
42 #include <types/action.h>
43 #include <types/connection.h>
44 #include <types/global.h>
45 #include <types/stream.h>
46
47 #include <proto/arg.h>
48 #include <proto/channel.h>
49 #include <proto/connection.h>
50 #include <proto/fd.h>
51 #include <proto/http_rules.h>
52 #include <proto/listener.h>
53 #include <proto/log.h>
54 #include <proto/port_range.h>
55 #include <proto/protocol.h>
56 #include <proto/http_ana.h>
57 #include <proto/proto_tcp.h>
58 #include <proto/proxy.h>
59 #include <proto/sample.h>
60 #include <proto/server.h>
61 #include <proto/task.h>
62 #include <proto/tcp_rules.h>
63
64 static int tcp_bind_listeners(struct protocol *proto, char *errmsg, int errlen);
65 static int tcp_bind_listener(struct listener *listener, char *errmsg, int errlen);
66 static void tcpv4_add_listener(struct listener *listener, int port);
67 static void tcpv6_add_listener(struct listener *listener, int port);
68
69 /* Note: must not be declared <const> as its list will be overwritten */
70 static struct protocol proto_tcpv4 = {
71 .name = "tcpv4",
72 .sock_domain = AF_INET,
73 .sock_type = SOCK_STREAM,
74 .sock_prot = IPPROTO_TCP,
75 .sock_family = AF_INET,
76 .sock_addrlen = sizeof(struct sockaddr_in),
77 .l3_addrlen = 32/8,
78 .accept = &listener_accept,
79 .connect = tcp_connect_server,
80 .bind = tcp_bind_listener,
81 .bind_all = tcp_bind_listeners,
82 .unbind_all = unbind_all_listeners,
83 .enable_all = enable_all_listeners,
84 .get_src = tcp_get_src,
85 .get_dst = tcp_get_dst,
86 .pause = tcp_pause_listener,
87 .add = tcpv4_add_listener,
88 .listeners = LIST_HEAD_INIT(proto_tcpv4.listeners),
89 .nb_listeners = 0,
90 };
91
92 INITCALL1(STG_REGISTER, protocol_register, &proto_tcpv4);
93
94 /* Note: must not be declared <const> as its list will be overwritten */
95 static struct protocol proto_tcpv6 = {
96 .name = "tcpv6",
97 .sock_domain = AF_INET6,
98 .sock_type = SOCK_STREAM,
99 .sock_prot = IPPROTO_TCP,
100 .sock_family = AF_INET6,
101 .sock_addrlen = sizeof(struct sockaddr_in6),
102 .l3_addrlen = 128/8,
103 .accept = &listener_accept,
104 .connect = tcp_connect_server,
105 .bind = tcp_bind_listener,
106 .bind_all = tcp_bind_listeners,
107 .unbind_all = unbind_all_listeners,
108 .enable_all = enable_all_listeners,
109 .get_src = tcp_get_src,
110 .get_dst = tcp_get_dst,
111 .pause = tcp_pause_listener,
112 .add = tcpv6_add_listener,
113 .listeners = LIST_HEAD_INIT(proto_tcpv6.listeners),
114 .nb_listeners = 0,
115 };
116
117 INITCALL1(STG_REGISTER, protocol_register, &proto_tcpv6);
118
119 /* Default TCP parameters, got by opening a temporary TCP socket. */
120 #ifdef TCP_MAXSEG
121 static THREAD_LOCAL int default_tcp_maxseg = -1;
122 static THREAD_LOCAL int default_tcp6_maxseg = -1;
123 #endif
124
125 /* Binds ipv4/ipv6 address <local> to socket <fd>, unless <flags> is set, in which
126 * case we try to bind <remote>. <flags> is a 2-bit field consisting of :
127 * - 0 : ignore remote address (may even be a NULL pointer)
128 * - 1 : use provided address
129 * - 2 : use provided port
130 * - 3 : use both
131 *
132 * The function supports multiple foreign binding methods :
133 * - linux_tproxy: we directly bind to the foreign address
134 * The second one can be used as a fallback for the first one.
135 * This function returns 0 when everything's OK, 1 if it could not bind, to the
136 * local address, 2 if it could not bind to the foreign address.
137 */
tcp_bind_socket(int fd,int flags,struct sockaddr_storage * local,struct sockaddr_storage * remote)138 int tcp_bind_socket(int fd, int flags, struct sockaddr_storage *local, struct sockaddr_storage *remote)
139 {
140 struct sockaddr_storage bind_addr;
141 int foreign_ok = 0;
142 int ret;
143 static THREAD_LOCAL int ip_transp_working = 1;
144 static THREAD_LOCAL int ip6_transp_working = 1;
145
146 switch (local->ss_family) {
147 case AF_INET:
148 if (flags && ip_transp_working) {
149 /* This deserves some explanation. Some platforms will support
150 * multiple combinations of certain methods, so we try the
151 * supported ones until one succeeds.
152 */
153 if (0
154 #if defined(IP_TRANSPARENT)
155 || (setsockopt(fd, SOL_IP, IP_TRANSPARENT, &one, sizeof(one)) == 0)
156 #endif
157 #if defined(IP_FREEBIND)
158 || (setsockopt(fd, SOL_IP, IP_FREEBIND, &one, sizeof(one)) == 0)
159 #endif
160 #if defined(IP_BINDANY)
161 || (setsockopt(fd, IPPROTO_IP, IP_BINDANY, &one, sizeof(one)) == 0)
162 #endif
163 #if defined(SO_BINDANY)
164 || (setsockopt(fd, SOL_SOCKET, SO_BINDANY, &one, sizeof(one)) == 0)
165 #endif
166 )
167 foreign_ok = 1;
168 else
169 ip_transp_working = 0;
170 }
171 break;
172 case AF_INET6:
173 if (flags && ip6_transp_working) {
174 if (0
175 #if defined(IPV6_TRANSPARENT) && defined(SOL_IPV6)
176 || (setsockopt(fd, SOL_IPV6, IPV6_TRANSPARENT, &one, sizeof(one)) == 0)
177 #endif
178 #if defined(IP_FREEBIND)
179 || (setsockopt(fd, SOL_IP, IP_FREEBIND, &one, sizeof(one)) == 0)
180 #endif
181 #if defined(IPV6_BINDANY)
182 || (setsockopt(fd, IPPROTO_IPV6, IPV6_BINDANY, &one, sizeof(one)) == 0)
183 #endif
184 #if defined(SO_BINDANY)
185 || (setsockopt(fd, SOL_SOCKET, SO_BINDANY, &one, sizeof(one)) == 0)
186 #endif
187 )
188 foreign_ok = 1;
189 else
190 ip6_transp_working = 0;
191 }
192 break;
193 }
194
195 if (flags) {
196 memset(&bind_addr, 0, sizeof(bind_addr));
197 bind_addr.ss_family = remote->ss_family;
198 switch (remote->ss_family) {
199 case AF_INET:
200 if (flags & 1)
201 ((struct sockaddr_in *)&bind_addr)->sin_addr = ((struct sockaddr_in *)remote)->sin_addr;
202 if (flags & 2)
203 ((struct sockaddr_in *)&bind_addr)->sin_port = ((struct sockaddr_in *)remote)->sin_port;
204 break;
205 case AF_INET6:
206 if (flags & 1)
207 ((struct sockaddr_in6 *)&bind_addr)->sin6_addr = ((struct sockaddr_in6 *)remote)->sin6_addr;
208 if (flags & 2)
209 ((struct sockaddr_in6 *)&bind_addr)->sin6_port = ((struct sockaddr_in6 *)remote)->sin6_port;
210 break;
211 default:
212 /* we don't want to try to bind to an unknown address family */
213 foreign_ok = 0;
214 }
215 }
216
217 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
218 if (foreign_ok) {
219 if (is_inet_addr(&bind_addr)) {
220 ret = bind(fd, (struct sockaddr *)&bind_addr, get_addr_len(&bind_addr));
221 if (ret < 0)
222 return 2;
223 }
224 }
225 else {
226 if (is_inet_addr(local)) {
227 ret = bind(fd, (struct sockaddr *)local, get_addr_len(local));
228 if (ret < 0)
229 return 1;
230 }
231 }
232
233 if (!flags)
234 return 0;
235
236 if (!foreign_ok)
237 /* we could not bind to a foreign address */
238 return 2;
239
240 return 0;
241 }
242
243 /* conn->dst MUST be valid */
create_server_socket(struct connection * conn)244 static int create_server_socket(struct connection *conn)
245 {
246 const struct netns_entry *ns = NULL;
247
248 #ifdef USE_NS
249 if (objt_server(conn->target)) {
250 if (__objt_server(conn->target)->flags & SRV_F_USE_NS_FROM_PP)
251 ns = conn->proxy_netns;
252 else
253 ns = __objt_server(conn->target)->netns;
254 }
255 #endif
256 return my_socketat(ns, conn->dst->ss_family, SOCK_STREAM, IPPROTO_TCP);
257 }
258
259 /*
260 * This function initiates a TCP connection establishment to the target assigned
261 * to connection <conn> using (si->{target,dst}). A source address may be
262 * pointed to by conn->src in case of transparent proxying. Normal source
263 * bind addresses are still determined locally (due to the possible need of a
264 * source port). conn->target may point either to a valid server or to a backend,
265 * depending on conn->target. Only OBJ_TYPE_PROXY and OBJ_TYPE_SERVER are
266 * supported. The <data> parameter is a boolean indicating whether there are data
267 * waiting for being sent or not, in order to adjust data write polling and on
268 * some platforms, the ability to avoid an empty initial ACK. The <flags> argument
269 * allows the caller to force using a delayed ACK when establishing the connection
270 * - 0 = no delayed ACK unless data are advertised and backend has tcp-smart-connect
271 * - CONNECT_DELACK_SMART_CONNECT = delayed ACK if backend has tcp-smart-connect, regardless of data
272 * - CONNECT_DELACK_ALWAYS = delayed ACK regardless of backend options
273 *
274 * Note that a pending send_proxy message accounts for data.
275 *
276 * It can return one of :
277 * - SF_ERR_NONE if everything's OK
278 * - SF_ERR_SRVTO if there are no more servers
279 * - SF_ERR_SRVCL if the connection was refused by the server
280 * - SF_ERR_PRXCOND if the connection has been limited by the proxy (maxconn)
281 * - SF_ERR_RESOURCE if a system resource is lacking (eg: fd limits, ports, ...)
282 * - SF_ERR_INTERNAL for any other purely internal errors
283 * Additionally, in the case of SF_ERR_RESOURCE, an emergency log will be emitted.
284 *
285 * The connection's fd is inserted only when SF_ERR_NONE is returned, otherwise
286 * it's invalid and the caller has nothing to do.
287 */
288
tcp_connect_server(struct connection * conn,int flags)289 int tcp_connect_server(struct connection *conn, int flags)
290 {
291 int fd;
292 struct server *srv;
293 struct proxy *be;
294 struct conn_src *src;
295 int use_fastopen = 0;
296 struct sockaddr_storage *addr;
297
298 conn->flags |= CO_FL_WAIT_L4_CONN; /* connection in progress */
299
300 switch (obj_type(conn->target)) {
301 case OBJ_TYPE_PROXY:
302 be = objt_proxy(conn->target);
303 srv = NULL;
304 break;
305 case OBJ_TYPE_SERVER:
306 srv = objt_server(conn->target);
307 be = srv->proxy;
308 /* Make sure we check that we have data before activating
309 * TFO, or we could trigger a kernel issue whereby after
310 * a successful connect() == 0, any subsequent connect()
311 * will return EINPROGRESS instead of EISCONN.
312 */
313 use_fastopen = (srv->flags & SRV_F_FASTOPEN) &&
314 ((flags & (CONNECT_CAN_USE_TFO | CONNECT_HAS_DATA)) ==
315 (CONNECT_CAN_USE_TFO | CONNECT_HAS_DATA));
316 break;
317 default:
318 conn->flags |= CO_FL_ERROR;
319 return SF_ERR_INTERNAL;
320 }
321
322 if (!conn->dst) {
323 conn->flags |= CO_FL_ERROR;
324 return SF_ERR_INTERNAL;
325 }
326
327 fd = conn->handle.fd = create_server_socket(conn);
328
329 if (fd == -1) {
330 qfprintf(stderr, "Cannot get a server socket.\n");
331
332 if (errno == ENFILE) {
333 conn->err_code = CO_ER_SYS_FDLIM;
334 send_log(be, LOG_EMERG,
335 "Proxy %s reached system FD limit (maxsock=%d). Please check system tunables.\n",
336 be->id, global.maxsock);
337 }
338 else if (errno == EMFILE) {
339 conn->err_code = CO_ER_PROC_FDLIM;
340 send_log(be, LOG_EMERG,
341 "Proxy %s reached process FD limit (maxsock=%d). Please check 'ulimit-n' and restart.\n",
342 be->id, global.maxsock);
343 }
344 else if (errno == ENOBUFS || errno == ENOMEM) {
345 conn->err_code = CO_ER_SYS_MEMLIM;
346 send_log(be, LOG_EMERG,
347 "Proxy %s reached system memory limit (maxsock=%d). Please check system tunables.\n",
348 be->id, global.maxsock);
349 }
350 else if (errno == EAFNOSUPPORT || errno == EPROTONOSUPPORT) {
351 conn->err_code = CO_ER_NOPROTO;
352 }
353 else
354 conn->err_code = CO_ER_SOCK_ERR;
355
356 /* this is a resource error */
357 conn->flags |= CO_FL_ERROR;
358 return SF_ERR_RESOURCE;
359 }
360
361 if (fd >= global.maxsock) {
362 /* do not log anything there, it's a normal condition when this option
363 * is used to serialize connections to a server !
364 */
365 ha_alert("socket(): not enough free sockets. Raise -n argument. Giving up.\n");
366 close(fd);
367 conn->err_code = CO_ER_CONF_FDLIM;
368 conn->flags |= CO_FL_ERROR;
369 return SF_ERR_PRXCOND; /* it is a configuration limit */
370 }
371
372 if ((fcntl(fd, F_SETFL, O_NONBLOCK)==-1) ||
373 (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)) == -1)) {
374 qfprintf(stderr,"Cannot set client socket to non blocking mode.\n");
375 close(fd);
376 conn->err_code = CO_ER_SOCK_ERR;
377 conn->flags |= CO_FL_ERROR;
378 return SF_ERR_INTERNAL;
379 }
380
381 if (master == 1 && (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)) {
382 ha_alert("Cannot set CLOEXEC on client socket.\n");
383 close(fd);
384 conn->err_code = CO_ER_SOCK_ERR;
385 conn->flags |= CO_FL_ERROR;
386 return SF_ERR_INTERNAL;
387 }
388
389 if (be->options & PR_O_TCP_SRV_KA)
390 setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one));
391
392 /* allow specific binding :
393 * - server-specific at first
394 * - proxy-specific next
395 */
396 if (srv && srv->conn_src.opts & CO_SRC_BIND)
397 src = &srv->conn_src;
398 else if (be->conn_src.opts & CO_SRC_BIND)
399 src = &be->conn_src;
400 else
401 src = NULL;
402
403 if (src) {
404 int ret, flags = 0;
405
406 if (conn->src && is_inet_addr(conn->src)) {
407 switch (src->opts & CO_SRC_TPROXY_MASK) {
408 case CO_SRC_TPROXY_CLI:
409 conn->flags |= CO_FL_PRIVATE;
410 /* fall through */
411 case CO_SRC_TPROXY_ADDR:
412 flags = 3;
413 break;
414 case CO_SRC_TPROXY_CIP:
415 case CO_SRC_TPROXY_DYN:
416 conn->flags |= CO_FL_PRIVATE;
417 flags = 1;
418 break;
419 }
420 }
421
422 #ifdef SO_BINDTODEVICE
423 /* Note: this might fail if not CAP_NET_RAW */
424 if (src->iface_name)
425 setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, src->iface_name, src->iface_len + 1);
426 #endif
427
428 if (src->sport_range) {
429 int attempts = 10; /* should be more than enough to find a spare port */
430 struct sockaddr_storage sa;
431
432 ret = 1;
433 memcpy(&sa, &src->source_addr, sizeof(sa));
434
435 do {
436 /* note: in case of retry, we may have to release a previously
437 * allocated port, hence this loop's construct.
438 */
439 port_range_release_port(fdinfo[fd].port_range, fdinfo[fd].local_port);
440 fdinfo[fd].port_range = NULL;
441
442 if (!attempts)
443 break;
444 attempts--;
445
446 fdinfo[fd].local_port = port_range_alloc_port(src->sport_range);
447 if (!fdinfo[fd].local_port) {
448 conn->err_code = CO_ER_PORT_RANGE;
449 break;
450 }
451
452 fdinfo[fd].port_range = src->sport_range;
453 set_host_port(&sa, fdinfo[fd].local_port);
454
455 ret = tcp_bind_socket(fd, flags, &sa, conn->src);
456 if (ret != 0)
457 conn->err_code = CO_ER_CANT_BIND;
458 } while (ret != 0); /* binding NOK */
459 }
460 else {
461 #ifdef IP_BIND_ADDRESS_NO_PORT
462 static THREAD_LOCAL int bind_address_no_port = 1;
463 setsockopt(fd, SOL_IP, IP_BIND_ADDRESS_NO_PORT, (const void *) &bind_address_no_port, sizeof(int));
464 #endif
465 ret = tcp_bind_socket(fd, flags, &src->source_addr, conn->src);
466 if (ret != 0)
467 conn->err_code = CO_ER_CANT_BIND;
468 }
469
470 if (unlikely(ret != 0)) {
471 port_range_release_port(fdinfo[fd].port_range, fdinfo[fd].local_port);
472 fdinfo[fd].port_range = NULL;
473 close(fd);
474
475 if (ret == 1) {
476 ha_alert("Cannot bind to source address before connect() for backend %s. Aborting.\n",
477 be->id);
478 send_log(be, LOG_EMERG,
479 "Cannot bind to source address before connect() for backend %s.\n",
480 be->id);
481 } else {
482 ha_alert("Cannot bind to tproxy source address before connect() for backend %s. Aborting.\n",
483 be->id);
484 send_log(be, LOG_EMERG,
485 "Cannot bind to tproxy source address before connect() for backend %s.\n",
486 be->id);
487 }
488 conn->flags |= CO_FL_ERROR;
489 return SF_ERR_RESOURCE;
490 }
491 }
492
493 #if defined(TCP_QUICKACK)
494 /* disabling tcp quick ack now allows the first request to leave the
495 * machine with the first ACK. We only do this if there are pending
496 * data in the buffer.
497 */
498 if (flags & (CONNECT_DELACK_ALWAYS) ||
499 ((flags & CONNECT_DELACK_SMART_CONNECT ||
500 (flags & CONNECT_HAS_DATA) || conn->send_proxy_ofs) &&
501 (be->options2 & PR_O2_SMARTCON)))
502 setsockopt(fd, IPPROTO_TCP, TCP_QUICKACK, &zero, sizeof(zero));
503 #endif
504
505 #ifdef TCP_USER_TIMEOUT
506 /* there is not much more we can do here when it fails, it's still minor */
507 if (srv && srv->tcp_ut)
508 setsockopt(fd, IPPROTO_TCP, TCP_USER_TIMEOUT, &srv->tcp_ut, sizeof(srv->tcp_ut));
509 #endif
510
511 if (use_fastopen) {
512 #if defined(TCP_FASTOPEN_CONNECT)
513 setsockopt(fd, IPPROTO_TCP, TCP_FASTOPEN_CONNECT, &one, sizeof(one));
514 #endif
515 }
516 if (global.tune.server_sndbuf)
517 setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &global.tune.server_sndbuf, sizeof(global.tune.server_sndbuf));
518
519 if (global.tune.server_rcvbuf)
520 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &global.tune.server_rcvbuf, sizeof(global.tune.server_rcvbuf));
521
522 addr = (conn->flags & CO_FL_SOCKS4) ? &srv->socks4_addr : conn->dst;
523 if (connect(fd, (const struct sockaddr *)addr, get_addr_len(addr)) == -1) {
524 if (errno == EINPROGRESS || errno == EALREADY) {
525 /* common case, let's wait for connect status */
526 conn->flags |= CO_FL_WAIT_L4_CONN;
527 }
528 else if (errno == EISCONN) {
529 /* should normally not happen but if so, indicates that it's OK */
530 conn->flags &= ~CO_FL_WAIT_L4_CONN;
531 }
532 else if (errno == EAGAIN || errno == EADDRINUSE || errno == EADDRNOTAVAIL) {
533 char *msg;
534 if (errno == EAGAIN || errno == EADDRNOTAVAIL) {
535 msg = "no free ports";
536 conn->err_code = CO_ER_FREE_PORTS;
537 }
538 else {
539 msg = "local address already in use";
540 conn->err_code = CO_ER_ADDR_INUSE;
541 }
542
543 qfprintf(stderr,"Connect() failed for backend %s: %s.\n", be->id, msg);
544 port_range_release_port(fdinfo[fd].port_range, fdinfo[fd].local_port);
545 fdinfo[fd].port_range = NULL;
546 close(fd);
547 send_log(be, LOG_ERR, "Connect() failed for backend %s: %s.\n", be->id, msg);
548 conn->flags |= CO_FL_ERROR;
549 return SF_ERR_RESOURCE;
550 } else if (errno == ETIMEDOUT) {
551 //qfprintf(stderr,"Connect(): ETIMEDOUT");
552 port_range_release_port(fdinfo[fd].port_range, fdinfo[fd].local_port);
553 fdinfo[fd].port_range = NULL;
554 close(fd);
555 conn->err_code = CO_ER_SOCK_ERR;
556 conn->flags |= CO_FL_ERROR;
557 return SF_ERR_SRVTO;
558 } else {
559 // (errno == ECONNREFUSED || errno == ENETUNREACH || errno == EACCES || errno == EPERM)
560 //qfprintf(stderr,"Connect(): %d", errno);
561 port_range_release_port(fdinfo[fd].port_range, fdinfo[fd].local_port);
562 fdinfo[fd].port_range = NULL;
563 close(fd);
564 conn->err_code = CO_ER_SOCK_ERR;
565 conn->flags |= CO_FL_ERROR;
566 return SF_ERR_SRVCL;
567 }
568 }
569 else {
570 /* connect() == 0, this is great! */
571 conn->flags &= ~CO_FL_WAIT_L4_CONN;
572 }
573
574 conn->flags |= CO_FL_ADDR_TO_SET;
575
576 conn_ctrl_init(conn); /* registers the FD */
577 fdtab[fd].linger_risk = 1; /* close hard if needed */
578
579 if (conn->flags & CO_FL_WAIT_L4_CONN)
580 fd_cant_recv(fd); // we'll change this once the connection is validated
581
582 if (conn_xprt_init(conn) < 0) {
583 conn_full_close(conn);
584 conn->flags |= CO_FL_ERROR;
585 return SF_ERR_RESOURCE;
586 }
587
588 conn_xprt_want_send(conn); /* for connect status, proxy protocol or SSL */
589 return SF_ERR_NONE; /* connection is OK */
590 }
591
592
593 /*
594 * Retrieves the source address for the socket <fd>, with <dir> indicating
595 * if we're a listener (=0) or an initiator (!=0). It returns 0 in case of
596 * success, -1 in case of error. The socket's source address is stored in
597 * <sa> for <salen> bytes.
598 */
tcp_get_src(int fd,struct sockaddr * sa,socklen_t salen,int dir)599 int tcp_get_src(int fd, struct sockaddr *sa, socklen_t salen, int dir)
600 {
601 if (dir)
602 return getsockname(fd, sa, &salen);
603 else
604 return getpeername(fd, sa, &salen);
605 }
606
607
608 /*
609 * Retrieves the original destination address for the socket <fd>, with <dir>
610 * indicating if we're a listener (=0) or an initiator (!=0). In the case of a
611 * listener, if the original destination address was translated, the original
612 * address is retrieved. It returns 0 in case of success, -1 in case of error.
613 * The socket's source address is stored in <sa> for <salen> bytes.
614 */
tcp_get_dst(int fd,struct sockaddr * sa,socklen_t salen,int dir)615 int tcp_get_dst(int fd, struct sockaddr *sa, socklen_t salen, int dir)
616 {
617 if (dir)
618 return getpeername(fd, sa, &salen);
619 else {
620 int ret = getsockname(fd, sa, &salen);
621
622 if (ret < 0)
623 return ret;
624
625 #if defined(USE_TPROXY) && defined(SO_ORIGINAL_DST)
626 /* For TPROXY and Netfilter's NAT, we can retrieve the original
627 * IPv4 address before DNAT/REDIRECT. We must not do that with
628 * other families because v6-mapped IPv4 addresses are still
629 * reported as v4.
630 */
631 if (((struct sockaddr_storage *)sa)->ss_family == AF_INET
632 && getsockopt(fd, SOL_IP, SO_ORIGINAL_DST, sa, &salen) == 0)
633 return 0;
634 #endif
635 return ret;
636 }
637 }
638
639 /* This is the callback which is set when a connection establishment is pending
640 * and we have nothing to send. It updates the FD polling status. It returns 0
641 * if it fails in a fatal way or needs to poll to go further, otherwise it
642 * returns non-zero and removes the CO_FL_WAIT_L4_CONN flag from the connection's
643 * flags. In case of error, it sets CO_FL_ERROR and leaves the error code in
644 * errno. The error checking is done in two passes in order to limit the number
645 * of syscalls in the normal case :
646 * - if POLL_ERR was reported by the poller, we check for a pending error on
647 * the socket before proceeding. If found, it's assigned to errno so that
648 * upper layers can see it.
649 * - otherwise connect() is used to check the connection state again, since
650 * the getsockopt return cannot reliably be used to know if the connection
651 * is still pending or ready. This one may often return an error as well,
652 * since we don't always have POLL_ERR (eg: OSX or cached events).
653 */
tcp_connect_probe(struct connection * conn)654 int tcp_connect_probe(struct connection *conn)
655 {
656 struct sockaddr_storage *addr;
657 int fd = conn->handle.fd;
658 socklen_t lskerr;
659 int skerr;
660
661 if (conn->flags & CO_FL_ERROR)
662 return 0;
663
664 if (!conn_ctrl_ready(conn))
665 return 0;
666
667 if (!(conn->flags & CO_FL_WAIT_L4_CONN))
668 return 1; /* strange we were called while ready */
669
670 if (!fd_send_ready(fd))
671 return 0;
672
673 /* we might be the first witness of FD_POLL_ERR. Note that FD_POLL_HUP
674 * without FD_POLL_IN also indicates a hangup without input data meaning
675 * there was no connection.
676 */
677 if (fdtab[fd].ev & FD_POLL_ERR ||
678 (fdtab[fd].ev & (FD_POLL_IN|FD_POLL_HUP)) == FD_POLL_HUP) {
679 skerr = 0;
680 lskerr = sizeof(skerr);
681 getsockopt(fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr);
682 errno = skerr;
683 if (errno == EAGAIN)
684 errno = 0;
685 if (errno)
686 goto out_error;
687 }
688
689 /* Use connect() to check the state of the socket. This has the
690 * advantage of giving us the following info :
691 * - error
692 * - connecting (EALREADY, EINPROGRESS)
693 * - connected (EISCONN, 0)
694 */
695 addr = conn->dst;
696 if ((conn->flags & CO_FL_SOCKS4) && obj_type(conn->target) == OBJ_TYPE_SERVER)
697 addr = &objt_server(conn->target)->socks4_addr;
698
699 if (connect(fd, (const struct sockaddr *)addr, get_addr_len(addr)) == -1) {
700 if (errno == EALREADY || errno == EINPROGRESS) {
701 __conn_xprt_want_send(conn);
702 fd_cant_send(fd);
703 return 0;
704 }
705
706 if (errno && errno != EISCONN)
707 goto out_error;
708
709 /* otherwise we're connected */
710 }
711
712 /* The FD is ready now, we'll mark the connection as complete and
713 * forward the event to the transport layer which will notify the
714 * data layer.
715 */
716 conn->flags &= ~CO_FL_WAIT_L4_CONN;
717 fd_may_send(fd);
718 fd_cond_recv(fd);
719 return 1;
720
721 out_error:
722 /* Write error on the file descriptor. Report it to the connection
723 * and disable polling on this FD.
724 */
725 fdtab[fd].linger_risk = 0;
726 conn->flags |= CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH;
727 __conn_xprt_stop_both(conn);
728 return 0;
729 }
730
731 /* XXX: Should probably be elsewhere */
compare_sockaddr(struct sockaddr_storage * a,struct sockaddr_storage * b)732 static int compare_sockaddr(struct sockaddr_storage *a, struct sockaddr_storage *b)
733 {
734 if (a->ss_family != b->ss_family) {
735 return (-1);
736 }
737 switch (a->ss_family) {
738 case AF_INET:
739 {
740 struct sockaddr_in *a4 = (void *)a, *b4 = (void *)b;
741 if (a4->sin_port != b4->sin_port)
742 return (-1);
743 return (memcmp(&a4->sin_addr, &b4->sin_addr,
744 sizeof(a4->sin_addr)));
745 }
746 case AF_INET6:
747 {
748 struct sockaddr_in6 *a6 = (void *)a, *b6 = (void *)b;
749 if (a6->sin6_port != b6->sin6_port)
750 return (-1);
751 return (memcmp(&a6->sin6_addr, &b6->sin6_addr,
752 sizeof(a6->sin6_addr)));
753 }
754 default:
755 return (-1);
756 }
757
758 }
759
760 #define LI_MANDATORY_FLAGS (LI_O_FOREIGN | LI_O_V6ONLY | LI_O_V4V6)
761 /* When binding the listeners, check if a socket has been sent to us by the
762 * previous process that we could reuse, instead of creating a new one.
763 */
tcp_find_compatible_fd(struct listener * l)764 static int tcp_find_compatible_fd(struct listener *l)
765 {
766 struct xfer_sock_list *xfer_sock = xfer_sock_list;
767 int ret = -1;
768
769 while (xfer_sock) {
770 if (!compare_sockaddr(&xfer_sock->addr, &l->addr)) {
771 if ((l->interface == NULL && xfer_sock->iface == NULL) ||
772 (l->interface != NULL && xfer_sock->iface != NULL &&
773 !strcmp(l->interface, xfer_sock->iface))) {
774 if ((l->options & LI_MANDATORY_FLAGS) ==
775 (xfer_sock->options & LI_MANDATORY_FLAGS)) {
776 if ((xfer_sock->namespace == NULL &&
777 l->netns == NULL)
778 #ifdef USE_NS
779 || (xfer_sock->namespace != NULL &&
780 l->netns != NULL &&
781 !strcmp(xfer_sock->namespace,
782 l->netns->node.key))
783 #endif
784 ) {
785 break;
786 }
787
788 }
789 }
790 }
791 xfer_sock = xfer_sock->next;
792 }
793 if (xfer_sock != NULL) {
794 ret = xfer_sock->fd;
795 if (xfer_sock == xfer_sock_list)
796 xfer_sock_list = xfer_sock->next;
797 if (xfer_sock->prev)
798 xfer_sock->prev->next = xfer_sock->next;
799 if (xfer_sock->next)
800 xfer_sock->next->prev = xfer_sock->prev;
801 free(xfer_sock->iface);
802 free(xfer_sock->namespace);
803 free(xfer_sock);
804 }
805 return ret;
806 }
807 #undef L1_MANDATORY_FLAGS
808
809 /* This function tries to bind a TCPv4/v6 listener. It may return a warning or
810 * an error message in <errmsg> if the message is at most <errlen> bytes long
811 * (including '\0'). Note that <errmsg> may be NULL if <errlen> is also zero.
812 * The return value is composed from ERR_ABORT, ERR_WARN,
813 * ERR_ALERT, ERR_RETRYABLE and ERR_FATAL. ERR_NONE indicates that everything
814 * was alright and that no message was returned. ERR_RETRYABLE means that an
815 * error occurred but that it may vanish after a retry (eg: port in use), and
816 * ERR_FATAL indicates a non-fixable error. ERR_WARN and ERR_ALERT do not alter
817 * the meaning of the error, but just indicate that a message is present which
818 * should be displayed with the respective level. Last, ERR_ABORT indicates
819 * that it's pointless to try to start other listeners. No error message is
820 * returned if errlen is NULL.
821 */
tcp_bind_listener(struct listener * listener,char * errmsg,int errlen)822 int tcp_bind_listener(struct listener *listener, char *errmsg, int errlen)
823 {
824 __label__ tcp_return, tcp_close_return;
825 int fd, err;
826 int ext, ready;
827 socklen_t ready_len;
828 const char *msg = NULL;
829 #ifdef TCP_MAXSEG
830
831 /* Create a temporary TCP socket to get default parameters we can't
832 * guess.
833 * */
834 ready_len = sizeof(default_tcp_maxseg);
835 if (default_tcp_maxseg == -1) {
836 default_tcp_maxseg = -2;
837 fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
838 if (fd < 0)
839 ha_warning("Failed to create a temporary socket!\n");
840 else {
841 if (getsockopt(fd, IPPROTO_TCP, TCP_MAXSEG, &default_tcp_maxseg,
842 &ready_len) == -1)
843 ha_warning("Failed to get the default value of TCP_MAXSEG\n");
844 close(fd);
845 }
846 }
847 if (default_tcp6_maxseg == -1) {
848 default_tcp6_maxseg = -2;
849 fd = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
850 if (fd >= 0) {
851 if (getsockopt(fd, IPPROTO_TCP, TCP_MAXSEG, &default_tcp6_maxseg,
852 &ready_len) == -1)
853 ha_warning("Failed ot get the default value of TCP_MAXSEG for IPv6\n");
854 close(fd);
855 }
856 }
857 #endif
858
859
860 /* ensure we never return garbage */
861 if (errlen)
862 *errmsg = 0;
863
864 if (listener->state != LI_ASSIGNED)
865 return ERR_NONE; /* already bound */
866
867 err = ERR_NONE;
868
869 if (listener->fd == -1)
870 listener->fd = tcp_find_compatible_fd(listener);
871
872 /* if the listener already has an fd assigned, then we were offered the
873 * fd by an external process (most likely the parent), and we don't want
874 * to create a new socket. However we still want to set a few flags on
875 * the socket.
876 */
877 fd = listener->fd;
878 ext = (fd >= 0);
879
880 if (!ext) {
881 fd = my_socketat(listener->netns, listener->addr.ss_family, SOCK_STREAM, IPPROTO_TCP);
882
883 if (fd == -1) {
884 err |= ERR_RETRYABLE | ERR_ALERT;
885 msg = "cannot create listening socket";
886 goto tcp_return;
887 }
888 }
889
890 if (fd >= global.maxsock) {
891 err |= ERR_FATAL | ERR_ABORT | ERR_ALERT;
892 msg = "not enough free sockets (raise '-n' parameter)";
893 goto tcp_close_return;
894 }
895
896 if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
897 err |= ERR_FATAL | ERR_ALERT;
898 msg = "cannot make socket non-blocking";
899 goto tcp_close_return;
900 }
901
902 if (!ext && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1) {
903 /* not fatal but should be reported */
904 msg = "cannot do so_reuseaddr";
905 err |= ERR_ALERT;
906 }
907
908 if (listener->options & LI_O_NOLINGER)
909 setsockopt(fd, SOL_SOCKET, SO_LINGER, &nolinger, sizeof(struct linger));
910 else {
911 struct linger tmplinger;
912 socklen_t len = sizeof(tmplinger);
913 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &tmplinger, &len) == 0 &&
914 (tmplinger.l_onoff == 1 || tmplinger.l_linger == 0)) {
915 tmplinger.l_onoff = 0;
916 tmplinger.l_linger = 0;
917 setsockopt(fd, SOL_SOCKET, SO_LINGER, &tmplinger,
918 sizeof(tmplinger));
919 }
920 }
921
922 #ifdef SO_REUSEPORT
923 /* OpenBSD and Linux 3.9 support this. As it's present in old libc versions of
924 * Linux, it might return an error that we will silently ignore.
925 */
926 if (!ext && (global.tune.options & GTUNE_USE_REUSEPORT))
927 setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one));
928 #endif
929
930 if (!ext && (listener->options & LI_O_FOREIGN)) {
931 switch (listener->addr.ss_family) {
932 case AF_INET:
933 if (1
934 #if defined(IP_TRANSPARENT)
935 && (setsockopt(fd, SOL_IP, IP_TRANSPARENT, &one, sizeof(one)) == -1)
936 #endif
937 #if defined(IP_FREEBIND)
938 && (setsockopt(fd, SOL_IP, IP_FREEBIND, &one, sizeof(one)) == -1)
939 #endif
940 #if defined(IP_BINDANY)
941 && (setsockopt(fd, IPPROTO_IP, IP_BINDANY, &one, sizeof(one)) == -1)
942 #endif
943 #if defined(SO_BINDANY)
944 && (setsockopt(fd, SOL_SOCKET, SO_BINDANY, &one, sizeof(one)) == -1)
945 #endif
946 ) {
947 msg = "cannot make listening socket transparent";
948 err |= ERR_ALERT;
949 }
950 break;
951 case AF_INET6:
952 if (1
953 #if defined(IPV6_TRANSPARENT) && defined(SOL_IPV6)
954 && (setsockopt(fd, SOL_IPV6, IPV6_TRANSPARENT, &one, sizeof(one)) == -1)
955 #endif
956 #if defined(IP_FREEBIND)
957 && (setsockopt(fd, SOL_IP, IP_FREEBIND, &one, sizeof(one)) == -1)
958 #endif
959 #if defined(IPV6_BINDANY)
960 && (setsockopt(fd, IPPROTO_IPV6, IPV6_BINDANY, &one, sizeof(one)) == -1)
961 #endif
962 #if defined(SO_BINDANY)
963 && (setsockopt(fd, SOL_SOCKET, SO_BINDANY, &one, sizeof(one)) == -1)
964 #endif
965 ) {
966 msg = "cannot make listening socket transparent";
967 err |= ERR_ALERT;
968 }
969 break;
970 }
971 }
972
973 #ifdef SO_BINDTODEVICE
974 /* Note: this might fail if not CAP_NET_RAW */
975 if (!ext && listener->interface) {
976 if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE,
977 listener->interface, strlen(listener->interface) + 1) == -1) {
978 msg = "cannot bind listener to device";
979 err |= ERR_WARN;
980 }
981 }
982 #endif
983 #if defined(TCP_MAXSEG)
984 if (listener->maxseg > 0) {
985 if (setsockopt(fd, IPPROTO_TCP, TCP_MAXSEG,
986 &listener->maxseg, sizeof(listener->maxseg)) == -1) {
987 msg = "cannot set MSS";
988 err |= ERR_WARN;
989 }
990 } else if (ext) {
991 int tmpmaxseg = -1;
992 int defaultmss;
993 socklen_t len = sizeof(tmpmaxseg);
994
995 if (listener->addr.ss_family == AF_INET)
996 defaultmss = default_tcp_maxseg;
997 else
998 defaultmss = default_tcp6_maxseg;
999
1000 getsockopt(fd, IPPROTO_TCP, TCP_MAXSEG, &tmpmaxseg, &len);
1001 if (defaultmss > 0 &&
1002 tmpmaxseg != defaultmss &&
1003 setsockopt(fd, IPPROTO_TCP, TCP_MAXSEG, &defaultmss, sizeof(defaultmss)) == -1) {
1004 msg = "cannot set MSS";
1005 err |= ERR_WARN;
1006 }
1007 }
1008 #endif
1009 #if defined(TCP_USER_TIMEOUT)
1010 if (listener->tcp_ut) {
1011 if (setsockopt(fd, IPPROTO_TCP, TCP_USER_TIMEOUT,
1012 &listener->tcp_ut, sizeof(listener->tcp_ut)) == -1) {
1013 msg = "cannot set TCP User Timeout";
1014 err |= ERR_WARN;
1015 }
1016 } else
1017 setsockopt(fd, IPPROTO_TCP, TCP_USER_TIMEOUT, &zero,
1018 sizeof(zero));
1019 #endif
1020 #if defined(TCP_DEFER_ACCEPT)
1021 if (listener->options & LI_O_DEF_ACCEPT) {
1022 /* defer accept by up to one second */
1023 int accept_delay = 1;
1024 if (setsockopt(fd, IPPROTO_TCP, TCP_DEFER_ACCEPT, &accept_delay, sizeof(accept_delay)) == -1) {
1025 msg = "cannot enable DEFER_ACCEPT";
1026 err |= ERR_WARN;
1027 }
1028 } else
1029 setsockopt(fd, IPPROTO_TCP, TCP_DEFER_ACCEPT, &zero,
1030 sizeof(zero));
1031 #endif
1032 #if defined(TCP_FASTOPEN)
1033 if (listener->options & LI_O_TCP_FO) {
1034 /* TFO needs a queue length, let's use the configured backlog */
1035 int qlen = listener_backlog(listener);
1036 if (setsockopt(fd, IPPROTO_TCP, TCP_FASTOPEN, &qlen, sizeof(qlen)) == -1) {
1037 msg = "cannot enable TCP_FASTOPEN";
1038 err |= ERR_WARN;
1039 }
1040 } else {
1041 socklen_t len;
1042 int qlen;
1043 len = sizeof(qlen);
1044 /* Only disable fast open if it was enabled, we don't want
1045 * the kernel to create a fast open queue if there's none.
1046 */
1047 if (getsockopt(fd, IPPROTO_TCP, TCP_FASTOPEN, &qlen, &len) == 0 &&
1048 qlen != 0) {
1049 if (setsockopt(fd, IPPROTO_TCP, TCP_FASTOPEN, &zero,
1050 sizeof(zero)) == -1) {
1051 msg = "cannot disable TCP_FASTOPEN";
1052 err |= ERR_WARN;
1053 }
1054 }
1055 }
1056 #endif
1057 #if defined(IPV6_V6ONLY)
1058 if (listener->options & LI_O_V6ONLY)
1059 setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &one, sizeof(one));
1060 else if (listener->options & LI_O_V4V6)
1061 setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &zero, sizeof(zero));
1062 #endif
1063
1064 if (!ext && bind(fd, (struct sockaddr *)&listener->addr, listener->proto->sock_addrlen) == -1) {
1065 err |= ERR_RETRYABLE | ERR_ALERT;
1066 msg = "cannot bind socket";
1067 goto tcp_close_return;
1068 }
1069
1070 ready = 0;
1071 ready_len = sizeof(ready);
1072 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &ready, &ready_len) == -1)
1073 ready = 0;
1074
1075 if (!(ext && ready) && /* only listen if not already done by external process */
1076 listen(fd, listener_backlog(listener)) == -1) {
1077 err |= ERR_RETRYABLE | ERR_ALERT;
1078 msg = "cannot listen to socket";
1079 goto tcp_close_return;
1080 }
1081
1082 #if defined(TCP_QUICKACK)
1083 if (listener->options & LI_O_NOQUICKACK)
1084 setsockopt(fd, IPPROTO_TCP, TCP_QUICKACK, &zero, sizeof(zero));
1085 else
1086 setsockopt(fd, IPPROTO_TCP, TCP_QUICKACK, &one, sizeof(one));
1087 #endif
1088
1089 /* the socket is ready */
1090 listener->fd = fd;
1091 listener->state = LI_LISTEN;
1092
1093 fd_insert(fd, listener, listener->proto->accept,
1094 thread_mask(listener->bind_conf->bind_thread) & all_threads_mask);
1095
1096 tcp_return:
1097 if (msg && errlen) {
1098 char pn[INET6_ADDRSTRLEN];
1099
1100 addr_to_str(&listener->addr, pn, sizeof(pn));
1101 snprintf(errmsg, errlen, "%s [%s:%d]", msg, pn, get_host_port(&listener->addr));
1102 }
1103 return err;
1104
1105 tcp_close_return:
1106 close(fd);
1107 goto tcp_return;
1108 }
1109
1110 /* This function creates all TCP sockets bound to the protocol entry <proto>.
1111 * It is intended to be used as the protocol's bind_all() function.
1112 * The sockets will be registered but not added to any fd_set, in order not to
1113 * loose them across the fork(). A call to enable_all_listeners() is needed
1114 * to complete initialization. The return value is composed from ERR_*.
1115 *
1116 * Must be called with proto_lock held.
1117 *
1118 */
tcp_bind_listeners(struct protocol * proto,char * errmsg,int errlen)1119 static int tcp_bind_listeners(struct protocol *proto, char *errmsg, int errlen)
1120 {
1121 struct listener *listener;
1122 int err = ERR_NONE;
1123
1124 list_for_each_entry(listener, &proto->listeners, proto_list) {
1125 err |= tcp_bind_listener(listener, errmsg, errlen);
1126 if (err & ERR_ABORT)
1127 break;
1128 }
1129
1130 return err;
1131 }
1132
1133 /* Add <listener> to the list of tcpv4 listeners, on port <port>. The
1134 * listener's state is automatically updated from LI_INIT to LI_ASSIGNED.
1135 * The number of listeners for the protocol is updated.
1136 *
1137 * Must be called with proto_lock held.
1138 *
1139 */
tcpv4_add_listener(struct listener * listener,int port)1140 static void tcpv4_add_listener(struct listener *listener, int port)
1141 {
1142 if (listener->state != LI_INIT)
1143 return;
1144 listener->state = LI_ASSIGNED;
1145 listener->proto = &proto_tcpv4;
1146 ((struct sockaddr_in *)(&listener->addr))->sin_port = htons(port);
1147 LIST_ADDQ(&proto_tcpv4.listeners, &listener->proto_list);
1148 proto_tcpv4.nb_listeners++;
1149 }
1150
1151 /* Add <listener> to the list of tcpv6 listeners, on port <port>. The
1152 * listener's state is automatically updated from LI_INIT to LI_ASSIGNED.
1153 * The number of listeners for the protocol is updated.
1154 *
1155 * Must be called with proto_lock held.
1156 *
1157 */
tcpv6_add_listener(struct listener * listener,int port)1158 static void tcpv6_add_listener(struct listener *listener, int port)
1159 {
1160 if (listener->state != LI_INIT)
1161 return;
1162 listener->state = LI_ASSIGNED;
1163 listener->proto = &proto_tcpv6;
1164 ((struct sockaddr_in *)(&listener->addr))->sin_port = htons(port);
1165 LIST_ADDQ(&proto_tcpv6.listeners, &listener->proto_list);
1166 proto_tcpv6.nb_listeners++;
1167 }
1168
1169 /* Pause a listener. Returns < 0 in case of failure, 0 if the listener
1170 * was totally stopped, or > 0 if correctly paused.
1171 */
tcp_pause_listener(struct listener * l)1172 int tcp_pause_listener(struct listener *l)
1173 {
1174 if (shutdown(l->fd, SHUT_WR) != 0)
1175 return -1; /* Solaris dies here */
1176
1177 if (listen(l->fd, listener_backlog(l)) != 0)
1178 return -1; /* OpenBSD dies here */
1179
1180 if (shutdown(l->fd, SHUT_RD) != 0)
1181 return -1; /* should always be OK */
1182 return 1;
1183 }
1184
1185 /*
1186 * Execute the "set-src" action. May be called from {tcp,http}request.
1187 * It only changes the address and tries to preserve the original port. If the
1188 * previous family was neither AF_INET nor AF_INET6, the port is set to zero.
1189 */
tcp_action_req_set_src(struct act_rule * rule,struct proxy * px,struct session * sess,struct stream * s,int flags)1190 enum act_return tcp_action_req_set_src(struct act_rule *rule, struct proxy *px,
1191 struct session *sess, struct stream *s, int flags)
1192 {
1193 struct connection *cli_conn;
1194
1195 if ((cli_conn = objt_conn(sess->origin)) && conn_get_src(cli_conn)) {
1196 struct sample *smp;
1197
1198 smp = sample_fetch_as_type(px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL, rule->arg.expr, SMP_T_ADDR);
1199 if (smp) {
1200 int port = get_net_port(cli_conn->src);
1201
1202 if (smp->data.type == SMP_T_IPV4) {
1203 ((struct sockaddr_in *)cli_conn->src)->sin_family = AF_INET;
1204 ((struct sockaddr_in *)cli_conn->src)->sin_addr.s_addr = smp->data.u.ipv4.s_addr;
1205 ((struct sockaddr_in *)cli_conn->src)->sin_port = port;
1206 } else if (smp->data.type == SMP_T_IPV6) {
1207 ((struct sockaddr_in6 *)cli_conn->src)->sin6_family = AF_INET6;
1208 memcpy(&((struct sockaddr_in6 *)cli_conn->src)->sin6_addr, &smp->data.u.ipv6, sizeof(struct in6_addr));
1209 ((struct sockaddr_in6 *)cli_conn->src)->sin6_port = port;
1210 }
1211 }
1212 cli_conn->flags |= CO_FL_ADDR_FROM_SET;
1213 }
1214 return ACT_RET_CONT;
1215 }
1216
1217 /*
1218 * Execute the "set-dst" action. May be called from {tcp,http}request.
1219 * It only changes the address and tries to preserve the original port. If the
1220 * previous family was neither AF_INET nor AF_INET6, the port is set to zero.
1221 */
tcp_action_req_set_dst(struct act_rule * rule,struct proxy * px,struct session * sess,struct stream * s,int flags)1222 enum act_return tcp_action_req_set_dst(struct act_rule *rule, struct proxy *px,
1223 struct session *sess, struct stream *s, int flags)
1224 {
1225 struct connection *cli_conn;
1226
1227 if ((cli_conn = objt_conn(sess->origin)) && conn_get_dst(cli_conn)) {
1228 struct sample *smp;
1229
1230 smp = sample_fetch_as_type(px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL, rule->arg.expr, SMP_T_ADDR);
1231 if (smp) {
1232 int port = get_net_port(cli_conn->dst);
1233
1234 if (smp->data.type == SMP_T_IPV4) {
1235 ((struct sockaddr_in *)cli_conn->dst)->sin_family = AF_INET;
1236 ((struct sockaddr_in *)cli_conn->dst)->sin_addr.s_addr = smp->data.u.ipv4.s_addr;
1237 } else if (smp->data.type == SMP_T_IPV6) {
1238 ((struct sockaddr_in6 *)cli_conn->dst)->sin6_family = AF_INET6;
1239 memcpy(&((struct sockaddr_in6 *)cli_conn->dst)->sin6_addr, &smp->data.u.ipv6, sizeof(struct in6_addr));
1240 ((struct sockaddr_in6 *)cli_conn->dst)->sin6_port = port;
1241 }
1242 cli_conn->flags |= CO_FL_ADDR_TO_SET;
1243 }
1244 }
1245 return ACT_RET_CONT;
1246 }
1247
1248 /*
1249 * Execute the "set-src-port" action. May be called from {tcp,http}request.
1250 * We must test the sin_family before setting the port. If the address family
1251 * is neither AF_INET nor AF_INET6, the address is forced to AF_INET "0.0.0.0"
1252 * and the port is assigned.
1253 */
tcp_action_req_set_src_port(struct act_rule * rule,struct proxy * px,struct session * sess,struct stream * s,int flags)1254 enum act_return tcp_action_req_set_src_port(struct act_rule *rule, struct proxy *px,
1255 struct session *sess, struct stream *s, int flags)
1256 {
1257 struct connection *cli_conn;
1258
1259 if ((cli_conn = objt_conn(sess->origin)) && conn_get_src(cli_conn)) {
1260 struct sample *smp;
1261
1262 smp = sample_fetch_as_type(px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL, rule->arg.expr, SMP_T_SINT);
1263 if (smp) {
1264 if (cli_conn->src->ss_family == AF_INET6) {
1265 ((struct sockaddr_in6 *)cli_conn->src)->sin6_port = htons(smp->data.u.sint);
1266 } else {
1267 if (cli_conn->src->ss_family != AF_INET) {
1268 cli_conn->src->ss_family = AF_INET;
1269 ((struct sockaddr_in *)cli_conn->src)->sin_addr.s_addr = 0;
1270 }
1271 ((struct sockaddr_in *)cli_conn->src)->sin_port = htons(smp->data.u.sint);
1272 }
1273 }
1274 }
1275 return ACT_RET_CONT;
1276 }
1277
1278 /*
1279 * Execute the "set-dst-port" action. May be called from {tcp,http}request.
1280 * We must test the sin_family before setting the port. If the address family
1281 * is neither AF_INET nor AF_INET6, the address is forced to AF_INET "0.0.0.0"
1282 * and the port is assigned.
1283 */
tcp_action_req_set_dst_port(struct act_rule * rule,struct proxy * px,struct session * sess,struct stream * s,int flags)1284 enum act_return tcp_action_req_set_dst_port(struct act_rule *rule, struct proxy *px,
1285 struct session *sess, struct stream *s, int flags)
1286 {
1287 struct connection *cli_conn;
1288
1289 if ((cli_conn = objt_conn(sess->origin)) && conn_get_dst(cli_conn)) {
1290 struct sample *smp;
1291
1292 smp = sample_fetch_as_type(px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL, rule->arg.expr, SMP_T_SINT);
1293 if (smp) {
1294 if (cli_conn->dst->ss_family == AF_INET6) {
1295 ((struct sockaddr_in6 *)cli_conn->dst)->sin6_port = htons(smp->data.u.sint);
1296 } else {
1297 if (cli_conn->dst->ss_family != AF_INET) {
1298 cli_conn->dst->ss_family = AF_INET;
1299 ((struct sockaddr_in *)cli_conn->dst)->sin_addr.s_addr = 0;
1300 }
1301 ((struct sockaddr_in *)cli_conn->dst)->sin_port = htons(smp->data.u.sint);
1302 }
1303 }
1304 }
1305 return ACT_RET_CONT;
1306 }
1307
1308 /* Executes the "silent-drop" action. May be called from {tcp,http}{request,response} */
tcp_exec_action_silent_drop(struct act_rule * rule,struct proxy * px,struct session * sess,struct stream * strm,int flags)1309 static enum act_return tcp_exec_action_silent_drop(struct act_rule *rule, struct proxy *px, struct session *sess, struct stream *strm, int flags)
1310 {
1311 struct connection *conn = objt_conn(sess->origin);
1312
1313 if (!conn)
1314 goto out;
1315
1316 if (!conn_ctrl_ready(conn))
1317 goto out;
1318
1319 #ifdef TCP_QUICKACK
1320 /* drain is needed only to send the quick ACK */
1321 conn_sock_drain(conn);
1322
1323 /* re-enable quickack if it was disabled to ack all data and avoid
1324 * retransmits from the client that might trigger a real reset.
1325 */
1326 setsockopt(conn->handle.fd, SOL_TCP, TCP_QUICKACK, &one, sizeof(one));
1327 #endif
1328 /* lingering must absolutely be disabled so that we don't send a
1329 * shutdown(), this is critical to the TCP_REPAIR trick. When no stream
1330 * is present, returning with ERR will cause lingering to be disabled.
1331 */
1332 if (strm)
1333 strm->si[0].flags |= SI_FL_NOLINGER;
1334
1335 /* We're on the client-facing side, we must force to disable lingering to
1336 * ensure we will use an RST exclusively and kill any pending data.
1337 */
1338 fdtab[conn->handle.fd].linger_risk = 1;
1339
1340 #ifdef TCP_REPAIR
1341 if (setsockopt(conn->handle.fd, SOL_TCP, TCP_REPAIR, &one, sizeof(one)) == 0) {
1342 /* socket will be quiet now */
1343 goto out;
1344 }
1345 #endif
1346 /* either TCP_REPAIR is not defined or it failed (eg: permissions).
1347 * Let's fall back on the TTL trick, though it only works for routed
1348 * network and has no effect on local net.
1349 */
1350 #ifdef IP_TTL
1351 setsockopt(conn->handle.fd, SOL_IP, IP_TTL, &one, sizeof(one));
1352 #endif
1353 out:
1354 /* kill the stream if any */
1355 if (strm) {
1356 channel_abort(&strm->req);
1357 channel_abort(&strm->res);
1358 strm->req.analysers &= AN_REQ_FLT_END;
1359 strm->res.analysers &= AN_RES_FLT_END;
1360 if (strm->flags & SF_BE_ASSIGNED)
1361 _HA_ATOMIC_ADD(&strm->be->be_counters.denied_req, 1);
1362 if (!(strm->flags & SF_ERR_MASK))
1363 strm->flags |= SF_ERR_PRXCOND;
1364 if (!(strm->flags & SF_FINST_MASK))
1365 strm->flags |= SF_FINST_R;
1366 }
1367
1368 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
1369 if (sess->listener->counters)
1370 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
1371
1372 return ACT_RET_STOP;
1373 }
1374
1375 /* parse "set-{src,dst}[-port]" action */
tcp_parse_set_src_dst(const char ** args,int * orig_arg,struct proxy * px,struct act_rule * rule,char ** err)1376 enum act_parse_ret tcp_parse_set_src_dst(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
1377 {
1378 int cur_arg;
1379 struct sample_expr *expr;
1380 unsigned int where;
1381
1382 cur_arg = *orig_arg;
1383 expr = sample_parse_expr((char **)args, &cur_arg, px->conf.args.file, px->conf.args.line, err, &px->conf.args);
1384 if (!expr)
1385 return ACT_RET_PRS_ERR;
1386
1387 where = 0;
1388 if (px->cap & PR_CAP_FE)
1389 where |= SMP_VAL_FE_HRQ_HDR;
1390 if (px->cap & PR_CAP_BE)
1391 where |= SMP_VAL_BE_HRQ_HDR;
1392
1393 if (!(expr->fetch->val & where)) {
1394 memprintf(err,
1395 "fetch method '%s' extracts information from '%s', none of which is available here",
1396 args[cur_arg-1], sample_src_names(expr->fetch->use));
1397 free(expr);
1398 return ACT_RET_PRS_ERR;
1399 }
1400 rule->arg.expr = expr;
1401 rule->action = ACT_CUSTOM;
1402
1403 if (!strcmp(args[*orig_arg-1], "set-src")) {
1404 rule->action_ptr = tcp_action_req_set_src;
1405 } else if (!strcmp(args[*orig_arg-1], "set-src-port")) {
1406 rule->action_ptr = tcp_action_req_set_src_port;
1407 } else if (!strcmp(args[*orig_arg-1], "set-dst")) {
1408 rule->action_ptr = tcp_action_req_set_dst;
1409 } else if (!strcmp(args[*orig_arg-1], "set-dst-port")) {
1410 rule->action_ptr = tcp_action_req_set_dst_port;
1411 } else {
1412 return ACT_RET_PRS_ERR;
1413 }
1414
1415 (*orig_arg)++;
1416
1417 return ACT_RET_PRS_OK;
1418 }
1419
1420
1421 /* Parse a "silent-drop" action. It takes no argument. It returns ACT_RET_PRS_OK on
1422 * success, ACT_RET_PRS_ERR on error.
1423 */
tcp_parse_silent_drop(const char ** args,int * orig_arg,struct proxy * px,struct act_rule * rule,char ** err)1424 static enum act_parse_ret tcp_parse_silent_drop(const char **args, int *orig_arg, struct proxy *px,
1425 struct act_rule *rule, char **err)
1426 {
1427 rule->action = ACT_CUSTOM;
1428 rule->action_ptr = tcp_exec_action_silent_drop;
1429 return ACT_RET_PRS_OK;
1430 }
1431
1432
1433 /************************************************************************/
1434 /* All supported sample fetch functions must be declared here */
1435 /************************************************************************/
1436
1437 /* fetch the connection's source IPv4/IPv6 address */
smp_fetch_src(const struct arg * args,struct sample * smp,const char * kw,void * private)1438 int smp_fetch_src(const struct arg *args, struct sample *smp, const char *kw, void *private)
1439 {
1440 struct connection *cli_conn = objt_conn(smp->sess->origin);
1441
1442 if (!cli_conn)
1443 return 0;
1444
1445 if (!conn_get_src(cli_conn))
1446 return 0;
1447
1448 switch (cli_conn->src->ss_family) {
1449 case AF_INET:
1450 smp->data.u.ipv4 = ((struct sockaddr_in *)cli_conn->src)->sin_addr;
1451 smp->data.type = SMP_T_IPV4;
1452 break;
1453 case AF_INET6:
1454 smp->data.u.ipv6 = ((struct sockaddr_in6 *)cli_conn->src)->sin6_addr;
1455 smp->data.type = SMP_T_IPV6;
1456 break;
1457 default:
1458 return 0;
1459 }
1460
1461 smp->flags = 0;
1462 return 1;
1463 }
1464
1465 /* set temp integer to the connection's source port */
1466 static int
smp_fetch_sport(const struct arg * args,struct sample * smp,const char * k,void * private)1467 smp_fetch_sport(const struct arg *args, struct sample *smp, const char *k, void *private)
1468 {
1469 struct connection *cli_conn = objt_conn(smp->sess->origin);
1470
1471 if (!cli_conn)
1472 return 0;
1473
1474 if (!conn_get_src(cli_conn))
1475 return 0;
1476
1477 smp->data.type = SMP_T_SINT;
1478 if (!(smp->data.u.sint = get_host_port(cli_conn->src)))
1479 return 0;
1480
1481 smp->flags = 0;
1482 return 1;
1483 }
1484
1485 /* fetch the connection's destination IPv4/IPv6 address */
1486 static int
smp_fetch_dst(const struct arg * args,struct sample * smp,const char * kw,void * private)1487 smp_fetch_dst(const struct arg *args, struct sample *smp, const char *kw, void *private)
1488 {
1489 struct connection *cli_conn = objt_conn(smp->sess->origin);
1490
1491 if (!cli_conn)
1492 return 0;
1493
1494 if (!conn_get_dst(cli_conn))
1495 return 0;
1496
1497 switch (cli_conn->dst->ss_family) {
1498 case AF_INET:
1499 smp->data.u.ipv4 = ((struct sockaddr_in *)cli_conn->dst)->sin_addr;
1500 smp->data.type = SMP_T_IPV4;
1501 break;
1502 case AF_INET6:
1503 smp->data.u.ipv6 = ((struct sockaddr_in6 *)cli_conn->dst)->sin6_addr;
1504 smp->data.type = SMP_T_IPV6;
1505 break;
1506 default:
1507 return 0;
1508 }
1509
1510 smp->flags = 0;
1511 return 1;
1512 }
1513
1514 /* check if the destination address of the front connection is local to the
1515 * system or if it was intercepted.
1516 */
smp_fetch_dst_is_local(const struct arg * args,struct sample * smp,const char * kw,void * private)1517 int smp_fetch_dst_is_local(const struct arg *args, struct sample *smp, const char *kw, void *private)
1518 {
1519 struct connection *conn = objt_conn(smp->sess->origin);
1520 struct listener *li = smp->sess->listener;
1521
1522 if (!conn)
1523 return 0;
1524
1525 if (!conn_get_dst(conn))
1526 return 0;
1527
1528 smp->data.type = SMP_T_BOOL;
1529 smp->flags = 0;
1530 smp->data.u.sint = addr_is_local(li->netns, conn->dst);
1531 return smp->data.u.sint >= 0;
1532 }
1533
1534 /* check if the source address of the front connection is local to the system
1535 * or not.
1536 */
smp_fetch_src_is_local(const struct arg * args,struct sample * smp,const char * kw,void * private)1537 int smp_fetch_src_is_local(const struct arg *args, struct sample *smp, const char *kw, void *private)
1538 {
1539 struct connection *conn = objt_conn(smp->sess->origin);
1540 struct listener *li = smp->sess->listener;
1541
1542 if (!conn)
1543 return 0;
1544
1545 if (!conn_get_src(conn))
1546 return 0;
1547
1548 smp->data.type = SMP_T_BOOL;
1549 smp->flags = 0;
1550 smp->data.u.sint = addr_is_local(li->netns, conn->src);
1551 return smp->data.u.sint >= 0;
1552 }
1553
1554 /* set temp integer to the frontend connexion's destination port */
1555 static int
smp_fetch_dport(const struct arg * args,struct sample * smp,const char * kw,void * private)1556 smp_fetch_dport(const struct arg *args, struct sample *smp, const char *kw, void *private)
1557 {
1558 struct connection *cli_conn = objt_conn(smp->sess->origin);
1559
1560 if (!cli_conn)
1561 return 0;
1562
1563 if (!conn_get_dst(cli_conn))
1564 return 0;
1565
1566 smp->data.type = SMP_T_SINT;
1567 if (!(smp->data.u.sint = get_host_port(cli_conn->dst)))
1568 return 0;
1569
1570 smp->flags = 0;
1571 return 1;
1572 }
1573
1574 #ifdef TCP_INFO
1575
1576
1577 /* Validates the arguments passed to "fc_*" fetch keywords returning a time
1578 * value. These keywords support an optional string representing the unit of the
1579 * result: "us" for microseconds and "ms" for milliseconds". Returns 0 on error
1580 * and non-zero if OK.
1581 */
val_fc_time_value(struct arg * args,char ** err)1582 static int val_fc_time_value(struct arg *args, char **err)
1583 {
1584 if (args[0].type == ARGT_STR) {
1585 if (strcmp(args[0].data.str.area, "us") == 0) {
1586 free(args[0].data.str.area);
1587 args[0].type = ARGT_SINT;
1588 args[0].data.sint = TIME_UNIT_US;
1589 }
1590 else if (strcmp(args[0].data.str.area, "ms") == 0) {
1591 free(args[0].data.str.area);
1592 args[0].type = ARGT_SINT;
1593 args[0].data.sint = TIME_UNIT_MS;
1594 }
1595 else {
1596 memprintf(err, "expects 'us' or 'ms', got '%s'",
1597 args[0].data.str.area);
1598 return 0;
1599 }
1600 }
1601 else {
1602 memprintf(err, "Unexpected arg type");
1603 return 0;
1604 }
1605
1606 return 1;
1607 }
1608
1609 /* Validates the arguments passed to "fc_*" fetch keywords returning a
1610 * counter. These keywords should be used without any keyword, but because of a
1611 * bug in previous versions, an optional string argument may be passed. In such
1612 * case, the argument is ignored and a warning is emitted. Returns 0 on error
1613 * and non-zero if OK.
1614 */
var_fc_counter(struct arg * args,char ** err)1615 static int var_fc_counter(struct arg *args, char **err)
1616 {
1617 if (args[0].type != ARGT_STOP) {
1618 ha_warning("no argument supported for 'fc_*' sample expressions returning counters.\n");
1619 if (args[0].type == ARGT_STR)
1620 free(args[0].data.str.area);
1621 args[0].type = ARGT_STOP;
1622 }
1623
1624 return 1;
1625 }
1626
1627 /* Returns some tcp_info data if it's available. "dir" must be set to 0 if
1628 * the client connection is required, otherwise it is set to 1. "val" represents
1629 * the required value.
1630 * If the function fails it returns 0, otherwise it returns 1 and "result" is filled.
1631 */
get_tcp_info(const struct arg * args,struct sample * smp,int dir,int val)1632 static inline int get_tcp_info(const struct arg *args, struct sample *smp,
1633 int dir, int val)
1634 {
1635 struct connection *conn;
1636 struct tcp_info info;
1637 socklen_t optlen;
1638
1639 /* strm can be null. */
1640 if (!smp->strm)
1641 return 0;
1642
1643 /* get the object associated with the stream interface.The
1644 * object can be other thing than a connection. For example,
1645 * it be a appctx. */
1646 conn = cs_conn(objt_cs(smp->strm->si[dir].end));
1647 if (!conn)
1648 return 0;
1649
1650 /* The fd may not be available for the tcp_info struct, and the
1651 syscal can fail. */
1652 optlen = sizeof(info);
1653 if (getsockopt(conn->handle.fd, SOL_TCP, TCP_INFO, &info, &optlen) == -1)
1654 return 0;
1655
1656 /* extract the value. */
1657 smp->data.type = SMP_T_SINT;
1658 switch (val) {
1659 case 0: smp->data.u.sint = info.tcpi_rtt; break;
1660 case 1: smp->data.u.sint = info.tcpi_rttvar; break;
1661 #if defined(__linux__)
1662 /* these ones are common to all Linux versions */
1663 case 2: smp->data.u.sint = info.tcpi_unacked; break;
1664 case 3: smp->data.u.sint = info.tcpi_sacked; break;
1665 case 4: smp->data.u.sint = info.tcpi_lost; break;
1666 case 5: smp->data.u.sint = info.tcpi_retrans; break;
1667 case 6: smp->data.u.sint = info.tcpi_fackets; break;
1668 case 7: smp->data.u.sint = info.tcpi_reordering; break;
1669 #elif defined(__FreeBSD__) || defined(__NetBSD__)
1670 /* the ones are found on FreeBSD and NetBSD featuring TCP_INFO */
1671 case 2: smp->data.u.sint = info.__tcpi_unacked; break;
1672 case 3: smp->data.u.sint = info.__tcpi_sacked; break;
1673 case 4: smp->data.u.sint = info.__tcpi_lost; break;
1674 case 5: smp->data.u.sint = info.__tcpi_retrans; break;
1675 case 6: smp->data.u.sint = info.__tcpi_fackets; break;
1676 case 7: smp->data.u.sint = info.__tcpi_reordering; break;
1677 #endif
1678 default: return 0;
1679 }
1680
1681 return 1;
1682 }
1683
1684 /* get the mean rtt of a client connexion */
1685 static int
smp_fetch_fc_rtt(const struct arg * args,struct sample * smp,const char * kw,void * private)1686 smp_fetch_fc_rtt(const struct arg *args, struct sample *smp, const char *kw, void *private)
1687 {
1688 if (!get_tcp_info(args, smp, 0, 0))
1689 return 0;
1690
1691 /* By default or if explicitly specified, convert rtt to ms */
1692 if (!args || args[0].type == ARGT_STOP || args[0].data.sint == TIME_UNIT_MS)
1693 smp->data.u.sint = (smp->data.u.sint + 500) / 1000;
1694
1695 return 1;
1696 }
1697
1698 /* get the variance of the mean rtt of a client connexion */
1699 static int
smp_fetch_fc_rttvar(const struct arg * args,struct sample * smp,const char * kw,void * private)1700 smp_fetch_fc_rttvar(const struct arg *args, struct sample *smp, const char *kw, void *private)
1701 {
1702 if (!get_tcp_info(args, smp, 0, 1))
1703 return 0;
1704
1705 /* By default or if explicitly specified, convert rttvar to ms */
1706 if (!args || args[0].type == ARGT_STOP || args[0].data.sint == TIME_UNIT_MS)
1707 smp->data.u.sint = (smp->data.u.sint + 500) / 1000;
1708
1709 return 1;
1710 }
1711
1712 #if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
1713
1714 /* get the unacked counter on a client connexion */
1715 static int
smp_fetch_fc_unacked(const struct arg * args,struct sample * smp,const char * kw,void * private)1716 smp_fetch_fc_unacked(const struct arg *args, struct sample *smp, const char *kw, void *private)
1717 {
1718 if (!get_tcp_info(args, smp, 0, 2))
1719 return 0;
1720 return 1;
1721 }
1722
1723 /* get the sacked counter on a client connexion */
1724 static int
smp_fetch_fc_sacked(const struct arg * args,struct sample * smp,const char * kw,void * private)1725 smp_fetch_fc_sacked(const struct arg *args, struct sample *smp, const char *kw, void *private)
1726 {
1727 if (!get_tcp_info(args, smp, 0, 3))
1728 return 0;
1729 return 1;
1730 }
1731
1732 /* get the lost counter on a client connexion */
1733 static int
smp_fetch_fc_lost(const struct arg * args,struct sample * smp,const char * kw,void * private)1734 smp_fetch_fc_lost(const struct arg *args, struct sample *smp, const char *kw, void *private)
1735 {
1736 if (!get_tcp_info(args, smp, 0, 4))
1737 return 0;
1738 return 1;
1739 }
1740
1741 /* get the retrans counter on a client connexion */
1742 static int
smp_fetch_fc_retrans(const struct arg * args,struct sample * smp,const char * kw,void * private)1743 smp_fetch_fc_retrans(const struct arg *args, struct sample *smp, const char *kw, void *private)
1744 {
1745 if (!get_tcp_info(args, smp, 0, 5))
1746 return 0;
1747 return 1;
1748 }
1749
1750 /* get the fackets counter on a client connexion */
1751 static int
smp_fetch_fc_fackets(const struct arg * args,struct sample * smp,const char * kw,void * private)1752 smp_fetch_fc_fackets(const struct arg *args, struct sample *smp, const char *kw, void *private)
1753 {
1754 if (!get_tcp_info(args, smp, 0, 6))
1755 return 0;
1756 return 1;
1757 }
1758
1759 /* get the reordering counter on a client connexion */
1760 static int
smp_fetch_fc_reordering(const struct arg * args,struct sample * smp,const char * kw,void * private)1761 smp_fetch_fc_reordering(const struct arg *args, struct sample *smp, const char *kw, void *private)
1762 {
1763 if (!get_tcp_info(args, smp, 0, 7))
1764 return 0;
1765 return 1;
1766 }
1767 #endif // linux || freebsd || netbsd
1768 #endif // TCP_INFO
1769
1770 #ifdef IPV6_V6ONLY
1771 /* parse the "v4v6" bind keyword */
bind_parse_v4v6(char ** args,int cur_arg,struct proxy * px,struct bind_conf * conf,char ** err)1772 static int bind_parse_v4v6(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
1773 {
1774 struct listener *l;
1775
1776 list_for_each_entry(l, &conf->listeners, by_bind) {
1777 if (l->addr.ss_family == AF_INET6)
1778 l->options |= LI_O_V4V6;
1779 }
1780
1781 return 0;
1782 }
1783
1784 /* parse the "v6only" bind keyword */
bind_parse_v6only(char ** args,int cur_arg,struct proxy * px,struct bind_conf * conf,char ** err)1785 static int bind_parse_v6only(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
1786 {
1787 struct listener *l;
1788
1789 list_for_each_entry(l, &conf->listeners, by_bind) {
1790 if (l->addr.ss_family == AF_INET6)
1791 l->options |= LI_O_V6ONLY;
1792 }
1793
1794 return 0;
1795 }
1796 #endif
1797
1798 #ifdef CONFIG_HAP_TRANSPARENT
1799 /* parse the "transparent" bind keyword */
bind_parse_transparent(char ** args,int cur_arg,struct proxy * px,struct bind_conf * conf,char ** err)1800 static int bind_parse_transparent(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
1801 {
1802 struct listener *l;
1803
1804 list_for_each_entry(l, &conf->listeners, by_bind) {
1805 if (l->addr.ss_family == AF_INET || l->addr.ss_family == AF_INET6)
1806 l->options |= LI_O_FOREIGN;
1807 }
1808
1809 return 0;
1810 }
1811 #endif
1812
1813 #ifdef TCP_DEFER_ACCEPT
1814 /* parse the "defer-accept" bind keyword */
bind_parse_defer_accept(char ** args,int cur_arg,struct proxy * px,struct bind_conf * conf,char ** err)1815 static int bind_parse_defer_accept(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
1816 {
1817 struct listener *l;
1818
1819 list_for_each_entry(l, &conf->listeners, by_bind) {
1820 if (l->addr.ss_family == AF_INET || l->addr.ss_family == AF_INET6)
1821 l->options |= LI_O_DEF_ACCEPT;
1822 }
1823
1824 return 0;
1825 }
1826 #endif
1827
1828 #ifdef TCP_FASTOPEN
1829 /* parse the "tfo" bind keyword */
bind_parse_tfo(char ** args,int cur_arg,struct proxy * px,struct bind_conf * conf,char ** err)1830 static int bind_parse_tfo(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
1831 {
1832 struct listener *l;
1833
1834 list_for_each_entry(l, &conf->listeners, by_bind) {
1835 if (l->addr.ss_family == AF_INET || l->addr.ss_family == AF_INET6)
1836 l->options |= LI_O_TCP_FO;
1837 }
1838
1839 return 0;
1840 }
1841 #endif
1842
1843 #ifdef TCP_MAXSEG
1844 /* parse the "mss" bind keyword */
bind_parse_mss(char ** args,int cur_arg,struct proxy * px,struct bind_conf * conf,char ** err)1845 static int bind_parse_mss(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
1846 {
1847 struct listener *l;
1848 int mss;
1849
1850 if (!*args[cur_arg + 1]) {
1851 memprintf(err, "'%s' : missing MSS value", args[cur_arg]);
1852 return ERR_ALERT | ERR_FATAL;
1853 }
1854
1855 mss = atoi(args[cur_arg + 1]);
1856 if (!mss || abs(mss) > 65535) {
1857 memprintf(err, "'%s' : expects an MSS with and absolute value between 1 and 65535", args[cur_arg]);
1858 return ERR_ALERT | ERR_FATAL;
1859 }
1860
1861 list_for_each_entry(l, &conf->listeners, by_bind) {
1862 if (l->addr.ss_family == AF_INET || l->addr.ss_family == AF_INET6)
1863 l->maxseg = mss;
1864 }
1865
1866 return 0;
1867 }
1868 #endif
1869
1870 #ifdef TCP_USER_TIMEOUT
1871 /* parse the "tcp-ut" bind keyword */
bind_parse_tcp_ut(char ** args,int cur_arg,struct proxy * px,struct bind_conf * conf,char ** err)1872 static int bind_parse_tcp_ut(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
1873 {
1874 const char *ptr = NULL;
1875 struct listener *l;
1876 unsigned int timeout;
1877
1878 if (!*args[cur_arg + 1]) {
1879 memprintf(err, "'%s' : missing TCP User Timeout value", args[cur_arg]);
1880 return ERR_ALERT | ERR_FATAL;
1881 }
1882
1883 ptr = parse_time_err(args[cur_arg + 1], &timeout, TIME_UNIT_MS);
1884 if (ptr == PARSE_TIME_OVER) {
1885 memprintf(err, "timer overflow in argument '%s' to '%s' (maximum value is 2147483647 ms or ~24.8 days)",
1886 args[cur_arg+1], args[cur_arg]);
1887 return ERR_ALERT | ERR_FATAL;
1888 }
1889 else if (ptr == PARSE_TIME_UNDER) {
1890 memprintf(err, "timer underflow in argument '%s' to '%s' (minimum non-null value is 1 ms)",
1891 args[cur_arg+1], args[cur_arg]);
1892 return ERR_ALERT | ERR_FATAL;
1893 }
1894 else if (ptr) {
1895 memprintf(err, "'%s' : expects a positive delay in milliseconds", args[cur_arg]);
1896 return ERR_ALERT | ERR_FATAL;
1897 }
1898
1899 list_for_each_entry(l, &conf->listeners, by_bind) {
1900 if (l->addr.ss_family == AF_INET || l->addr.ss_family == AF_INET6)
1901 l->tcp_ut = timeout;
1902 }
1903
1904 return 0;
1905 }
1906 #endif
1907
1908 #ifdef SO_BINDTODEVICE
1909 /* parse the "interface" bind keyword */
bind_parse_interface(char ** args,int cur_arg,struct proxy * px,struct bind_conf * conf,char ** err)1910 static int bind_parse_interface(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
1911 {
1912 struct listener *l;
1913
1914 if (!*args[cur_arg + 1]) {
1915 memprintf(err, "'%s' : missing interface name", args[cur_arg]);
1916 return ERR_ALERT | ERR_FATAL;
1917 }
1918
1919 list_for_each_entry(l, &conf->listeners, by_bind) {
1920 if (l->addr.ss_family == AF_INET || l->addr.ss_family == AF_INET6)
1921 l->interface = strdup(args[cur_arg + 1]);
1922 }
1923
1924 return 0;
1925 }
1926 #endif
1927
1928 #ifdef USE_NS
1929 /* parse the "namespace" bind keyword */
bind_parse_namespace(char ** args,int cur_arg,struct proxy * px,struct bind_conf * conf,char ** err)1930 static int bind_parse_namespace(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
1931 {
1932 struct listener *l;
1933 char *namespace = NULL;
1934
1935 if (!*args[cur_arg + 1]) {
1936 memprintf(err, "'%s' : missing namespace id", args[cur_arg]);
1937 return ERR_ALERT | ERR_FATAL;
1938 }
1939 namespace = args[cur_arg + 1];
1940
1941 list_for_each_entry(l, &conf->listeners, by_bind) {
1942 l->netns = netns_store_lookup(namespace, strlen(namespace));
1943
1944 if (l->netns == NULL)
1945 l->netns = netns_store_insert(namespace);
1946
1947 if (l->netns == NULL) {
1948 ha_alert("Cannot open namespace '%s'.\n", args[cur_arg + 1]);
1949 return ERR_ALERT | ERR_FATAL;
1950 }
1951 }
1952 return 0;
1953 }
1954 #endif
1955
1956 #ifdef TCP_USER_TIMEOUT
1957 /* parse the "tcp-ut" server keyword */
srv_parse_tcp_ut(char ** args,int * cur_arg,struct proxy * px,struct server * newsrv,char ** err)1958 static int srv_parse_tcp_ut(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
1959 {
1960 const char *ptr = NULL;
1961 unsigned int timeout;
1962
1963 if (!*args[*cur_arg + 1]) {
1964 memprintf(err, "'%s' : missing TCP User Timeout value", args[*cur_arg]);
1965 return ERR_ALERT | ERR_FATAL;
1966 }
1967
1968 ptr = parse_time_err(args[*cur_arg + 1], &timeout, TIME_UNIT_MS);
1969 if (ptr == PARSE_TIME_OVER) {
1970 memprintf(err, "timer overflow in argument '%s' to '%s' (maximum value is 2147483647 ms or ~24.8 days)",
1971 args[*cur_arg+1], args[*cur_arg]);
1972 return ERR_ALERT | ERR_FATAL;
1973 }
1974 else if (ptr == PARSE_TIME_UNDER) {
1975 memprintf(err, "timer underflow in argument '%s' to '%s' (minimum non-null value is 1 ms)",
1976 args[*cur_arg+1], args[*cur_arg]);
1977 return ERR_ALERT | ERR_FATAL;
1978 }
1979 else if (ptr) {
1980 memprintf(err, "'%s' : expects a positive delay in milliseconds", args[*cur_arg]);
1981 return ERR_ALERT | ERR_FATAL;
1982 }
1983
1984 if (newsrv->addr.ss_family == AF_INET || newsrv->addr.ss_family == AF_INET6)
1985 newsrv->tcp_ut = timeout;
1986
1987 return 0;
1988 }
1989 #endif
1990
1991
1992 /* Note: must not be declared <const> as its list will be overwritten.
1993 * Note: fetches that may return multiple types must be declared as the lowest
1994 * common denominator, the type that can be casted into all other ones. For
1995 * instance v4/v6 must be declared v4.
1996 */
1997 static struct sample_fetch_kw_list sample_fetch_keywords = {ILH, {
1998 { "dst", smp_fetch_dst, 0, NULL, SMP_T_IPV4, SMP_USE_L4CLI },
1999 { "dst_is_local", smp_fetch_dst_is_local, 0, NULL, SMP_T_BOOL, SMP_USE_L4CLI },
2000 { "dst_port", smp_fetch_dport, 0, NULL, SMP_T_SINT, SMP_USE_L4CLI },
2001 { "src", smp_fetch_src, 0, NULL, SMP_T_IPV4, SMP_USE_L4CLI },
2002 { "src_is_local", smp_fetch_src_is_local, 0, NULL, SMP_T_BOOL, SMP_USE_L4CLI },
2003 { "src_port", smp_fetch_sport, 0, NULL, SMP_T_SINT, SMP_USE_L4CLI },
2004 #ifdef TCP_INFO
2005 { "fc_rtt", smp_fetch_fc_rtt, ARG1(0,STR), val_fc_time_value, SMP_T_SINT, SMP_USE_L4CLI },
2006 { "fc_rttvar", smp_fetch_fc_rttvar, ARG1(0,STR), val_fc_time_value, SMP_T_SINT, SMP_USE_L4CLI },
2007 #if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
2008 { "fc_unacked", smp_fetch_fc_unacked, ARG1(0,STR), var_fc_counter, SMP_T_SINT, SMP_USE_L4CLI },
2009 { "fc_sacked", smp_fetch_fc_sacked, ARG1(0,STR), var_fc_counter, SMP_T_SINT, SMP_USE_L4CLI },
2010 { "fc_retrans", smp_fetch_fc_retrans, ARG1(0,STR), var_fc_counter, SMP_T_SINT, SMP_USE_L4CLI },
2011 { "fc_fackets", smp_fetch_fc_fackets, ARG1(0,STR), var_fc_counter, SMP_T_SINT, SMP_USE_L4CLI },
2012 { "fc_lost", smp_fetch_fc_lost, ARG1(0,STR), var_fc_counter, SMP_T_SINT, SMP_USE_L4CLI },
2013 { "fc_reordering", smp_fetch_fc_reordering, ARG1(0,STR), var_fc_counter, SMP_T_SINT, SMP_USE_L4CLI },
2014 #endif // linux || freebsd || netbsd
2015 #endif // TCP_INFO
2016 { /* END */ },
2017 }};
2018
2019 INITCALL1(STG_REGISTER, sample_register_fetches, &sample_fetch_keywords);
2020
2021 /************************************************************************/
2022 /* All supported bind keywords must be declared here. */
2023 /************************************************************************/
2024
2025 /* Note: must not be declared <const> as its list will be overwritten.
2026 * Please take care of keeping this list alphabetically sorted, doing so helps
2027 * all code contributors.
2028 * Optional keywords are also declared with a NULL ->parse() function so that
2029 * the config parser can report an appropriate error when a known keyword was
2030 * not enabled.
2031 */
2032 static struct bind_kw_list bind_kws = { "TCP", { }, {
2033 #ifdef TCP_DEFER_ACCEPT
2034 { "defer-accept", bind_parse_defer_accept, 0 }, /* wait for some data for 1 second max before doing accept */
2035 #endif
2036 #ifdef SO_BINDTODEVICE
2037 { "interface", bind_parse_interface, 1 }, /* specifically bind to this interface */
2038 #endif
2039 #ifdef TCP_MAXSEG
2040 { "mss", bind_parse_mss, 1 }, /* set MSS of listening socket */
2041 #endif
2042 #ifdef TCP_USER_TIMEOUT
2043 { "tcp-ut", bind_parse_tcp_ut, 1 }, /* set User Timeout on listening socket */
2044 #endif
2045 #ifdef TCP_FASTOPEN
2046 { "tfo", bind_parse_tfo, 0 }, /* enable TCP_FASTOPEN of listening socket */
2047 #endif
2048 #ifdef CONFIG_HAP_TRANSPARENT
2049 { "transparent", bind_parse_transparent, 0 }, /* transparently bind to the specified addresses */
2050 #endif
2051 #ifdef IPV6_V6ONLY
2052 { "v4v6", bind_parse_v4v6, 0 }, /* force socket to bind to IPv4+IPv6 */
2053 { "v6only", bind_parse_v6only, 0 }, /* force socket to bind to IPv6 only */
2054 #endif
2055 #ifdef USE_NS
2056 { "namespace", bind_parse_namespace, 1 },
2057 #endif
2058 /* the versions with the NULL parse function*/
2059 { "defer-accept", NULL, 0 },
2060 { "interface", NULL, 1 },
2061 { "mss", NULL, 1 },
2062 { "transparent", NULL, 0 },
2063 { "v4v6", NULL, 0 },
2064 { "v6only", NULL, 0 },
2065 { NULL, NULL, 0 },
2066 }};
2067
2068 INITCALL1(STG_REGISTER, bind_register_keywords, &bind_kws);
2069
2070 static struct srv_kw_list srv_kws = { "TCP", { }, {
2071 #ifdef TCP_USER_TIMEOUT
2072 { "tcp-ut", srv_parse_tcp_ut, 1, 1 }, /* set TCP user timeout on server */
2073 #endif
2074 { NULL, NULL, 0 },
2075 }};
2076
2077 INITCALL1(STG_REGISTER, srv_register_keywords, &srv_kws);
2078
2079 static struct action_kw_list tcp_req_conn_actions = {ILH, {
2080 { "set-src", tcp_parse_set_src_dst },
2081 { "set-src-port", tcp_parse_set_src_dst },
2082 { "set-dst" , tcp_parse_set_src_dst },
2083 { "set-dst-port", tcp_parse_set_src_dst },
2084 { "silent-drop", tcp_parse_silent_drop },
2085 { /* END */ }
2086 }};
2087
2088 INITCALL1(STG_REGISTER, tcp_req_conn_keywords_register, &tcp_req_conn_actions);
2089
2090 static struct action_kw_list tcp_req_sess_actions = {ILH, {
2091 { "set-src", tcp_parse_set_src_dst },
2092 { "set-src-port", tcp_parse_set_src_dst },
2093 { "set-dst" , tcp_parse_set_src_dst },
2094 { "set-dst-port", tcp_parse_set_src_dst },
2095 { "silent-drop", tcp_parse_silent_drop },
2096 { /* END */ }
2097 }};
2098
2099 INITCALL1(STG_REGISTER, tcp_req_sess_keywords_register, &tcp_req_sess_actions);
2100
2101 static struct action_kw_list tcp_req_cont_actions = {ILH, {
2102 { "set-dst" , tcp_parse_set_src_dst },
2103 { "set-dst-port", tcp_parse_set_src_dst },
2104 { "silent-drop", tcp_parse_silent_drop },
2105 { /* END */ }
2106 }};
2107
2108 INITCALL1(STG_REGISTER, tcp_req_cont_keywords_register, &tcp_req_cont_actions);
2109
2110 static struct action_kw_list tcp_res_cont_actions = {ILH, {
2111 { "silent-drop", tcp_parse_silent_drop },
2112 { /* END */ }
2113 }};
2114
2115 INITCALL1(STG_REGISTER, tcp_res_cont_keywords_register, &tcp_res_cont_actions);
2116
2117 static struct action_kw_list http_req_actions = {ILH, {
2118 { "silent-drop", tcp_parse_silent_drop },
2119 { "set-src", tcp_parse_set_src_dst },
2120 { "set-src-port", tcp_parse_set_src_dst },
2121 { "set-dst", tcp_parse_set_src_dst },
2122 { "set-dst-port", tcp_parse_set_src_dst },
2123 { /* END */ }
2124 }};
2125
2126 INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
2127
2128 static struct action_kw_list http_res_actions = {ILH, {
2129 { "silent-drop", tcp_parse_silent_drop },
2130 { /* END */ }
2131 }};
2132
2133 INITCALL1(STG_REGISTER, http_res_keywords_register, &http_res_actions);
2134
2135 REGISTER_BUILD_OPTS("Built with transparent proxy support using:"
2136 #if defined(IP_TRANSPARENT)
2137 " IP_TRANSPARENT"
2138 #endif
2139 #if defined(IPV6_TRANSPARENT)
2140 " IPV6_TRANSPARENT"
2141 #endif
2142 #if defined(IP_FREEBIND)
2143 " IP_FREEBIND"
2144 #endif
2145 #if defined(IP_BINDANY)
2146 " IP_BINDANY"
2147 #endif
2148 #if defined(IPV6_BINDANY)
2149 " IPV6_BINDANY"
2150 #endif
2151 #if defined(SO_BINDANY)
2152 " SO_BINDANY"
2153 #endif
2154 "");
2155
2156
2157 /*
2158 * Local variables:
2159 * c-indent-level: 8
2160 * c-basic-offset: 8
2161 * End:
2162 */
2163