blob: 80c10fdc98a276717a1077c236093aa009d69b01 [file] [log] [blame]
Willy Tarreaue6b98942007-10-29 01:09:36 +01001/*
2 * AF_INET/AF_INET6 SOCK_STREAM protocol layer (tcp)
3 *
Willy Tarreau1a687942010-05-23 22:40:30 +02004 * Copyright 2000-2010 Willy Tarreau <w@1wt.eu>
Willy Tarreaue6b98942007-10-29 01:09:36 +01005 *
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#include <ctype.h>
14#include <errno.h>
15#include <fcntl.h>
16#include <stdio.h>
17#include <stdlib.h>
18#include <string.h>
19#include <time.h>
20
21#include <sys/param.h>
22#include <sys/socket.h>
23#include <sys/stat.h>
24#include <sys/types.h>
25#include <sys/un.h>
26
Dmitry Sivachenkocaf58982009-08-24 15:11:06 +040027#include <netinet/tcp.h>
28
Willy Tarreaub6866442008-07-14 23:54:42 +020029#include <common/cfgparse.h>
Willy Tarreaue6b98942007-10-29 01:09:36 +010030#include <common/compat.h>
31#include <common/config.h>
32#include <common/debug.h>
33#include <common/errors.h>
Willy Tarreaue6b98942007-10-29 01:09:36 +010034#include <common/mini-clist.h>
35#include <common/standard.h>
Willy Tarreaue6b98942007-10-29 01:09:36 +010036
Willy Tarreaue6b98942007-10-29 01:09:36 +010037#include <types/global.h>
Willy Tarreau9650f372009-08-16 14:02:45 +020038#include <types/server.h>
Willy Tarreaue6b98942007-10-29 01:09:36 +010039
40#include <proto/acl.h>
Willy Tarreaue6b98942007-10-29 01:09:36 +010041#include <proto/buffers.h>
Willy Tarreau03fa5df2010-05-24 21:02:37 +020042#include <proto/frontend.h>
Willy Tarreau9650f372009-08-16 14:02:45 +020043#include <proto/log.h>
Willy Tarreau645513a2010-05-24 20:55:15 +020044#include <proto/pattern.h>
Willy Tarreau9650f372009-08-16 14:02:45 +020045#include <proto/port_range.h>
Willy Tarreaue6b98942007-10-29 01:09:36 +010046#include <proto/protocols.h>
47#include <proto/proto_tcp.h>
Willy Tarreaub6866442008-07-14 23:54:42 +020048#include <proto/proxy.h>
Willy Tarreaua975b8f2010-06-05 19:13:27 +020049#include <proto/stick_table.h>
Willy Tarreaue6b98942007-10-29 01:09:36 +010050#include <proto/stream_sock.h>
Willy Tarreaua975b8f2010-06-05 19:13:27 +020051#include <proto/task.h>
Willy Tarreaue6b98942007-10-29 01:09:36 +010052
Willy Tarreaue8c66af2008-01-13 18:40:14 +010053#ifdef CONFIG_HAP_CTTPROXY
54#include <import/ip_tproxy.h>
55#endif
56
Willy Tarreaue6b98942007-10-29 01:09:36 +010057static int tcp_bind_listeners(struct protocol *proto);
58
59/* Note: must not be declared <const> as its list will be overwritten */
60static struct protocol proto_tcpv4 = {
61 .name = "tcpv4",
62 .sock_domain = AF_INET,
63 .sock_type = SOCK_STREAM,
64 .sock_prot = IPPROTO_TCP,
65 .sock_family = AF_INET,
66 .sock_addrlen = sizeof(struct sockaddr_in),
67 .l3_addrlen = 32/8,
Willy Tarreaueb472682010-05-28 18:46:57 +020068 .accept = &stream_sock_accept,
Willy Tarreaue6b98942007-10-29 01:09:36 +010069 .read = &stream_sock_read,
70 .write = &stream_sock_write,
71 .bind_all = tcp_bind_listeners,
72 .unbind_all = unbind_all_listeners,
73 .enable_all = enable_all_listeners,
74 .listeners = LIST_HEAD_INIT(proto_tcpv4.listeners),
75 .nb_listeners = 0,
76};
77
78/* Note: must not be declared <const> as its list will be overwritten */
79static struct protocol proto_tcpv6 = {
80 .name = "tcpv6",
81 .sock_domain = AF_INET6,
82 .sock_type = SOCK_STREAM,
83 .sock_prot = IPPROTO_TCP,
84 .sock_family = AF_INET6,
85 .sock_addrlen = sizeof(struct sockaddr_in6),
86 .l3_addrlen = 128/8,
Willy Tarreaueb472682010-05-28 18:46:57 +020087 .accept = &stream_sock_accept,
Willy Tarreaue6b98942007-10-29 01:09:36 +010088 .read = &stream_sock_read,
89 .write = &stream_sock_write,
90 .bind_all = tcp_bind_listeners,
91 .unbind_all = unbind_all_listeners,
92 .enable_all = enable_all_listeners,
93 .listeners = LIST_HEAD_INIT(proto_tcpv6.listeners),
94 .nb_listeners = 0,
95};
96
Willy Tarreaue8c66af2008-01-13 18:40:14 +010097
98/* Binds ipv4 address <local> to socket <fd>, unless <flags> is set, in which
99 * case we try to bind <remote>. <flags> is a 2-bit field consisting of :
100 * - 0 : ignore remote address (may even be a NULL pointer)
101 * - 1 : use provided address
102 * - 2 : use provided port
103 * - 3 : use both
104 *
105 * The function supports multiple foreign binding methods :
106 * - linux_tproxy: we directly bind to the foreign address
107 * - cttproxy: we bind to a local address then nat.
108 * The second one can be used as a fallback for the first one.
109 * This function returns 0 when everything's OK, 1 if it could not bind, to the
110 * local address, 2 if it could not bind to the foreign address.
111 */
112int tcpv4_bind_socket(int fd, int flags, struct sockaddr_in *local, struct sockaddr_in *remote)
113{
114 struct sockaddr_in bind_addr;
115 int foreign_ok = 0;
116 int ret;
117
118#ifdef CONFIG_HAP_LINUX_TPROXY
119 static int ip_transp_working = 1;
120 if (flags && ip_transp_working) {
121 if (setsockopt(fd, SOL_IP, IP_TRANSPARENT, (char *) &one, sizeof(one)) == 0
122 || setsockopt(fd, SOL_IP, IP_FREEBIND, (char *) &one, sizeof(one)) == 0)
123 foreign_ok = 1;
124 else
125 ip_transp_working = 0;
126 }
127#endif
128 if (flags) {
129 memset(&bind_addr, 0, sizeof(bind_addr));
130 if (flags & 1)
131 bind_addr.sin_addr = remote->sin_addr;
132 if (flags & 2)
133 bind_addr.sin_port = remote->sin_port;
134 }
135
136 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &one, sizeof(one));
137 if (foreign_ok) {
138 ret = bind(fd, (struct sockaddr *)&bind_addr, sizeof(bind_addr));
139 if (ret < 0)
140 return 2;
141 }
142 else {
143 ret = bind(fd, (struct sockaddr *)local, sizeof(*local));
144 if (ret < 0)
145 return 1;
146 }
147
148 if (!flags)
149 return 0;
150
151#ifdef CONFIG_HAP_CTTPROXY
152 if (!foreign_ok) {
153 struct in_tproxy itp1, itp2;
154 memset(&itp1, 0, sizeof(itp1));
155
156 itp1.op = TPROXY_ASSIGN;
157 itp1.v.addr.faddr = bind_addr.sin_addr;
158 itp1.v.addr.fport = bind_addr.sin_port;
159
160 /* set connect flag on socket */
161 itp2.op = TPROXY_FLAGS;
162 itp2.v.flags = ITP_CONNECT | ITP_ONCE;
163
164 if (setsockopt(fd, SOL_IP, IP_TPROXY, &itp1, sizeof(itp1)) != -1 &&
165 setsockopt(fd, SOL_IP, IP_TPROXY, &itp2, sizeof(itp2)) != -1) {
166 foreign_ok = 1;
167 }
168 }
169#endif
170 if (!foreign_ok)
171 /* we could not bind to a foreign address */
172 return 2;
173
174 return 0;
175}
Willy Tarreaue6b98942007-10-29 01:09:36 +0100176
Willy Tarreau9650f372009-08-16 14:02:45 +0200177
178/*
179 * This function initiates a connection to the server assigned to this session
Willy Tarreaub1d67742010-03-29 19:36:59 +0200180 * (s->srv, s->srv_addr). It will assign a server if none is assigned yet. A
181 * source address may be pointed to by <from_addr>. Note that this is only used
182 * in case of transparent proxying. Normal source bind addresses are still
183 * determined locally (due to the possible need of a source port).
184 *
Willy Tarreau9650f372009-08-16 14:02:45 +0200185 * It can return one of :
186 * - SN_ERR_NONE if everything's OK
187 * - SN_ERR_SRVTO if there are no more servers
188 * - SN_ERR_SRVCL if the connection was refused by the server
189 * - SN_ERR_PRXCOND if the connection has been limited by the proxy (maxconn)
190 * - SN_ERR_RESOURCE if a system resource is lacking (eg: fd limits, ports, ...)
191 * - SN_ERR_INTERNAL for any other purely internal errors
192 * Additionnally, in the case of SN_ERR_RESOURCE, an emergency log will be emitted.
193 */
194int tcpv4_connect_server(struct stream_interface *si,
195 struct proxy *be, struct server *srv,
Willy Tarreaub1d67742010-03-29 19:36:59 +0200196 struct sockaddr *srv_addr, struct sockaddr *from_addr)
Willy Tarreau9650f372009-08-16 14:02:45 +0200197{
198 int fd;
199
200 if ((fd = si->fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) {
201 qfprintf(stderr, "Cannot get a server socket.\n");
202
203 if (errno == ENFILE)
204 send_log(be, LOG_EMERG,
205 "Proxy %s reached system FD limit at %d. Please check system tunables.\n",
206 be->id, maxfd);
207 else if (errno == EMFILE)
208 send_log(be, LOG_EMERG,
209 "Proxy %s reached process FD limit at %d. Please check 'ulimit-n' and restart.\n",
210 be->id, maxfd);
211 else if (errno == ENOBUFS || errno == ENOMEM)
212 send_log(be, LOG_EMERG,
213 "Proxy %s reached system memory limit at %d sockets. Please check system tunables.\n",
214 be->id, maxfd);
215 /* this is a resource error */
216 return SN_ERR_RESOURCE;
217 }
218
219 if (fd >= global.maxsock) {
220 /* do not log anything there, it's a normal condition when this option
221 * is used to serialize connections to a server !
222 */
223 Alert("socket(): not enough free sockets. Raise -n argument. Giving up.\n");
224 close(fd);
225 return SN_ERR_PRXCOND; /* it is a configuration limit */
226 }
227
228 if ((fcntl(fd, F_SETFL, O_NONBLOCK)==-1) ||
229 (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &one, sizeof(one)) == -1)) {
230 qfprintf(stderr,"Cannot set client socket to non blocking mode.\n");
231 close(fd);
232 return SN_ERR_INTERNAL;
233 }
234
235 if (be->options & PR_O_TCP_SRV_KA)
236 setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (char *) &one, sizeof(one));
237
238 if (be->options & PR_O_TCP_NOLING)
239 setsockopt(fd, SOL_SOCKET, SO_LINGER, (struct linger *) &nolinger, sizeof(struct linger));
240
241 /* allow specific binding :
242 * - server-specific at first
243 * - proxy-specific next
244 */
245 if (srv != NULL && srv->state & SRV_BIND_SRC) {
Willy Tarreau9650f372009-08-16 14:02:45 +0200246 int ret, flags = 0;
247
Willy Tarreau9650f372009-08-16 14:02:45 +0200248 switch (srv->state & SRV_TPROXY_MASK) {
249 case SRV_TPROXY_ADDR:
Willy Tarreau9650f372009-08-16 14:02:45 +0200250 case SRV_TPROXY_CLI:
Willy Tarreaub1d67742010-03-29 19:36:59 +0200251 flags = 3;
252 break;
Willy Tarreau9650f372009-08-16 14:02:45 +0200253 case SRV_TPROXY_CIP:
Willy Tarreau090466c2009-09-07 11:51:47 +0200254 case SRV_TPROXY_DYN:
Willy Tarreaub1d67742010-03-29 19:36:59 +0200255 flags = 1;
Willy Tarreau9650f372009-08-16 14:02:45 +0200256 break;
257 }
Willy Tarreaub1d67742010-03-29 19:36:59 +0200258
Willy Tarreau9650f372009-08-16 14:02:45 +0200259#ifdef SO_BINDTODEVICE
260 /* Note: this might fail if not CAP_NET_RAW */
261 if (srv->iface_name)
262 setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, srv->iface_name, srv->iface_len + 1);
263#endif
264
265 if (srv->sport_range) {
266 int attempts = 10; /* should be more than enough to find a spare port */
267 struct sockaddr_in src;
268
269 ret = 1;
270 src = srv->source_addr;
271
272 do {
273 /* note: in case of retry, we may have to release a previously
274 * allocated port, hence this loop's construct.
275 */
Willy Tarreau8d5d77e2009-10-18 07:25:52 +0200276 port_range_release_port(fdinfo[fd].port_range, fdinfo[fd].local_port);
277 fdinfo[fd].port_range = NULL;
Willy Tarreau9650f372009-08-16 14:02:45 +0200278
279 if (!attempts)
280 break;
281 attempts--;
282
Willy Tarreau8d5d77e2009-10-18 07:25:52 +0200283 fdinfo[fd].local_port = port_range_alloc_port(srv->sport_range);
284 if (!fdinfo[fd].local_port)
Willy Tarreau9650f372009-08-16 14:02:45 +0200285 break;
286
Willy Tarreau8d5d77e2009-10-18 07:25:52 +0200287 fdinfo[fd].port_range = srv->sport_range;
288 src.sin_port = htons(fdinfo[fd].local_port);
Willy Tarreau9650f372009-08-16 14:02:45 +0200289
Willy Tarreaub1d67742010-03-29 19:36:59 +0200290 ret = tcpv4_bind_socket(fd, flags, &src, (struct sockaddr_in *)from_addr);
Willy Tarreau9650f372009-08-16 14:02:45 +0200291 } while (ret != 0); /* binding NOK */
292 }
293 else {
Willy Tarreaub1d67742010-03-29 19:36:59 +0200294 ret = tcpv4_bind_socket(fd, flags, &srv->source_addr, (struct sockaddr_in *)from_addr);
Willy Tarreau9650f372009-08-16 14:02:45 +0200295 }
296
297 if (ret) {
Willy Tarreau8d5d77e2009-10-18 07:25:52 +0200298 port_range_release_port(fdinfo[fd].port_range, fdinfo[fd].local_port);
299 fdinfo[fd].port_range = NULL;
Willy Tarreau9650f372009-08-16 14:02:45 +0200300 close(fd);
301
302 if (ret == 1) {
303 Alert("Cannot bind to source address before connect() for server %s/%s. Aborting.\n",
304 be->id, srv->id);
305 send_log(be, LOG_EMERG,
306 "Cannot bind to source address before connect() for server %s/%s.\n",
307 be->id, srv->id);
308 } else {
309 Alert("Cannot bind to tproxy source address before connect() for server %s/%s. Aborting.\n",
310 be->id, srv->id);
311 send_log(be, LOG_EMERG,
312 "Cannot bind to tproxy source address before connect() for server %s/%s.\n",
313 be->id, srv->id);
314 }
315 return SN_ERR_RESOURCE;
316 }
317 }
318 else if (be->options & PR_O_BIND_SRC) {
Willy Tarreau9650f372009-08-16 14:02:45 +0200319 int ret, flags = 0;
320
Willy Tarreau9650f372009-08-16 14:02:45 +0200321 switch (be->options & PR_O_TPXY_MASK) {
322 case PR_O_TPXY_ADDR:
Willy Tarreau9650f372009-08-16 14:02:45 +0200323 case PR_O_TPXY_CLI:
Willy Tarreaub1d67742010-03-29 19:36:59 +0200324 flags = 3;
325 break;
Willy Tarreau9650f372009-08-16 14:02:45 +0200326 case PR_O_TPXY_CIP:
Willy Tarreau090466c2009-09-07 11:51:47 +0200327 case PR_O_TPXY_DYN:
Willy Tarreaub1d67742010-03-29 19:36:59 +0200328 flags = 1;
Willy Tarreau9650f372009-08-16 14:02:45 +0200329 break;
330 }
Willy Tarreaub1d67742010-03-29 19:36:59 +0200331
Willy Tarreau9650f372009-08-16 14:02:45 +0200332#ifdef SO_BINDTODEVICE
333 /* Note: this might fail if not CAP_NET_RAW */
334 if (be->iface_name)
335 setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, be->iface_name, be->iface_len + 1);
336#endif
Willy Tarreaub1d67742010-03-29 19:36:59 +0200337 ret = tcpv4_bind_socket(fd, flags, &be->source_addr, (struct sockaddr_in *)from_addr);
Willy Tarreau9650f372009-08-16 14:02:45 +0200338 if (ret) {
339 close(fd);
340 if (ret == 1) {
341 Alert("Cannot bind to source address before connect() for proxy %s. Aborting.\n",
342 be->id);
343 send_log(be, LOG_EMERG,
344 "Cannot bind to source address before connect() for proxy %s.\n",
345 be->id);
346 } else {
347 Alert("Cannot bind to tproxy source address before connect() for proxy %s. Aborting.\n",
348 be->id);
349 send_log(be, LOG_EMERG,
350 "Cannot bind to tproxy source address before connect() for proxy %s.\n",
351 be->id);
352 }
353 return SN_ERR_RESOURCE;
354 }
355 }
356
Dmitry Sivachenkocaf58982009-08-24 15:11:06 +0400357#if defined(TCP_QUICKACK)
Willy Tarreau9650f372009-08-16 14:02:45 +0200358 /* disabling tcp quick ack now allows the first request to leave the
359 * machine with the first ACK. We only do this if there are pending
360 * data in the buffer.
361 */
362 if ((be->options2 & PR_O2_SMARTCON) && si->ob->send_max)
Dmitry Sivachenkocaf58982009-08-24 15:11:06 +0400363 setsockopt(fd, IPPROTO_TCP, TCP_QUICKACK, (char *) &zero, sizeof(zero));
Willy Tarreau9650f372009-08-16 14:02:45 +0200364#endif
365
Willy Tarreaue803de22010-01-21 17:43:04 +0100366 if (global.tune.server_sndbuf)
367 setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &global.tune.server_sndbuf, sizeof(global.tune.server_sndbuf));
368
369 if (global.tune.server_rcvbuf)
370 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &global.tune.server_rcvbuf, sizeof(global.tune.server_rcvbuf));
371
Willy Tarreau9650f372009-08-16 14:02:45 +0200372 if ((connect(fd, (struct sockaddr *)srv_addr, sizeof(struct sockaddr_in)) == -1) &&
373 (errno != EINPROGRESS) && (errno != EALREADY) && (errno != EISCONN)) {
374
375 if (errno == EAGAIN || errno == EADDRINUSE) {
376 char *msg;
377 if (errno == EAGAIN) /* no free ports left, try again later */
378 msg = "no free ports";
379 else
380 msg = "local address already in use";
381
382 qfprintf(stderr,"Cannot connect: %s.\n",msg);
Willy Tarreau8d5d77e2009-10-18 07:25:52 +0200383 port_range_release_port(fdinfo[fd].port_range, fdinfo[fd].local_port);
384 fdinfo[fd].port_range = NULL;
Willy Tarreau9650f372009-08-16 14:02:45 +0200385 close(fd);
386 send_log(be, LOG_EMERG,
387 "Connect() failed for server %s/%s: %s.\n",
388 be->id, srv->id, msg);
389 return SN_ERR_RESOURCE;
390 } else if (errno == ETIMEDOUT) {
391 //qfprintf(stderr,"Connect(): ETIMEDOUT");
Willy Tarreau8d5d77e2009-10-18 07:25:52 +0200392 port_range_release_port(fdinfo[fd].port_range, fdinfo[fd].local_port);
393 fdinfo[fd].port_range = NULL;
Willy Tarreau9650f372009-08-16 14:02:45 +0200394 close(fd);
395 return SN_ERR_SRVTO;
396 } else {
397 // (errno == ECONNREFUSED || errno == ENETUNREACH || errno == EACCES || errno == EPERM)
398 //qfprintf(stderr,"Connect(): %d", errno);
Willy Tarreau8d5d77e2009-10-18 07:25:52 +0200399 port_range_release_port(fdinfo[fd].port_range, fdinfo[fd].local_port);
400 fdinfo[fd].port_range = NULL;
Willy Tarreau9650f372009-08-16 14:02:45 +0200401 close(fd);
402 return SN_ERR_SRVCL;
403 }
404 }
405
406 fdtab[fd].owner = si;
407 fdtab[fd].state = FD_STCONN; /* connection in progress */
408 fdtab[fd].flags = FD_FL_TCP | FD_FL_TCP_NODELAY;
409 fdtab[fd].cb[DIR_RD].f = &stream_sock_read;
410 fdtab[fd].cb[DIR_RD].b = si->ib;
411 fdtab[fd].cb[DIR_WR].f = &stream_sock_write;
412 fdtab[fd].cb[DIR_WR].b = si->ob;
413
Willy Tarreau8d5d77e2009-10-18 07:25:52 +0200414 fdinfo[fd].peeraddr = (struct sockaddr *)srv_addr;
415 fdinfo[fd].peerlen = sizeof(struct sockaddr_in);
Willy Tarreau9650f372009-08-16 14:02:45 +0200416
417 fd_insert(fd);
418 EV_FD_SET(fd, DIR_WR); /* for connect status */
419
420 si->state = SI_ST_CON;
421 si->flags |= SI_FL_CAP_SPLTCP; /* TCP supports splicing */
422 si->exp = tick_add_ifset(now_ms, be->timeout.connect);
423
424 return SN_ERR_NONE; /* connection is OK */
425}
426
427
Willy Tarreaue6b98942007-10-29 01:09:36 +0100428/* This function tries to bind a TCPv4/v6 listener. It may return a warning or
429 * an error message in <err> if the message is at most <errlen> bytes long
430 * (including '\0'). The return value is composed from ERR_ABORT, ERR_WARN,
431 * ERR_ALERT, ERR_RETRYABLE and ERR_FATAL. ERR_NONE indicates that everything
432 * was alright and that no message was returned. ERR_RETRYABLE means that an
433 * error occurred but that it may vanish after a retry (eg: port in use), and
434 * ERR_FATAL indicates a non-fixable error.ERR_WARN and ERR_ALERT do not alter
435 * the meaning of the error, but just indicate that a message is present which
436 * should be displayed with the respective level. Last, ERR_ABORT indicates
437 * that it's pointless to try to start other listeners. No error message is
438 * returned if errlen is NULL.
439 */
440int tcp_bind_listener(struct listener *listener, char *errmsg, int errlen)
441{
442 __label__ tcp_return, tcp_close_return;
443 int fd, err;
444 const char *msg = NULL;
445
446 /* ensure we never return garbage */
447 if (errmsg && errlen)
448 *errmsg = 0;
449
450 if (listener->state != LI_ASSIGNED)
451 return ERR_NONE; /* already bound */
452
453 err = ERR_NONE;
454
455 if ((fd = socket(listener->addr.ss_family, SOCK_STREAM, IPPROTO_TCP)) == -1) {
456 err |= ERR_RETRYABLE | ERR_ALERT;
457 msg = "cannot create listening socket";
458 goto tcp_return;
459 }
Willy Tarreauedcf6682008-11-30 23:15:34 +0100460
Willy Tarreaue6b98942007-10-29 01:09:36 +0100461 if (fd >= global.maxsock) {
462 err |= ERR_FATAL | ERR_ABORT | ERR_ALERT;
463 msg = "not enough free sockets (raise '-n' parameter)";
464 goto tcp_close_return;
465 }
466
Willy Tarreaufb14edc2009-06-14 15:24:37 +0200467 if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
Willy Tarreaue6b98942007-10-29 01:09:36 +0100468 err |= ERR_FATAL | ERR_ALERT;
469 msg = "cannot make socket non-blocking";
470 goto tcp_close_return;
471 }
472
473 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &one, sizeof(one)) == -1) {
474 /* not fatal but should be reported */
475 msg = "cannot do so_reuseaddr";
476 err |= ERR_ALERT;
477 }
478
479 if (listener->options & LI_O_NOLINGER)
480 setsockopt(fd, SOL_SOCKET, SO_LINGER, (struct linger *) &nolinger, sizeof(struct linger));
Willy Tarreauedcf6682008-11-30 23:15:34 +0100481
Willy Tarreaue6b98942007-10-29 01:09:36 +0100482#ifdef SO_REUSEPORT
483 /* OpenBSD supports this. As it's present in old libc versions of Linux,
484 * it might return an error that we will silently ignore.
485 */
486 setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, (char *) &one, sizeof(one));
487#endif
Willy Tarreaub1e52e82008-01-13 14:49:51 +0100488#ifdef CONFIG_HAP_LINUX_TPROXY
Willy Tarreauedcf6682008-11-30 23:15:34 +0100489 if ((listener->options & LI_O_FOREIGN)
Willy Tarreau0a459892008-01-13 17:37:16 +0100490 && (setsockopt(fd, SOL_IP, IP_TRANSPARENT, (char *) &one, sizeof(one)) == -1)
491 && (setsockopt(fd, SOL_IP, IP_FREEBIND, (char *) &one, sizeof(one)) == -1)) {
Willy Tarreaub1e52e82008-01-13 14:49:51 +0100492 msg = "cannot make listening socket transparent";
493 err |= ERR_ALERT;
494 }
495#endif
Willy Tarreau5e6e2042009-02-04 17:19:29 +0100496#ifdef SO_BINDTODEVICE
497 /* Note: this might fail if not CAP_NET_RAW */
498 if (listener->interface) {
499 if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE,
Willy Tarreau604e8302009-03-06 00:48:23 +0100500 listener->interface, strlen(listener->interface) + 1) == -1) {
Willy Tarreau5e6e2042009-02-04 17:19:29 +0100501 msg = "cannot bind listener to device";
502 err |= ERR_WARN;
503 }
504 }
505#endif
Dmitry Sivachenkocaf58982009-08-24 15:11:06 +0400506#if defined(TCP_MAXSEG)
Willy Tarreaube1b9182009-06-14 18:48:19 +0200507 if (listener->maxseg) {
Dmitry Sivachenkocaf58982009-08-24 15:11:06 +0400508 if (setsockopt(fd, IPPROTO_TCP, TCP_MAXSEG,
Willy Tarreaube1b9182009-06-14 18:48:19 +0200509 &listener->maxseg, sizeof(listener->maxseg)) == -1) {
510 msg = "cannot set MSS";
511 err |= ERR_WARN;
512 }
513 }
514#endif
Willy Tarreaucb6cd432009-10-13 07:34:14 +0200515#if defined(TCP_DEFER_ACCEPT)
516 if (listener->options & LI_O_DEF_ACCEPT) {
517 /* defer accept by up to one second */
518 int accept_delay = 1;
519 if (setsockopt(fd, IPPROTO_TCP, TCP_DEFER_ACCEPT, &accept_delay, sizeof(accept_delay)) == -1) {
520 msg = "cannot enable DEFER_ACCEPT";
521 err |= ERR_WARN;
522 }
523 }
524#endif
Willy Tarreaue6b98942007-10-29 01:09:36 +0100525 if (bind(fd, (struct sockaddr *)&listener->addr, listener->proto->sock_addrlen) == -1) {
526 err |= ERR_RETRYABLE | ERR_ALERT;
527 msg = "cannot bind socket";
528 goto tcp_close_return;
529 }
Willy Tarreauedcf6682008-11-30 23:15:34 +0100530
Willy Tarreauc73ce2b2008-01-06 10:55:10 +0100531 if (listen(fd, listener->backlog ? listener->backlog : listener->maxconn) == -1) {
Willy Tarreaue6b98942007-10-29 01:09:36 +0100532 err |= ERR_RETRYABLE | ERR_ALERT;
533 msg = "cannot listen to socket";
534 goto tcp_close_return;
535 }
Willy Tarreauedcf6682008-11-30 23:15:34 +0100536
Dmitry Sivachenkocaf58982009-08-24 15:11:06 +0400537#if defined(TCP_QUICKACK)
Willy Tarreau9ea05a72009-06-14 12:07:01 +0200538 if (listener->options & LI_O_NOQUICKACK)
Dmitry Sivachenkocaf58982009-08-24 15:11:06 +0400539 setsockopt(fd, IPPROTO_TCP, TCP_QUICKACK, (char *) &zero, sizeof(zero));
Willy Tarreau9ea05a72009-06-14 12:07:01 +0200540#endif
541
Willy Tarreaue6b98942007-10-29 01:09:36 +0100542 /* the socket is ready */
543 listener->fd = fd;
544 listener->state = LI_LISTEN;
545
Willy Tarreaueabf3132008-08-29 23:36:51 +0200546 fdtab[fd].owner = listener; /* reference the listener instead of a task */
Willy Tarreaue6b98942007-10-29 01:09:36 +0100547 fdtab[fd].state = FD_STLISTEN;
Willy Tarreaueb472682010-05-28 18:46:57 +0200548 fdtab[fd].flags = FD_FL_TCP | ((listener->options & LI_O_NOLINGER) ? FD_FL_TCP_NOLING : 0);
549 fdtab[fd].cb[DIR_RD].f = listener->proto->accept;
550 fdtab[fd].cb[DIR_WR].f = NULL; /* never called */
551 fdtab[fd].cb[DIR_RD].b = fdtab[fd].cb[DIR_WR].b = NULL;
Willy Tarreau5d707e12009-06-28 11:09:07 +0200552
Willy Tarreau8d5d77e2009-10-18 07:25:52 +0200553 fdinfo[fd].peeraddr = NULL;
554 fdinfo[fd].peerlen = 0;
Willy Tarreaueb472682010-05-28 18:46:57 +0200555 fd_insert(fd);
556
Willy Tarreaue6b98942007-10-29 01:09:36 +0100557 tcp_return:
558 if (msg && errlen)
559 strlcpy2(errmsg, msg, errlen);
560 return err;
561
562 tcp_close_return:
563 close(fd);
564 goto tcp_return;
565}
566
567/* This function creates all TCP sockets bound to the protocol entry <proto>.
568 * It is intended to be used as the protocol's bind_all() function.
569 * The sockets will be registered but not added to any fd_set, in order not to
570 * loose them across the fork(). A call to enable_all_listeners() is needed
571 * to complete initialization. The return value is composed from ERR_*.
572 */
573static int tcp_bind_listeners(struct protocol *proto)
574{
575 struct listener *listener;
576 int err = ERR_NONE;
577
578 list_for_each_entry(listener, &proto->listeners, proto_list) {
579 err |= tcp_bind_listener(listener, NULL, 0);
580 if ((err & ERR_CODE) == ERR_ABORT)
581 break;
582 }
583
584 return err;
585}
586
587/* Add listener to the list of tcpv4 listeners. The listener's state
588 * is automatically updated from LI_INIT to LI_ASSIGNED. The number of
589 * listeners is updated. This is the function to use to add a new listener.
590 */
591void tcpv4_add_listener(struct listener *listener)
592{
593 if (listener->state != LI_INIT)
594 return;
595 listener->state = LI_ASSIGNED;
596 listener->proto = &proto_tcpv4;
597 LIST_ADDQ(&proto_tcpv4.listeners, &listener->proto_list);
598 proto_tcpv4.nb_listeners++;
599}
600
601/* Add listener to the list of tcpv4 listeners. The listener's state
602 * is automatically updated from LI_INIT to LI_ASSIGNED. The number of
603 * listeners is updated. This is the function to use to add a new listener.
604 */
605void tcpv6_add_listener(struct listener *listener)
606{
607 if (listener->state != LI_INIT)
608 return;
609 listener->state = LI_ASSIGNED;
610 listener->proto = &proto_tcpv6;
611 LIST_ADDQ(&proto_tcpv6.listeners, &listener->proto_list);
612 proto_tcpv6.nb_listeners++;
613}
614
Willy Tarreauedcf6682008-11-30 23:15:34 +0100615/* This function performs the TCP request analysis on the current request. It
616 * returns 1 if the processing can continue on next analysers, or zero if it
617 * needs more data, encounters an error, or wants to immediately abort the
618 * request. It relies on buffers flags, and updates s->req->analysers. Its
619 * behaviour is rather simple:
Willy Tarreau86ef7dc2009-03-15 22:55:47 +0100620 * - the analyser should check for errors and timeouts, and react as expected.
621 * It does not have to close anything upon error, the caller will. Note that
622 * the caller also knows how to report errors and timeouts.
623 * - if the analyser does not have enough data, it must return 0 without calling
Willy Tarreauedcf6682008-11-30 23:15:34 +0100624 * other ones. It should also probably do a buffer_write_dis() to ensure
625 * that unprocessed data will not be forwarded. But that probably depends on
626 * the protocol.
627 * - if an analyser has enough data, it just has to pass on to the next
628 * analyser without using buffer_write_dis() (enabled by default).
629 * - if an analyser thinks it has no added value anymore staying here, it must
630 * reset its bit from the analysers flags in order not to be called anymore.
631 *
632 * In the future, analysers should be able to indicate that they want to be
633 * called after XXX bytes have been received (or transfered), and the min of
634 * all's wishes will be used to ring back (unless a special condition occurs).
635 */
Willy Tarreau3a816292009-07-07 10:55:49 +0200636int tcp_inspect_request(struct session *s, struct buffer *req, int an_bit)
Willy Tarreauedcf6682008-11-30 23:15:34 +0100637{
638 struct tcp_rule *rule;
639 int partial;
640
641 DPRINTF(stderr,"[%u] %s: session=%p b=%p, exp(r,w)=%u,%u bf=%08x bl=%d analysers=%02x\n",
642 now_ms, __FUNCTION__,
643 s,
644 req,
645 req->rex, req->wex,
646 req->flags,
647 req->l,
648 req->analysers);
649
Willy Tarreauedcf6682008-11-30 23:15:34 +0100650 /* We don't know whether we have enough data, so must proceed
651 * this way :
652 * - iterate through all rules in their declaration order
653 * - if one rule returns MISS, it means the inspect delay is
654 * not over yet, then return immediately, otherwise consider
655 * it as a non-match.
656 * - if one rule returns OK, then return OK
657 * - if one rule returns KO, then return KO
658 */
659
Willy Tarreaud869b242009-03-15 14:43:58 +0100660 if (req->flags & BF_SHUTR || !s->fe->tcp_req.inspect_delay || tick_is_expired(req->analyse_exp, now_ms))
Willy Tarreauedcf6682008-11-30 23:15:34 +0100661 partial = 0;
662 else
663 partial = ACL_PARTIAL;
664
665 list_for_each_entry(rule, &s->fe->tcp_req.inspect_rules, list) {
666 int ret = ACL_PAT_PASS;
667
668 if (rule->cond) {
Willy Tarreau51d5dad2009-07-12 10:10:05 +0200669 ret = acl_exec_cond(rule->cond, s->fe, s, &s->txn, ACL_DIR_REQ | partial);
Willy Tarreauedcf6682008-11-30 23:15:34 +0100670 if (ret == ACL_PAT_MISS) {
Willy Tarreau520d95e2009-09-19 21:04:57 +0200671 buffer_dont_connect(req);
Willy Tarreauedcf6682008-11-30 23:15:34 +0100672 /* just set the request timeout once at the beginning of the request */
Willy Tarreaud869b242009-03-15 14:43:58 +0100673 if (!tick_isset(req->analyse_exp) && s->fe->tcp_req.inspect_delay)
Willy Tarreauedcf6682008-11-30 23:15:34 +0100674 req->analyse_exp = tick_add_ifset(now_ms, s->fe->tcp_req.inspect_delay);
675 return 0;
676 }
677
678 ret = acl_pass(ret);
679 if (rule->cond->pol == ACL_COND_UNLESS)
680 ret = !ret;
681 }
682
683 if (ret) {
684 /* we have a matching rule. */
685 if (rule->action == TCP_ACT_REJECT) {
686 buffer_abort(req);
687 buffer_abort(s->rep);
688 req->analysers = 0;
Krzysztof Piotr Oledzkiaeebf9b2009-10-04 15:43:17 +0200689
Willy Tarreau23968d82010-05-23 23:50:44 +0200690 s->fe->counters.denied_req++;
Krzysztof Piotr Oledzkiaeebf9b2009-10-04 15:43:17 +0200691 if (s->listener->counters)
Willy Tarreau23968d82010-05-23 23:50:44 +0200692 s->listener->counters->denied_req++;
Krzysztof Piotr Oledzkiaeebf9b2009-10-04 15:43:17 +0200693
Willy Tarreauedcf6682008-11-30 23:15:34 +0100694 if (!(s->flags & SN_ERR_MASK))
695 s->flags |= SN_ERR_PRXCOND;
696 if (!(s->flags & SN_FINST_MASK))
697 s->flags |= SN_FINST_R;
698 return 0;
699 }
700 /* otherwise accept */
701 break;
702 }
703 }
704
705 /* if we get there, it means we have no rule which matches, or
706 * we have an explicit accept, so we apply the default accept.
707 */
Willy Tarreau3a816292009-07-07 10:55:49 +0200708 req->analysers &= ~an_bit;
Willy Tarreauedcf6682008-11-30 23:15:34 +0100709 req->analyse_exp = TICK_ETERNITY;
710 return 1;
711}
712
Willy Tarreaua5c0ab22010-05-31 10:30:33 +0200713/* This function performs the TCP layer4 analysis on the current request. It
714 * returns 0 if a reject rule matches, otherwise 1 if either an accept rule
715 * matches or if no more rule matches. It can only use rules which don't need
716 * any data.
717 */
718int tcp_exec_req_rules(struct session *s)
719{
720 struct tcp_rule *rule;
721 int ret;
722
723 list_for_each_entry(rule, &s->fe->tcp_req.l4_rules, list) {
724 ret = ACL_PAT_PASS;
725
726 if (rule->cond) {
727 ret = acl_exec_cond(rule->cond, s->fe, s, NULL, ACL_DIR_REQ);
728 ret = acl_pass(ret);
729 if (rule->cond->pol == ACL_COND_UNLESS)
730 ret = !ret;
731 }
732
733 if (ret) {
734 /* we have a matching rule. */
735 if (rule->action == TCP_ACT_REJECT) {
Willy Tarreau2799e982010-06-05 15:43:21 +0200736 s->fe->counters.denied_conn++;
Willy Tarreaua5c0ab22010-05-31 10:30:33 +0200737 if (s->listener->counters)
Willy Tarreau2799e982010-06-05 15:43:21 +0200738 s->listener->counters->denied_conn++;
Willy Tarreaua5c0ab22010-05-31 10:30:33 +0200739
740 if (!(s->flags & SN_ERR_MASK))
741 s->flags |= SN_ERR_PRXCOND;
742 if (!(s->flags & SN_FINST_MASK))
743 s->flags |= SN_FINST_R;
744 return 0;
745 }
746 /* otherwise it's an accept */
747 break;
748 }
749 }
750 return 1;
751}
752
Willy Tarreaub6866442008-07-14 23:54:42 +0200753/* This function should be called to parse a line starting with the "tcp-request"
754 * keyword.
755 */
756static int tcp_parse_tcp_req(char **args, int section_type, struct proxy *curpx,
757 struct proxy *defpx, char *err, int errlen)
758{
759 const char *ptr = NULL;
Willy Tarreauc7e961e2008-08-17 17:13:47 +0200760 unsigned int val;
Willy Tarreaub6866442008-07-14 23:54:42 +0200761 int retlen;
Willy Tarreau1a687942010-05-23 22:40:30 +0200762 int action;
763 int warn = 0;
764 int pol = ACL_COND_NONE;
765 struct acl_cond *cond;
766 struct tcp_rule *rule;
Willy Tarreaub6866442008-07-14 23:54:42 +0200767
768 if (!*args[1]) {
769 snprintf(err, errlen, "missing argument for '%s' in %s '%s'",
770 args[0], proxy_type_str(proxy), curpx->id);
771 return -1;
772 }
773
774 if (!strcmp(args[1], "inspect-delay")) {
775 if (curpx == defpx) {
776 snprintf(err, errlen, "%s %s is not allowed in 'defaults' sections",
777 args[0], args[1]);
778 return -1;
779 }
780
781 if (!(curpx->cap & PR_CAP_FE)) {
782 snprintf(err, errlen, "%s %s will be ignored because %s '%s' has no %s capability",
783 args[0], args[1], proxy_type_str(proxy), curpx->id,
784 "frontend");
785 return 1;
786 }
787
788 if (!*args[2] || (ptr = parse_time_err(args[2], &val, TIME_UNIT_MS))) {
789 retlen = snprintf(err, errlen,
790 "'%s %s' expects a positive delay in milliseconds, in %s '%s'",
791 args[0], args[1], proxy_type_str(proxy), curpx->id);
792 if (ptr && retlen < errlen)
793 retlen += snprintf(err+retlen, errlen - retlen,
794 " (unexpected character '%c')", *ptr);
795 return -1;
796 }
797
798 if (curpx->tcp_req.inspect_delay) {
799 snprintf(err, errlen, "ignoring %s %s (was already defined) in %s '%s'",
800 args[0], args[1], proxy_type_str(proxy), curpx->id);
801 return 1;
802 }
803 curpx->tcp_req.inspect_delay = val;
804 return 0;
805 }
806
807 if (!strcmp(args[1], "content")) {
Willy Tarreaub6866442008-07-14 23:54:42 +0200808 if (curpx == defpx) {
809 snprintf(err, errlen, "%s %s is not allowed in 'defaults' sections",
810 args[0], args[1]);
811 return -1;
812 }
813
814 if (!strcmp(args[2], "accept"))
815 action = TCP_ACT_ACCEPT;
816 else if (!strcmp(args[2], "reject"))
817 action = TCP_ACT_REJECT;
818 else {
819 retlen = snprintf(err, errlen,
820 "'%s %s' expects 'accept' or 'reject', in %s '%s' (was '%s')",
821 args[0], args[1], proxy_type_str(curpx), curpx->id, args[2]);
822 return -1;
823 }
824
825 pol = ACL_COND_NONE;
826 cond = NULL;
827
Willy Tarreauef6494c2010-01-28 17:12:36 +0100828 if (strcmp(args[3], "if") == 0 || strcmp(args[3], "unless") == 0) {
829 if ((cond = build_acl_cond(NULL, 0, curpx, (const char **)args+3)) == NULL) {
830 retlen = snprintf(err, errlen,
831 "error detected in %s '%s' while parsing '%s' condition",
832 proxy_type_str(curpx), curpx->id, args[3]);
833 return -1;
834 }
835 }
836 else if (*args[3]) {
Willy Tarreau606ad732009-07-14 21:17:05 +0200837 retlen = snprintf(err, errlen,
838 "'%s %s %s' only accepts 'if' or 'unless', in %s '%s' (was '%s')",
839 args[0], args[1], args[2], proxy_type_str(curpx), curpx->id, args[3]);
840 return -1;
841 }
Willy Tarreaub6866442008-07-14 23:54:42 +0200842
Willy Tarreau1a211942009-07-14 13:53:17 +0200843 if (cond && (cond->requires & ACL_USE_RTR_ANY)) {
Willy Tarreaudd64f8d2008-07-27 22:02:32 +0200844 struct acl *acl;
845 const char *name;
846
Willy Tarreau1a211942009-07-14 13:53:17 +0200847 acl = cond_find_require(cond, ACL_USE_RTR_ANY);
Willy Tarreaudd64f8d2008-07-27 22:02:32 +0200848 name = acl ? acl->name : "(unknown)";
849
850 retlen = snprintf(err, errlen,
Willy Tarreau1a211942009-07-14 13:53:17 +0200851 "acl '%s' involves some response-only criteria which will be ignored.",
852 name);
Willy Tarreaudd64f8d2008-07-27 22:02:32 +0200853 warn++;
854 }
Willy Tarreaub6866442008-07-14 23:54:42 +0200855 rule = (struct tcp_rule *)calloc(1, sizeof(*rule));
856 rule->cond = cond;
857 rule->action = action;
858 LIST_INIT(&rule->list);
859 LIST_ADDQ(&curpx->tcp_req.inspect_rules, &rule->list);
Willy Tarreaudd64f8d2008-07-27 22:02:32 +0200860 return warn;
Willy Tarreaub6866442008-07-14 23:54:42 +0200861 }
862
Willy Tarreau1a687942010-05-23 22:40:30 +0200863 /* OK so we're in front of plain L4 rules */
864 if (!strcmp(args[1], "accept"))
865 action = TCP_ACT_ACCEPT;
866 else if (!strcmp(args[1], "reject"))
867 action = TCP_ACT_REJECT;
868 else {
869 retlen = snprintf(err, errlen,
870 "'%s' expects 'inspect-delay', 'content', 'accept' or 'reject', in %s '%s' (was '%s')",
871 args[0], proxy_type_str(curpx), curpx->id, args[1]);
872 return -1;
873 }
874
875 if (curpx == defpx) {
876 snprintf(err, errlen, "%s %s is not allowed in 'defaults' sections",
877 args[0], args[1]);
878 return -1;
879 }
880
881 pol = ACL_COND_NONE;
882 cond = NULL;
883
884 if (strcmp(args[2], "if") == 0 || strcmp(args[2], "unless") == 0) {
885 if ((cond = build_acl_cond(NULL, 0, curpx, (const char **)args+2)) == NULL) {
886 retlen = snprintf(err, errlen,
887 "error detected in %s '%s' while parsing '%s' condition",
888 proxy_type_str(curpx), curpx->id, args[2]);
889 return -1;
890 }
891 }
892 else if (*args[2]) {
893 retlen = snprintf(err, errlen,
894 "'%s %s' only accepts 'if' or 'unless', in %s '%s' (was '%s')",
895 args[0], args[1], proxy_type_str(curpx), curpx->id, args[2]);
896 return -1;
897 }
898
899 if (cond && (cond->requires & (ACL_USE_RTR_ANY|ACL_USE_L6_ANY|ACL_USE_L7_ANY))) {
900 struct acl *acl;
901 const char *name;
902
903 acl = cond_find_require(cond, ACL_USE_RTR_ANY|ACL_USE_L6_ANY|ACL_USE_L7_ANY);
904 name = acl ? acl->name : "(unknown)";
905
906 if (acl->requires & (ACL_USE_L6_ANY|ACL_USE_L7_ANY)) {
907 retlen = snprintf(err, errlen,
908 "'%s %s' may not reference acl '%s' which makes use of payload in %s '%s'. Please use '%s content' for this.",
909 args[0], args[1], name, proxy_type_str(curpx), curpx->id, args[0]);
910 return -1;
911 }
912 if (acl->requires & ACL_USE_RTR_ANY)
913 retlen = snprintf(err, errlen,
914 "acl '%s' involves some response-only criteria which will be ignored.",
915 name);
916
917 warn++;
918 }
919
920 rule = (struct tcp_rule *)calloc(1, sizeof(*rule));
921 rule->cond = cond;
922 rule->action = action;
923 LIST_INIT(&rule->list);
924 LIST_ADDQ(&curpx->tcp_req.l4_rules, &rule->list);
925 return warn;
Willy Tarreaub6866442008-07-14 23:54:42 +0200926}
927
Willy Tarreau645513a2010-05-24 20:55:15 +0200928
929/************************************************************************/
930/* All supported ACL keywords must be declared here. */
931/************************************************************************/
932
933/* set test->ptr to point to the source IPv4/IPv6 address and test->i to the family */
934static int
935acl_fetch_src(struct proxy *px, struct session *l4, void *l7, int dir,
936 struct acl_expr *expr, struct acl_test *test)
937{
938 test->i = l4->cli_addr.ss_family;
939 if (test->i == AF_INET)
940 test->ptr = (void *)&((struct sockaddr_in *)&l4->cli_addr)->sin_addr;
941 else
942 test->ptr = (void *)&((struct sockaddr_in6 *)(&l4->cli_addr))->sin6_addr;
943 test->flags = ACL_TEST_F_READ_ONLY;
944 return 1;
945}
946
947/* extract the connection's source address */
948static int
949pattern_fetch_src(struct proxy *px, struct session *l4, void *l7, int dir,
950 const char *arg, int arg_len, union pattern_data *data)
951{
952 data->ip.s_addr = ((struct sockaddr_in *)&l4->cli_addr)->sin_addr.s_addr;
953 return 1;
954}
955
956
957/* set test->i to the connection's source port */
958static int
959acl_fetch_sport(struct proxy *px, struct session *l4, void *l7, int dir,
960 struct acl_expr *expr, struct acl_test *test)
961{
962 if (l4->cli_addr.ss_family == AF_INET)
963 test->i = ntohs(((struct sockaddr_in *)&l4->cli_addr)->sin_port);
964 else
965 test->i = ntohs(((struct sockaddr_in6 *)(&l4->cli_addr))->sin6_port);
966 test->flags = 0;
967 return 1;
968}
969
970
971/* set test->ptr to point to the frontend's IPv4/IPv6 address and test->i to the family */
972static int
973acl_fetch_dst(struct proxy *px, struct session *l4, void *l7, int dir,
974 struct acl_expr *expr, struct acl_test *test)
975{
976 if (!(l4->flags & SN_FRT_ADDR_SET))
977 get_frt_addr(l4);
978
979 test->i = l4->frt_addr.ss_family;
980 if (test->i == AF_INET)
981 test->ptr = (void *)&((struct sockaddr_in *)&l4->frt_addr)->sin_addr;
982 else
983 test->ptr = (void *)&((struct sockaddr_in6 *)(&l4->frt_addr))->sin6_addr;
984 test->flags = ACL_TEST_F_READ_ONLY;
985 return 1;
986}
987
988
989/* extract the connection's destination address */
990static int
991pattern_fetch_dst(struct proxy *px, struct session *l4, void *l7, int dir,
992 const char *arg, int arg_len, union pattern_data *data)
993{
994 data->ip.s_addr = ((struct sockaddr_in *)&l4->frt_addr)->sin_addr.s_addr;
995 return 1;
996}
997
998/* set test->i to the frontend connexion's destination port */
999static int
1000acl_fetch_dport(struct proxy *px, struct session *l4, void *l7, int dir,
1001 struct acl_expr *expr, struct acl_test *test)
1002{
1003 if (!(l4->flags & SN_FRT_ADDR_SET))
1004 get_frt_addr(l4);
1005
1006 if (l4->frt_addr.ss_family == AF_INET)
1007 test->i = ntohs(((struct sockaddr_in *)&l4->frt_addr)->sin_port);
1008 else
1009 test->i = ntohs(((struct sockaddr_in6 *)(&l4->frt_addr))->sin6_port);
1010 test->flags = 0;
1011 return 1;
1012}
1013
1014static int
1015pattern_fetch_dport(struct proxy *px, struct session *l4, void *l7, int dir,
1016 const char *arg, int arg_len, union pattern_data *data)
1017
1018{
1019 data->integer = ntohs(((struct sockaddr_in *)&l4->frt_addr)->sin_port);
1020 return 1;
1021}
1022
Willy Tarreaua975b8f2010-06-05 19:13:27 +02001023/* set test->i to the number of connections from the session's source address
1024 * in the table pointed to by expr.
1025 */
1026static int
1027acl_fetch_src_count(struct proxy *px, struct session *l4, void *l7, int dir,
1028 struct acl_expr *expr, struct acl_test *test)
1029{
1030 struct stksess *ts;
1031
1032 /* right now we only support IPv4 */
1033 if (l4->cli_addr.ss_family != AF_INET)
1034 return 0;
1035
1036 if (expr->arg_len) {
1037 /* another table was designated, we must look for it */
1038 for (px = proxy; px; px = px->next)
1039 if (strcmp(px->id, expr->arg.str) == 0)
1040 break;
1041 }
1042 if (!px)
1043 return 0; /* table not found */
1044
1045 static_table_key.key = (void *)&((struct sockaddr_in *)&l4->frt_addr)->sin_addr;
1046 test->flags = ACL_TEST_F_VOL_TEST;
1047 test->i = 0;
1048 if ((ts = stktable_lookup_key(&px->table, &static_table_key)) != NULL) {
1049 void *ptr = stktable_data_ptr(&px->table, ts, STKTABLE_DT_CONN_CUM);
1050 if (!ptr)
1051 return 0; /* parameter not stored */
1052 test->i = stktable_data_cast(ptr, conn_cum);
1053 }
1054
1055 return 1;
1056}
1057
1058/* set test->i to the number of connections from the session's source address
1059 * in the table pointed to by expr, after updating it.
1060 */
1061static int
1062acl_fetch_src_update_count(struct proxy *px, struct session *l4, void *l7, int dir,
1063 struct acl_expr *expr, struct acl_test *test)
1064{
1065 struct stksess *ts;
1066 void *ptr;
1067
1068 /* right now we only support IPv4 */
1069 if (l4->cli_addr.ss_family != AF_INET)
1070 return 0;
1071
1072 if (expr->arg_len) {
1073 /* another table was designated, we must look for it */
1074 for (px = proxy; px; px = px->next)
1075 if (strcmp(px->id, expr->arg.str) == 0)
1076 break;
1077 }
1078 if (!px)
1079 return 0;
1080
1081 static_table_key.key = (void *)&((struct sockaddr_in *)&l4->frt_addr)->sin_addr;
1082 if ((ts = stktable_lookup_key(&px->table, &static_table_key)) == NULL) {
1083 /* entry does not exist, initialize a new one */
1084 ts = stksess_new(&px->table, &static_table_key);
1085 if (!ts)
1086 return 0;
1087 stktable_store(&px->table, ts);
1088 }
1089 else if (px->table.expire) {
1090 /* if entries can expire, let's update the entry and the table */
1091 ts->expire = tick_add(now_ms, MS_TO_TICKS(px->table.expire));
1092 px->table.exp_task->expire = px->table.exp_next = tick_first(ts->expire, px->table.exp_next);
1093 task_queue(px->table.exp_task);
1094 }
1095
1096 ptr = stktable_data_ptr(&px->table, ts, STKTABLE_DT_CONN_CUM);
1097 if (!ptr)
1098 return 0; /* parameter not stored in this table */
1099
1100 test->i = ++stktable_data_cast(ptr, conn_cum);
1101 test->flags = ACL_TEST_F_VOL_TEST;
1102 return 1;
1103}
Willy Tarreau645513a2010-05-24 20:55:15 +02001104
Willy Tarreaub6866442008-07-14 23:54:42 +02001105static struct cfg_kw_list cfg_kws = {{ },{
1106 { CFG_LISTEN, "tcp-request", tcp_parse_tcp_req },
1107 { 0, NULL, NULL },
1108}};
1109
Willy Tarreau645513a2010-05-24 20:55:15 +02001110/* Note: must not be declared <const> as its list will be overwritten */
Willy Tarreaub6866442008-07-14 23:54:42 +02001111static struct acl_kw_list acl_kws = {{ },{
Willy Tarreau645513a2010-05-24 20:55:15 +02001112 { "src_port", acl_parse_int, acl_fetch_sport, acl_match_int, ACL_USE_TCP_PERMANENT },
1113 { "src", acl_parse_ip, acl_fetch_src, acl_match_ip, ACL_USE_TCP4_PERMANENT|ACL_MAY_LOOKUP },
1114 { "dst", acl_parse_ip, acl_fetch_dst, acl_match_ip, ACL_USE_TCP4_PERMANENT|ACL_MAY_LOOKUP },
1115 { "dst_port", acl_parse_int, acl_fetch_dport, acl_match_int, ACL_USE_TCP_PERMANENT },
Willy Tarreaua975b8f2010-06-05 19:13:27 +02001116 { "src_count", acl_parse_int, acl_fetch_src_count,acl_match_int, ACL_USE_TCP4_PERMANENT },
1117 { "src_update_count", acl_parse_int, acl_fetch_src_update_count, acl_match_int, ACL_USE_TCP4_PERMANENT },
Willy Tarreaub6866442008-07-14 23:54:42 +02001118 { NULL, NULL, NULL, NULL },
1119}};
1120
Willy Tarreau645513a2010-05-24 20:55:15 +02001121/* Note: must not be declared <const> as its list will be overwritten */
1122static struct pattern_fetch_kw_list pattern_fetch_keywords = {{ },{
1123 { "src", pattern_fetch_src, PATTERN_TYPE_IP, PATTERN_FETCH_REQ },
1124 { "dst", pattern_fetch_dst, PATTERN_TYPE_IP, PATTERN_FETCH_REQ },
1125 { "dst_port", pattern_fetch_dport, PATTERN_TYPE_INTEGER, PATTERN_FETCH_REQ },
1126 { NULL, NULL, 0, 0 },
1127}};
1128
Willy Tarreaue6b98942007-10-29 01:09:36 +01001129__attribute__((constructor))
1130static void __tcp_protocol_init(void)
1131{
1132 protocol_register(&proto_tcpv4);
1133 protocol_register(&proto_tcpv6);
Willy Tarreau645513a2010-05-24 20:55:15 +02001134 pattern_register_fetches(&pattern_fetch_keywords);
Willy Tarreaub6866442008-07-14 23:54:42 +02001135 cfg_register_keywords(&cfg_kws);
1136 acl_register_keywords(&acl_kws);
Willy Tarreaue6b98942007-10-29 01:09:36 +01001137}
1138
1139
1140/*
1141 * Local variables:
1142 * c-indent-level: 8
1143 * c-basic-offset: 8
1144 * End:
1145 */