blob: 3d93a34b108afe6f116e6e201efca576ad0632e5 [file] [log] [blame]
Willy Tarreaue6b98942007-10-29 01:09:36 +01001/*
2 * AF_INET/AF_INET6 SOCK_STREAM protocol layer (tcp)
3 *
Willy Tarreaue8c66af2008-01-13 18:40:14 +01004 * Copyright 2000-2008 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
Willy Tarreaub6866442008-07-14 23:54:42 +020027#include <common/cfgparse.h>
Willy Tarreaue6b98942007-10-29 01:09:36 +010028#include <common/compat.h>
29#include <common/config.h>
30#include <common/debug.h>
31#include <common/errors.h>
32#include <common/memory.h>
33#include <common/mini-clist.h>
34#include <common/standard.h>
35#include <common/time.h>
36#include <common/version.h>
37
Willy Tarreaue6b98942007-10-29 01:09:36 +010038#include <types/global.h>
Willy Tarreaue6b98942007-10-29 01:09:36 +010039
40#include <proto/acl.h>
41#include <proto/backend.h>
42#include <proto/buffers.h>
43#include <proto/fd.h>
44#include <proto/protocols.h>
45#include <proto/proto_tcp.h>
Willy Tarreaub6866442008-07-14 23:54:42 +020046#include <proto/proxy.h>
Willy Tarreaue6b98942007-10-29 01:09:36 +010047#include <proto/queue.h>
48#include <proto/senddata.h>
49#include <proto/session.h>
50#include <proto/stream_sock.h>
51#include <proto/task.h>
52
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,
68 .read = &stream_sock_read,
69 .write = &stream_sock_write,
70 .bind_all = tcp_bind_listeners,
71 .unbind_all = unbind_all_listeners,
72 .enable_all = enable_all_listeners,
73 .listeners = LIST_HEAD_INIT(proto_tcpv4.listeners),
74 .nb_listeners = 0,
75};
76
77/* Note: must not be declared <const> as its list will be overwritten */
78static struct protocol proto_tcpv6 = {
79 .name = "tcpv6",
80 .sock_domain = AF_INET6,
81 .sock_type = SOCK_STREAM,
82 .sock_prot = IPPROTO_TCP,
83 .sock_family = AF_INET6,
84 .sock_addrlen = sizeof(struct sockaddr_in6),
85 .l3_addrlen = 128/8,
86 .read = &stream_sock_read,
87 .write = &stream_sock_write,
88 .bind_all = tcp_bind_listeners,
89 .unbind_all = unbind_all_listeners,
90 .enable_all = enable_all_listeners,
91 .listeners = LIST_HEAD_INIT(proto_tcpv6.listeners),
92 .nb_listeners = 0,
93};
94
Willy Tarreaue8c66af2008-01-13 18:40:14 +010095
96/* Binds ipv4 address <local> to socket <fd>, unless <flags> is set, in which
97 * case we try to bind <remote>. <flags> is a 2-bit field consisting of :
98 * - 0 : ignore remote address (may even be a NULL pointer)
99 * - 1 : use provided address
100 * - 2 : use provided port
101 * - 3 : use both
102 *
103 * The function supports multiple foreign binding methods :
104 * - linux_tproxy: we directly bind to the foreign address
105 * - cttproxy: we bind to a local address then nat.
106 * The second one can be used as a fallback for the first one.
107 * This function returns 0 when everything's OK, 1 if it could not bind, to the
108 * local address, 2 if it could not bind to the foreign address.
109 */
110int tcpv4_bind_socket(int fd, int flags, struct sockaddr_in *local, struct sockaddr_in *remote)
111{
112 struct sockaddr_in bind_addr;
113 int foreign_ok = 0;
114 int ret;
115
116#ifdef CONFIG_HAP_LINUX_TPROXY
117 static int ip_transp_working = 1;
118 if (flags && ip_transp_working) {
119 if (setsockopt(fd, SOL_IP, IP_TRANSPARENT, (char *) &one, sizeof(one)) == 0
120 || setsockopt(fd, SOL_IP, IP_FREEBIND, (char *) &one, sizeof(one)) == 0)
121 foreign_ok = 1;
122 else
123 ip_transp_working = 0;
124 }
125#endif
126 if (flags) {
127 memset(&bind_addr, 0, sizeof(bind_addr));
128 if (flags & 1)
129 bind_addr.sin_addr = remote->sin_addr;
130 if (flags & 2)
131 bind_addr.sin_port = remote->sin_port;
132 }
133
134 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &one, sizeof(one));
135 if (foreign_ok) {
136 ret = bind(fd, (struct sockaddr *)&bind_addr, sizeof(bind_addr));
137 if (ret < 0)
138 return 2;
139 }
140 else {
141 ret = bind(fd, (struct sockaddr *)local, sizeof(*local));
142 if (ret < 0)
143 return 1;
144 }
145
146 if (!flags)
147 return 0;
148
149#ifdef CONFIG_HAP_CTTPROXY
150 if (!foreign_ok) {
151 struct in_tproxy itp1, itp2;
152 memset(&itp1, 0, sizeof(itp1));
153
154 itp1.op = TPROXY_ASSIGN;
155 itp1.v.addr.faddr = bind_addr.sin_addr;
156 itp1.v.addr.fport = bind_addr.sin_port;
157
158 /* set connect flag on socket */
159 itp2.op = TPROXY_FLAGS;
160 itp2.v.flags = ITP_CONNECT | ITP_ONCE;
161
162 if (setsockopt(fd, SOL_IP, IP_TPROXY, &itp1, sizeof(itp1)) != -1 &&
163 setsockopt(fd, SOL_IP, IP_TPROXY, &itp2, sizeof(itp2)) != -1) {
164 foreign_ok = 1;
165 }
166 }
167#endif
168 if (!foreign_ok)
169 /* we could not bind to a foreign address */
170 return 2;
171
172 return 0;
173}
Willy Tarreaue6b98942007-10-29 01:09:36 +0100174
175/* This function tries to bind a TCPv4/v6 listener. It may return a warning or
176 * an error message in <err> if the message is at most <errlen> bytes long
177 * (including '\0'). The return value is composed from ERR_ABORT, ERR_WARN,
178 * ERR_ALERT, ERR_RETRYABLE and ERR_FATAL. ERR_NONE indicates that everything
179 * was alright and that no message was returned. ERR_RETRYABLE means that an
180 * error occurred but that it may vanish after a retry (eg: port in use), and
181 * ERR_FATAL indicates a non-fixable error.ERR_WARN and ERR_ALERT do not alter
182 * the meaning of the error, but just indicate that a message is present which
183 * should be displayed with the respective level. Last, ERR_ABORT indicates
184 * that it's pointless to try to start other listeners. No error message is
185 * returned if errlen is NULL.
186 */
187int tcp_bind_listener(struct listener *listener, char *errmsg, int errlen)
188{
189 __label__ tcp_return, tcp_close_return;
190 int fd, err;
191 const char *msg = NULL;
192
193 /* ensure we never return garbage */
194 if (errmsg && errlen)
195 *errmsg = 0;
196
197 if (listener->state != LI_ASSIGNED)
198 return ERR_NONE; /* already bound */
199
200 err = ERR_NONE;
201
202 if ((fd = socket(listener->addr.ss_family, SOCK_STREAM, IPPROTO_TCP)) == -1) {
203 err |= ERR_RETRYABLE | ERR_ALERT;
204 msg = "cannot create listening socket";
205 goto tcp_return;
206 }
207
208 if (fd >= global.maxsock) {
209 err |= ERR_FATAL | ERR_ABORT | ERR_ALERT;
210 msg = "not enough free sockets (raise '-n' parameter)";
211 goto tcp_close_return;
212 }
213
214 if ((fcntl(fd, F_SETFL, O_NONBLOCK) == -1) ||
215 (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY,
216 (char *) &one, sizeof(one)) == -1)) {
217 err |= ERR_FATAL | ERR_ALERT;
218 msg = "cannot make socket non-blocking";
219 goto tcp_close_return;
220 }
221
222 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &one, sizeof(one)) == -1) {
223 /* not fatal but should be reported */
224 msg = "cannot do so_reuseaddr";
225 err |= ERR_ALERT;
226 }
227
228 if (listener->options & LI_O_NOLINGER)
229 setsockopt(fd, SOL_SOCKET, SO_LINGER, (struct linger *) &nolinger, sizeof(struct linger));
230
231#ifdef SO_REUSEPORT
232 /* OpenBSD supports this. As it's present in old libc versions of Linux,
233 * it might return an error that we will silently ignore.
234 */
235 setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, (char *) &one, sizeof(one));
236#endif
Willy Tarreaub1e52e82008-01-13 14:49:51 +0100237#ifdef CONFIG_HAP_LINUX_TPROXY
238 if ((listener->options & LI_O_FOREIGN)
Willy Tarreau0a459892008-01-13 17:37:16 +0100239 && (setsockopt(fd, SOL_IP, IP_TRANSPARENT, (char *) &one, sizeof(one)) == -1)
240 && (setsockopt(fd, SOL_IP, IP_FREEBIND, (char *) &one, sizeof(one)) == -1)) {
Willy Tarreaub1e52e82008-01-13 14:49:51 +0100241 msg = "cannot make listening socket transparent";
242 err |= ERR_ALERT;
243 }
244#endif
Willy Tarreaue6b98942007-10-29 01:09:36 +0100245 if (bind(fd, (struct sockaddr *)&listener->addr, listener->proto->sock_addrlen) == -1) {
246 err |= ERR_RETRYABLE | ERR_ALERT;
247 msg = "cannot bind socket";
248 goto tcp_close_return;
249 }
250
Willy Tarreauc73ce2b2008-01-06 10:55:10 +0100251 if (listen(fd, listener->backlog ? listener->backlog : listener->maxconn) == -1) {
Willy Tarreaue6b98942007-10-29 01:09:36 +0100252 err |= ERR_RETRYABLE | ERR_ALERT;
253 msg = "cannot listen to socket";
254 goto tcp_close_return;
255 }
256
257 /* the socket is ready */
258 listener->fd = fd;
259 listener->state = LI_LISTEN;
260
261 /* the function for the accept() event */
262 fd_insert(fd);
263 fdtab[fd].cb[DIR_RD].f = listener->accept;
264 fdtab[fd].cb[DIR_WR].f = NULL; /* never called */
265 fdtab[fd].cb[DIR_RD].b = fdtab[fd].cb[DIR_WR].b = NULL;
266 fdtab[fd].owner = (struct task *)listener; /* reference the listener instead of a task */
267 fdtab[fd].state = FD_STLISTEN;
268 fdtab[fd].peeraddr = NULL;
269 fdtab[fd].peerlen = 0;
270 fdtab[fd].listener = NULL;
Willy Tarreaue6b98942007-10-29 01:09:36 +0100271 tcp_return:
272 if (msg && errlen)
273 strlcpy2(errmsg, msg, errlen);
274 return err;
275
276 tcp_close_return:
277 close(fd);
278 goto tcp_return;
279}
280
281/* This function creates all TCP sockets bound to the protocol entry <proto>.
282 * It is intended to be used as the protocol's bind_all() function.
283 * The sockets will be registered but not added to any fd_set, in order not to
284 * loose them across the fork(). A call to enable_all_listeners() is needed
285 * to complete initialization. The return value is composed from ERR_*.
286 */
287static int tcp_bind_listeners(struct protocol *proto)
288{
289 struct listener *listener;
290 int err = ERR_NONE;
291
292 list_for_each_entry(listener, &proto->listeners, proto_list) {
293 err |= tcp_bind_listener(listener, NULL, 0);
294 if ((err & ERR_CODE) == ERR_ABORT)
295 break;
296 }
297
298 return err;
299}
300
301/* Add listener to the list of tcpv4 listeners. The listener's state
302 * is automatically updated from LI_INIT to LI_ASSIGNED. The number of
303 * listeners is updated. This is the function to use to add a new listener.
304 */
305void tcpv4_add_listener(struct listener *listener)
306{
307 if (listener->state != LI_INIT)
308 return;
309 listener->state = LI_ASSIGNED;
310 listener->proto = &proto_tcpv4;
311 LIST_ADDQ(&proto_tcpv4.listeners, &listener->proto_list);
312 proto_tcpv4.nb_listeners++;
313}
314
315/* Add listener to the list of tcpv4 listeners. The listener's state
316 * is automatically updated from LI_INIT to LI_ASSIGNED. The number of
317 * listeners is updated. This is the function to use to add a new listener.
318 */
319void tcpv6_add_listener(struct listener *listener)
320{
321 if (listener->state != LI_INIT)
322 return;
323 listener->state = LI_ASSIGNED;
324 listener->proto = &proto_tcpv6;
325 LIST_ADDQ(&proto_tcpv6.listeners, &listener->proto_list);
326 proto_tcpv6.nb_listeners++;
327}
328
Willy Tarreaub6866442008-07-14 23:54:42 +0200329/* This function should be called to parse a line starting with the "tcp-request"
330 * keyword.
331 */
332static int tcp_parse_tcp_req(char **args, int section_type, struct proxy *curpx,
333 struct proxy *defpx, char *err, int errlen)
334{
335 const char *ptr = NULL;
336 int val;
337 int retlen;
338
339 if (!*args[1]) {
340 snprintf(err, errlen, "missing argument for '%s' in %s '%s'",
341 args[0], proxy_type_str(proxy), curpx->id);
342 return -1;
343 }
344
345 if (!strcmp(args[1], "inspect-delay")) {
346 if (curpx == defpx) {
347 snprintf(err, errlen, "%s %s is not allowed in 'defaults' sections",
348 args[0], args[1]);
349 return -1;
350 }
351
352 if (!(curpx->cap & PR_CAP_FE)) {
353 snprintf(err, errlen, "%s %s will be ignored because %s '%s' has no %s capability",
354 args[0], args[1], proxy_type_str(proxy), curpx->id,
355 "frontend");
356 return 1;
357 }
358
359 if (!*args[2] || (ptr = parse_time_err(args[2], &val, TIME_UNIT_MS))) {
360 retlen = snprintf(err, errlen,
361 "'%s %s' expects a positive delay in milliseconds, in %s '%s'",
362 args[0], args[1], proxy_type_str(proxy), curpx->id);
363 if (ptr && retlen < errlen)
364 retlen += snprintf(err+retlen, errlen - retlen,
365 " (unexpected character '%c')", *ptr);
366 return -1;
367 }
368
369 if (curpx->tcp_req.inspect_delay) {
370 snprintf(err, errlen, "ignoring %s %s (was already defined) in %s '%s'",
371 args[0], args[1], proxy_type_str(proxy), curpx->id);
372 return 1;
373 }
374 curpx->tcp_req.inspect_delay = val;
375 return 0;
376 }
377
378 if (!strcmp(args[1], "content")) {
379 int action;
380 int pol = ACL_COND_NONE;
381 struct acl_cond *cond;
382 struct tcp_rule *rule;
383
384 if (curpx == defpx) {
385 snprintf(err, errlen, "%s %s is not allowed in 'defaults' sections",
386 args[0], args[1]);
387 return -1;
388 }
389
390 if (!strcmp(args[2], "accept"))
391 action = TCP_ACT_ACCEPT;
392 else if (!strcmp(args[2], "reject"))
393 action = TCP_ACT_REJECT;
394 else {
395 retlen = snprintf(err, errlen,
396 "'%s %s' expects 'accept' or 'reject', in %s '%s' (was '%s')",
397 args[0], args[1], proxy_type_str(curpx), curpx->id, args[2]);
398 return -1;
399 }
400
401 pol = ACL_COND_NONE;
402 cond = NULL;
403
404 if (!strcmp(args[3], "if"))
405 pol = ACL_COND_IF;
406 else if (!strcmp(args[3], "unless"))
407 pol = ACL_COND_UNLESS;
408
409 /* Note: we consider "if TRUE" when there is no condition */
410 if (pol != ACL_COND_NONE &&
411 (cond = parse_acl_cond((const char **)args+4, &curpx->acl, pol)) == NULL) {
412 retlen = snprintf(err, errlen,
413 "Error detected in %s '%s' while parsing '%s' condition",
414 proxy_type_str(curpx), curpx->id, args[3]);
415 return -1;
416 }
417
418 rule = (struct tcp_rule *)calloc(1, sizeof(*rule));
419 rule->cond = cond;
420 rule->action = action;
421 LIST_INIT(&rule->list);
422 LIST_ADDQ(&curpx->tcp_req.inspect_rules, &rule->list);
423 return 0;
424 }
425
426 snprintf(err, errlen, "unknown argument '%s' after '%s' in %s '%s'",
427 args[1], args[0], proxy_type_str(proxy), curpx->id);
428 return -1;
429}
430
431/* return the number of bytes in the request buffer */
432static int
433acl_fetch_req_len(struct proxy *px, struct session *l4, void *l7, int dir,
434 struct acl_expr *expr, struct acl_test *test)
435{
436 if (!l4 || !l4->req)
437 return 0;
438
439 test->i = l4->req->l;
440 test->flags = ACL_TEST_F_VOLATILE | ACL_TEST_F_MAY_CHANGE;
441 return 1;
442}
443
Willy Tarreau655e26a2008-07-15 18:58:05 +0200444/* Return the version of the SSL protocol in the request. It supports both
445 * SSLv3 (TLSv1) header format for any message, and SSLv2 header format for
446 * the hello message. The SSLv3 format is described in RFC 2246 p49, and the
447 * SSLv2 format is described here, and completed p67 of RFC 2246 :
448 * http://wp.netscape.com/eng/security/SSL_2.html
449 *
450 * Note: this decoder only works with non-wrapping data.
451 */
452static int
453acl_fetch_req_ssl_ver(struct proxy *px, struct session *l4, void *l7, int dir,
454 struct acl_expr *expr, struct acl_test *test)
455{
456 int version, bleft, msg_len;
457 const unsigned char *data;
458
459 if (!l4 || !l4->req)
460 return 0;
461
462 msg_len = 0;
463 bleft = l4->req->l;
464 if (!bleft)
465 goto too_short;
466
467 data = l4->req->w;
468 if ((*data >= 0x14 && *data <= 0x17) || (*data == 0xFF)) {
469 /* SSLv3 header format */
470 if (bleft < 5)
471 goto too_short;
472
473 version = (data[1] << 16) + data[2]; /* version: major, minor */
474 msg_len = (data[3] << 8) + data[4]; /* record length */
475
476 /* format introduced with SSLv3 */
477 if (version < 0x00030000)
478 goto not_ssl;
479
480 /* message length between 1 and 2^14 + 2048 */
481 if (msg_len < 1 || msg_len > ((1<<14) + 2048))
482 goto not_ssl;
483
484 bleft -= 5; data += 5;
485 } else {
486 /* SSLv2 header format, only supported for hello (msg type 1) */
487 int rlen, plen, cilen, silen, chlen;
488
489 if (*data & 0x80) {
490 if (bleft < 3)
491 goto too_short;
492 /* short header format : 15 bits for length */
493 rlen = ((data[0] & 0x7F) << 8) | data[1];
494 plen = 0;
495 bleft -= 2; data += 2;
496 } else {
497 if (bleft < 4)
498 goto too_short;
499 /* long header format : 14 bits for length + pad length */
500 rlen = ((data[0] & 0x3F) << 8) | data[1];
501 plen = data[2];
502 bleft -= 3; data += 2;
503 }
504
505 if (*data != 0x01)
506 goto not_ssl;
507 bleft--; data++;
508
509 if (bleft < 8)
510 goto too_short;
511 version = (data[0] << 16) + data[1]; /* version: major, minor */
512 cilen = (data[2] << 8) + data[3]; /* cipher len, multiple of 3 */
513 silen = (data[4] << 8) + data[5]; /* session_id_len: 0 or 16 */
514 chlen = (data[6] << 8) + data[7]; /* 16<=challenge length<=32 */
515
516 bleft -= 8; data += 8;
517 if (cilen % 3 != 0)
518 goto not_ssl;
519 if (silen && silen != 16)
520 goto not_ssl;
521 if (chlen < 16 || chlen > 32)
522 goto not_ssl;
523 if (rlen != 9 + cilen + silen + chlen)
524 goto not_ssl;
525
526 /* focus on the remaining data length */
527 msg_len = cilen + silen + chlen + plen;
528 }
529 /* We could recursively check that the buffer ends exactly on an SSL
530 * fragment boundary and that a possible next segment is still SSL,
531 * but that's a bit pointless. However, we could still check that
532 * all the part of the request which fits in a buffer is already
533 * there.
534 */
535 if (msg_len > l4->req->rlim - l4->req->w)
536 msg_len = l4->req->rlim - l4->req->w;
537
538 if (bleft < msg_len)
539 goto too_short;
540
541 /* OK that's enough. We have at least the whole message, and we have
542 * the protocol version.
543 */
544 test->i = version;
545 test->flags = ACL_TEST_F_VOLATILE;
546 return 1;
547
548 too_short:
549 test->flags = ACL_TEST_F_MAY_CHANGE;
550 not_ssl:
551 return 0;
552}
553
Willy Tarreaub6866442008-07-14 23:54:42 +0200554
555static struct cfg_kw_list cfg_kws = {{ },{
556 { CFG_LISTEN, "tcp-request", tcp_parse_tcp_req },
557 { 0, NULL, NULL },
558}};
559
560static struct acl_kw_list acl_kws = {{ },{
Willy Tarreau0ceba5a2008-07-25 19:31:03 +0200561 { "req_len", acl_parse_int, acl_fetch_req_len, acl_match_int, ACL_USE_L4REQ_VOLATILE },
562 { "req_ssl_ver", acl_parse_dotted_ver, acl_fetch_req_ssl_ver, acl_match_int, ACL_USE_L4REQ_VOLATILE },
Willy Tarreaub6866442008-07-14 23:54:42 +0200563 { NULL, NULL, NULL, NULL },
564}};
565
Willy Tarreaue6b98942007-10-29 01:09:36 +0100566__attribute__((constructor))
567static void __tcp_protocol_init(void)
568{
569 protocol_register(&proto_tcpv4);
570 protocol_register(&proto_tcpv6);
Willy Tarreaub6866442008-07-14 23:54:42 +0200571 cfg_register_keywords(&cfg_kws);
572 acl_register_keywords(&acl_kws);
Willy Tarreaue6b98942007-10-29 01:09:36 +0100573}
574
575
576/*
577 * Local variables:
578 * c-indent-level: 8
579 * c-basic-offset: 8
580 * End:
581 */