blob: 35549ee806c49954b84be7403483bb03c5393b67 [file] [log] [blame]
Willy Tarreau59f98392012-07-06 14:13:49 +02001/*
2 * Connection management functions
3 *
4 * Copyright 2000-2012 Willy Tarreau <w@1wt.eu>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Willy Tarreaue1e4a612012-10-05 00:10:55 +020013#include <errno.h>
14
Willy Tarreau930428c2021-10-06 18:27:28 +020015#include <import/ebmbtree.h>
16
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020017#include <haproxy/api.h>
Willy Tarreau6be78492020-06-05 00:00:29 +020018#include <haproxy/cfgparse.h>
Willy Tarreau7ea393d2020-06-04 18:02:10 +020019#include <haproxy/connection.h>
Christopher Faulet1329f2a2021-12-16 17:32:56 +010020#include <haproxy/conn_stream.h>
Christopher Faulet8da67aa2022-03-29 17:53:09 +020021#include <haproxy/cs_utils.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020022#include <haproxy/fd.h>
Willy Tarreau762d7a52020-06-04 11:23:07 +020023#include <haproxy/frontend.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020024#include <haproxy/hash.h>
Willy Tarreauaac777f2021-10-06 18:48:28 +020025#include <haproxy/list.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020026#include <haproxy/log-t.h>
Willy Tarreau7a00efb2020-06-02 17:02:59 +020027#include <haproxy/namespace.h>
Willy Tarreau6131d6a2020-06-02 16:48:09 +020028#include <haproxy/net_helper.h>
Willy Tarreaufc774542020-06-04 17:31:04 +020029#include <haproxy/proto_tcp.h>
Willy Tarreaue6ce10b2020-06-04 15:33:47 +020030#include <haproxy/sample.h>
Christopher Faulet1329f2a2021-12-16 17:32:56 +010031#include <haproxy/session.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020032#include <haproxy/stream_interface.h>
Christopher Faulet1329f2a2021-12-16 17:32:56 +010033#include <haproxy/ssl_sock.h>
Willy Tarreau908908e2021-05-08 13:07:31 +020034#include <haproxy/tools.h>
Willy Tarreaue5983ff2021-10-06 17:14:49 +020035#include <haproxy/xxhash.h>
Emeric Brun46591952012-05-18 15:47:34 +020036
Alexander Liu2a54bb72019-05-22 19:44:48 +080037
Amaury Denoyelle8990b012021-02-19 15:29:16 +010038DECLARE_POOL(pool_head_connection, "connection", sizeof(struct connection));
Amaury Denoyelle8990b012021-02-19 15:29:16 +010039DECLARE_POOL(pool_head_conn_hash_node, "conn_hash_node", sizeof(struct conn_hash_node));
40DECLARE_POOL(pool_head_sockaddr, "sockaddr", sizeof(struct sockaddr_storage));
41DECLARE_POOL(pool_head_authority, "authority", PP2_AUTHORITY_MAX);
Willy Tarreau8ceae722018-11-26 11:58:30 +010042
Willy Tarreau4d82bf52020-06-28 00:19:17 +020043struct idle_conns idle_conns[MAX_THREADS] = { };
Willy Tarreau13e14102016-12-22 20:25:26 +010044struct xprt_ops *registered_xprt[XPRT_ENTRIES] = { NULL, };
Willy Tarreauf2943dc2012-10-26 20:10:28 +020045
Christopher Faulet32f61c02018-04-10 14:33:41 +020046/* List head of all known muxes for PROTO */
47struct mux_proto_list mux_proto_list = {
48 .list = LIST_HEAD_INIT(mux_proto_list.list)
Willy Tarreau2386be62017-09-21 19:40:52 +020049};
50
Amaury Denoyelled3a88c12021-05-03 10:47:51 +020051struct mux_stopping_data mux_stopping_data[MAX_THREADS];
52
Willy Tarreau119e50e2020-05-22 13:53:29 +020053/* disables sending of proxy-protocol-v2's LOCAL command */
54static int pp2_never_send_local;
55
Willy Tarreau930428c2021-10-06 18:27:28 +020056void conn_delete_from_tree(struct ebmb_node *node)
57{
58 ebmb_delete(node);
Willy Tarreau930428c2021-10-06 18:27:28 +020059}
60
Olivier Houchard477902b2020-01-22 18:08:48 +010061int conn_create_mux(struct connection *conn)
62{
Olivier Houchard477902b2020-01-22 18:08:48 +010063 if (conn_is_back(conn)) {
64 struct server *srv;
65 struct conn_stream *cs = conn->ctx;
Christopher Faulet14cd3162020-04-16 14:50:06 +020066 struct session *sess = conn->owner;
Olivier Houchard477902b2020-01-22 18:08:48 +010067
68 if (conn->flags & CO_FL_ERROR)
69 goto fail;
Olivier Houcharda8a415d2020-01-23 13:15:14 +010070
Christopher Faulet14cd3162020-04-16 14:50:06 +020071 if (sess && obj_type(sess->origin) == OBJ_TYPE_CHECK) {
Willy Tarreau38b4d2e2020-11-20 17:08:15 +010072 if (conn_install_mux_chk(conn, conn->ctx, sess) < 0)
Christopher Faulet14cd3162020-04-16 14:50:06 +020073 goto fail;
74 }
Amaury Denoyelleac03ef22021-10-28 16:36:11 +020075 else if (conn_install_mux_be(conn, conn->ctx, sess, NULL) < 0)
Olivier Houchard477902b2020-01-22 18:08:48 +010076 goto fail;
77 srv = objt_server(conn->target);
Christopher Faulet08016ab2020-07-01 16:10:06 +020078
79 /* If we're doing http-reuse always, and the connection is not
80 * private with available streams (an http2 connection), add it
81 * to the available list, so that others can use it right
82 * away. If the connection is private, add it in the session
83 * server list.
84 */
Christopher Faulet2883fcf2020-07-01 14:59:43 +020085 if (srv && ((srv->proxy->options & PR_O_REUSE_MASK) == PR_O_REUSE_ALWS) &&
Christopher Fauletaa278532020-06-30 14:47:46 +020086 !(conn->flags & CO_FL_PRIVATE) && conn->mux->avail_streams(conn) > 0)
Willy Tarreau430bf4a2021-03-04 09:45:32 +010087 ebmb_insert(&srv->per_thr[tid].avail_conns, &conn->hash_node->node, sizeof(conn->hash_node->hash));
Christopher Faulet08016ab2020-07-01 16:10:06 +020088 else if (conn->flags & CO_FL_PRIVATE) {
Ilya Shipitsin6b79f382020-07-23 00:32:55 +050089 /* If it fail now, the same will be done in mux->detach() callback */
Willy Tarreau38b4d2e2020-11-20 17:08:15 +010090 session_add_conn(sess, conn, conn->target);
Christopher Faulet08016ab2020-07-01 16:10:06 +020091 }
Olivier Houchard477902b2020-01-22 18:08:48 +010092 return 0;
93fail:
94 /* let the upper layer know the connection failed */
95 cs->data_cb->wake(cs);
96 return -1;
97 } else
98 return conn_complete_session(conn);
99
Willy Tarreau930428c2021-10-06 18:27:28 +0200100}
101
102/* This is used at the end of the socket IOCB to possibly create the mux if it
103 * was not done yet, or wake it up if flags changed compared to old_flags or if
104 * need_wake insists on this. It returns <0 if the connection was destroyed and
105 * must not be used, >=0 otherwise.
106 */
107int conn_notify_mux(struct connection *conn, int old_flags, int forced_wake)
108{
109 int ret = 0;
110
111 /* If we don't yet have a mux, that means we were waiting for
112 * information to create one, typically from the ALPN. If we're
113 * done with the handshake, attempt to create one.
114 */
115 if (unlikely(!conn->mux) && !(conn->flags & CO_FL_WAIT_XPRT)) {
116 ret = conn_create_mux(conn);
117 if (ret < 0)
118 goto done;
119 }
120
121 /* The wake callback is normally used to notify the data layer about
122 * data layer activity (successful send/recv), connection establishment,
123 * shutdown and fatal errors. We need to consider the following
124 * situations to wake up the data layer :
125 * - change among the CO_FL_NOTIFY_DONE flags :
126 * SOCK_{RD,WR}_SH, ERROR,
127 * - absence of any of {L4,L6}_CONN and CONNECTED, indicating the
128 * end of handshake and transition to CONNECTED
129 * - raise of CONNECTED with HANDSHAKE down
130 * - end of HANDSHAKE with CONNECTED set
131 * - regular data layer activity
132 *
133 * One tricky case is the wake up on read0 or error on an idle
134 * backend connection, that can happen on a connection that is still
135 * polled while at the same moment another thread is about to perform a
136 * takeover. The solution against this is to remove the connection from
137 * the idle list if it was in it, and possibly reinsert it at the end
138 * if the connection remains valid. The cost is non-null (locked tree
139 * removal) but remains low given that this is extremely rarely called.
140 * In any case it's guaranteed by the FD's thread_mask that we're
141 * called from the same thread the connection is queued in.
142 *
143 * Note that the wake callback is allowed to release the connection and
144 * the fd (and return < 0 in this case).
145 */
146 if ((forced_wake ||
147 ((conn->flags ^ old_flags) & CO_FL_NOTIFY_DONE) ||
148 ((old_flags & CO_FL_WAIT_XPRT) && !(conn->flags & CO_FL_WAIT_XPRT))) &&
149 conn->mux && conn->mux->wake) {
150 uint conn_in_list = conn->flags & CO_FL_LIST_MASK;
151 struct server *srv = objt_server(conn->target);
152
153 if (conn_in_list) {
154 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
155 conn_delete_from_tree(&conn->hash_node->node);
156 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
157 }
158
159 ret = conn->mux->wake(conn);
160 if (ret < 0)
161 goto done;
162
163 if (conn_in_list) {
164 struct eb_root *root = (conn_in_list == CO_FL_SAFE_LIST) ?
165 &srv->per_thr[tid].safe_conns :
166 &srv->per_thr[tid].idle_conns;
167
168 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
169 ebmb_insert(root, &conn->hash_node->node, sizeof(conn->hash_node->hash));
170 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
171 }
172 }
173 done:
174 return ret;
Olivier Houchard477902b2020-01-22 18:08:48 +0100175}
176
Willy Tarreauaac777f2021-10-06 18:48:28 +0200177/* Change the mux for the connection.
178 * The caller should make sure he's not subscribed to the underlying XPRT.
179 */
180int conn_upgrade_mux_fe(struct connection *conn, void *ctx, struct buffer *buf,
181 struct ist mux_proto, int mode)
182{
183 struct bind_conf *bind_conf = __objt_listener(conn->target)->bind_conf;
184 const struct mux_ops *old_mux, *new_mux;
185 void *old_mux_ctx;
186 const char *alpn_str = NULL;
187 int alpn_len = 0;
188
189 if (!mux_proto.len) {
190 conn_get_alpn(conn, &alpn_str, &alpn_len);
191 mux_proto = ist2(alpn_str, alpn_len);
192 }
193 new_mux = conn_get_best_mux(conn, mux_proto, PROTO_SIDE_FE, mode);
194 old_mux = conn->mux;
195
196 /* No mux found */
197 if (!new_mux)
198 return -1;
199
200 /* Same mux, nothing to do */
201 if (old_mux == new_mux)
202 return 0;
203
204 old_mux_ctx = conn->ctx;
205 conn->mux = new_mux;
206 conn->ctx = ctx;
207 if (new_mux->init(conn, bind_conf->frontend, conn->owner, buf) == -1) {
208 /* The mux upgrade failed, so restore the old mux */
209 conn->ctx = old_mux_ctx;
210 conn->mux = old_mux;
211 return -1;
212 }
213
214 /* The mux was upgraded, destroy the old one */
215 *buf = BUF_NULL;
216 old_mux->destroy(old_mux_ctx);
217 return 0;
218}
219
220/* installs the best mux for incoming connection <conn> using the upper context
221 * <ctx>. If the mux protocol is forced, we use it to find the best
222 * mux. Otherwise we use the ALPN name, if any. Returns < 0 on error.
223 */
224int conn_install_mux_fe(struct connection *conn, void *ctx)
225{
226 struct bind_conf *bind_conf = __objt_listener(conn->target)->bind_conf;
227 const struct mux_ops *mux_ops;
228
229 if (bind_conf->mux_proto)
230 mux_ops = bind_conf->mux_proto->mux;
231 else {
232 struct ist mux_proto;
233 const char *alpn_str = NULL;
234 int alpn_len = 0;
235 int mode;
236
237 if (bind_conf->frontend->mode == PR_MODE_HTTP)
238 mode = PROTO_MODE_HTTP;
239 else
240 mode = PROTO_MODE_TCP;
241
242 conn_get_alpn(conn, &alpn_str, &alpn_len);
243 mux_proto = ist2(alpn_str, alpn_len);
244 mux_ops = conn_get_best_mux(conn, mux_proto, PROTO_SIDE_FE, mode);
245 if (!mux_ops)
246 return -1;
247 }
248 return conn_install_mux(conn, mux_ops, ctx, bind_conf->frontend, conn->owner);
249}
250
251/* installs the best mux for outgoing connection <conn> using the upper context
Amaury Denoyelleac03ef22021-10-28 16:36:11 +0200252 * <ctx>. If the server mux protocol is forced, we use it to find the best mux.
253 * It's also possible to specify an alternative mux protocol <force_mux_ops>,
254 * in which case it will be used instead of the default server mux protocol.
255 *
256 * Returns < 0 on error.
Willy Tarreauaac777f2021-10-06 18:48:28 +0200257 */
Amaury Denoyelleac03ef22021-10-28 16:36:11 +0200258int conn_install_mux_be(struct connection *conn, void *ctx, struct session *sess,
259 const struct mux_ops *force_mux_ops)
Willy Tarreauaac777f2021-10-06 18:48:28 +0200260{
261 struct server *srv = objt_server(conn->target);
262 struct proxy *prx = objt_proxy(conn->target);
263 const struct mux_ops *mux_ops;
264
265 if (srv)
266 prx = srv->proxy;
267
268 if (!prx) // target must be either proxy or server
269 return -1;
270
Amaury Denoyelleac03ef22021-10-28 16:36:11 +0200271 if (srv && srv->mux_proto && likely(!force_mux_ops)) {
Willy Tarreauaac777f2021-10-06 18:48:28 +0200272 mux_ops = srv->mux_proto->mux;
Amaury Denoyelleac03ef22021-10-28 16:36:11 +0200273 }
274 else if (srv && unlikely(force_mux_ops)) {
275 mux_ops = force_mux_ops;
276 }
Willy Tarreauaac777f2021-10-06 18:48:28 +0200277 else {
278 struct ist mux_proto;
279 const char *alpn_str = NULL;
280 int alpn_len = 0;
281 int mode;
282
283 if (prx->mode == PR_MODE_HTTP)
284 mode = PROTO_MODE_HTTP;
285 else
286 mode = PROTO_MODE_TCP;
287
288 conn_get_alpn(conn, &alpn_str, &alpn_len);
289 mux_proto = ist2(alpn_str, alpn_len);
290
291 mux_ops = conn_get_best_mux(conn, mux_proto, PROTO_SIDE_BE, mode);
292 if (!mux_ops)
293 return -1;
294 }
295 return conn_install_mux(conn, mux_ops, ctx, prx, sess);
296}
297
298/* installs the best mux for outgoing connection <conn> for a check using the
299 * upper context <ctx>. If the mux protocol is forced by the check, we use it to
300 * find the best mux. Returns < 0 on error.
301 */
302int conn_install_mux_chk(struct connection *conn, void *ctx, struct session *sess)
303{
304 struct check *check = objt_check(sess->origin);
305 struct server *srv = objt_server(conn->target);
306 struct proxy *prx = objt_proxy(conn->target);
307 const struct mux_ops *mux_ops;
308
309 if (!check) // Check must be defined
310 return -1;
311
312 if (srv)
313 prx = srv->proxy;
314
315 if (!prx) // target must be either proxy or server
316 return -1;
317
318 if (check->mux_proto)
319 mux_ops = check->mux_proto->mux;
320 else {
321 struct ist mux_proto;
322 const char *alpn_str = NULL;
323 int alpn_len = 0;
324 int mode;
325
326 if ((check->tcpcheck_rules->flags & TCPCHK_RULES_PROTO_CHK) == TCPCHK_RULES_HTTP_CHK)
327 mode = PROTO_MODE_HTTP;
328 else
329 mode = PROTO_MODE_TCP;
330
331 conn_get_alpn(conn, &alpn_str, &alpn_len);
332 mux_proto = ist2(alpn_str, alpn_len);
333
334 mux_ops = conn_get_best_mux(conn, mux_proto, PROTO_SIDE_BE, mode);
335 if (!mux_ops)
336 return -1;
337 }
338 return conn_install_mux(conn, mux_ops, ctx, prx, sess);
339}
340
Amaury Denoyelle2454bda2021-10-18 14:32:36 +0200341/* Set the ALPN of connection <conn> to <alpn>. If force is false, <alpn> must
342 * be a subset or identical to the registered protos for the parent SSL_CTX.
343 * In this case <alpn> must be a single protocol value, not a list.
344 *
345 * Returns 0 if ALPN is updated else -1.
346 */
347int conn_update_alpn(struct connection *conn, const struct ist alpn, int force)
348{
349#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
350 size_t alpn_len = istlen(alpn);
351 char *ctx_alpn_str = NULL;
352 int ctx_alpn_len = 0, found = 0;
353
354 /* if not force, first search if alpn is a subset or identical to the
355 * parent SSL_CTX.
356 */
357 if (!force) {
358 /* retrieve the SSL_CTX according to the connection side. */
359 if (conn_is_back(conn)) {
360 if (obj_type(conn->target) == OBJ_TYPE_SERVER) {
361 struct server *srv = __objt_server(conn->target);
362 ctx_alpn_str = srv->ssl_ctx.alpn_str;
363 ctx_alpn_len = srv->ssl_ctx.alpn_len;
364 }
365 }
366 else {
367 struct session *sess = conn->owner;
368 struct listener *li = sess->listener;
369
370 if (li->bind_conf && li->bind_conf->is_ssl) {
371 ctx_alpn_str = li->bind_conf->ssl_conf.alpn_str;
372 ctx_alpn_len = li->bind_conf->ssl_conf.alpn_len;
373 }
374 }
375
376 if (ctx_alpn_str) {
377 /* search if ALPN is present in SSL_CTX ALPN before
378 * using it.
379 */
380 while (ctx_alpn_len) {
381 /* skip ALPN whose size is not 8 */
382 if (*ctx_alpn_str != alpn_len - 1) {
383 ctx_alpn_len -= *ctx_alpn_str + 1;
384 }
385 else {
386 if (isteqi(ist2(ctx_alpn_str, alpn_len), alpn)) {
387 found = 1;
388 break;
389 }
390 }
391 ctx_alpn_str += *ctx_alpn_str + 1;
392
393 /* This indicates an invalid ALPN formatted
394 * string and should never happen. */
395 BUG_ON(ctx_alpn_len < 0);
396 }
397 }
398 }
399
400 if (found || force) {
401 ssl_sock_set_alpn(conn, (const uchar *)istptr(alpn), istlen(alpn));
402 return 0;
403 }
404
405#endif
406 return -1;
407}
408
Willy Tarreauaac777f2021-10-06 18:48:28 +0200409/* Initializes all required fields for a new connection. Note that it does the
410 * minimum acceptable initialization for a connection that already exists and
411 * is about to be reused. It also leaves the addresses untouched, which makes
412 * it usable across connection retries to reset a connection to a known state.
413 */
414void conn_init(struct connection *conn, void *target)
415{
416 conn->obj_type = OBJ_TYPE_CONN;
417 conn->flags = CO_FL_NONE;
418 conn->mux = NULL;
419 conn->ctx = NULL;
420 conn->owner = NULL;
421 conn->send_proxy_ofs = 0;
422 conn->handle.fd = DEAD_FD_MAGIC;
423 conn->err_code = CO_ER_NONE;
424 conn->target = target;
425 conn->destroy_cb = NULL;
426 conn->proxy_netns = NULL;
427 MT_LIST_INIT(&conn->toremove_list);
428 if (conn_is_back(conn))
429 LIST_INIT(&conn->session_list);
430 else
431 LIST_INIT(&conn->stopping_list);
432 conn->subs = NULL;
433 conn->src = NULL;
434 conn->dst = NULL;
435 conn->proxy_authority = IST_NULL;
436 conn->proxy_unique_id = IST_NULL;
Willy Tarreauaac777f2021-10-06 18:48:28 +0200437 conn->hash_node = NULL;
438 conn->xprt = NULL;
439}
440
441/* Tries to allocate a new connection and initialized its main fields. The
442 * connection is returned on success, NULL on failure. The connection must
443 * be released using pool_free() or conn_free().
444 */
445struct connection *conn_new(void *target)
446{
447 struct connection *conn;
448 struct conn_hash_node *hash_node;
449
450 conn = pool_alloc(pool_head_connection);
451 if (unlikely(!conn))
452 return NULL;
453
454 conn_init(conn, target);
455
456 if (conn_is_back(conn)) {
457 if (obj_type(target) == OBJ_TYPE_SERVER)
458 srv_use_conn(__objt_server(target), conn);
459
460 hash_node = conn_alloc_hash_node(conn);
461 if (unlikely(!hash_node)) {
462 pool_free(pool_head_connection, conn);
463 return NULL;
464 }
465
466 conn->hash_node = hash_node;
467 }
468
469 return conn;
470}
471
472/* Releases a connection previously allocated by conn_new() */
473void conn_free(struct connection *conn)
474{
475 /* If the connection is owned by the session, remove it from its list
476 */
477 if (conn_is_back(conn) && LIST_INLIST(&conn->session_list)) {
478 session_unown_conn(conn->owner, conn);
479 }
480 else if (!(conn->flags & CO_FL_PRIVATE)) {
481 if (obj_type(conn->target) == OBJ_TYPE_SERVER)
482 srv_release_conn(__objt_server(conn->target), conn);
483 }
484
485 /* Remove the conn from toremove_list.
486 *
487 * This is needed to prevent a double-free in case the connection was
488 * already scheduled from cleaning but is freed before via another
489 * call.
490 */
491 MT_LIST_DELETE(&conn->toremove_list);
492
493 sockaddr_free(&conn->src);
494 sockaddr_free(&conn->dst);
495
496 pool_free(pool_head_authority, istptr(conn->proxy_authority));
497 conn->proxy_authority = IST_NULL;
498
499 pool_free(pool_head_uniqueid, istptr(conn->proxy_unique_id));
500 conn->proxy_unique_id = IST_NULL;
501
502 pool_free(pool_head_conn_hash_node, conn->hash_node);
503 conn->hash_node = NULL;
504
505 /* By convention we always place a NULL where the ctx points to if the
506 * mux is null. It may have been used to store the connection as a
507 * stream_interface's end point for example.
508 */
509 if (conn->ctx != NULL && conn->mux == NULL)
510 *(void **)conn->ctx = NULL;
511
512 conn_force_unsubscribe(conn);
513 pool_free(pool_head_connection, conn);
514}
515
Willy Tarreau8de90c72021-10-06 19:11:10 +0200516struct conn_hash_node *conn_alloc_hash_node(struct connection *conn)
517{
518 struct conn_hash_node *hash_node = NULL;
519
520 hash_node = pool_zalloc(pool_head_conn_hash_node);
521 if (unlikely(!hash_node))
522 return NULL;
523
524 hash_node->conn = conn;
525
526 return hash_node;
527}
528
529/* Allocates a struct sockaddr from the pool if needed, assigns it to *sap and
530 * returns it. If <sap> is NULL, the address is always allocated and returned.
531 * if <sap> is non-null, an address will only be allocated if it points to a
532 * non-null pointer. In this case the allocated address will be assigned there.
533 * If <orig> is non-null and <len> positive, the address in <sa> will be copied
534 * into the allocated address. In both situations the new pointer is returned.
535 */
536struct sockaddr_storage *sockaddr_alloc(struct sockaddr_storage **sap, const struct sockaddr_storage *orig, socklen_t len)
537{
538 struct sockaddr_storage *sa;
539
540 if (sap && *sap)
541 return *sap;
542
543 sa = pool_alloc(pool_head_sockaddr);
544 if (sa && orig && len > 0)
545 memcpy(sa, orig, len);
546 if (sap)
547 *sap = sa;
548 return sa;
549}
550
551/* Releases the struct sockaddr potentially pointed to by <sap> to the pool. It
552 * may be NULL or may point to NULL. If <sap> is not NULL, a NULL is placed
553 * there.
554 */
555void sockaddr_free(struct sockaddr_storage **sap)
556{
557 if (!sap)
558 return;
559 pool_free(pool_head_sockaddr, *sap);
560 *sap = NULL;
561}
562
Willy Tarreauaac777f2021-10-06 18:48:28 +0200563/* Try to add a handshake pseudo-XPRT. If the connection's first XPRT is
564 * raw_sock, then just use the new XPRT as the connection XPRT, otherwise
565 * call the xprt's add_xprt() method.
566 * Returns 0 on success, or non-zero on failure.
567 */
568int xprt_add_hs(struct connection *conn)
569{
570 void *xprt_ctx = NULL;
571 const struct xprt_ops *ops = xprt_get(XPRT_HANDSHAKE);
572 void *nextxprt_ctx = NULL;
573 const struct xprt_ops *nextxprt_ops = NULL;
574
575 if (conn->flags & CO_FL_ERROR)
576 return -1;
577 if (ops->init(conn, &xprt_ctx) < 0)
578 return -1;
579 if (conn->xprt == xprt_get(XPRT_RAW)) {
580 nextxprt_ctx = conn->xprt_ctx;
581 nextxprt_ops = conn->xprt;
582 conn->xprt_ctx = xprt_ctx;
583 conn->xprt = ops;
584 } else {
585 if (conn->xprt->add_xprt(conn, conn->xprt_ctx, xprt_ctx, ops,
586 &nextxprt_ctx, &nextxprt_ops) != 0) {
587 ops->close(conn, xprt_ctx);
588 return -1;
589 }
590 }
591 if (ops->add_xprt(conn, xprt_ctx, nextxprt_ctx, nextxprt_ops, NULL, NULL) != 0) {
592 ops->close(conn, xprt_ctx);
593 return -1;
594 }
595 return 0;
596}
597
598/* returns a human-readable error code for conn->err_code, or NULL if the code
599 * is unknown.
600 */
601const char *conn_err_code_str(struct connection *c)
602{
603 switch (c->err_code) {
604 case CO_ER_NONE: return "Success";
605
606 case CO_ER_CONF_FDLIM: return "Reached configured maxconn value";
607 case CO_ER_PROC_FDLIM: return "Too many sockets on the process";
608 case CO_ER_SYS_FDLIM: return "Too many sockets on the system";
609 case CO_ER_SYS_MEMLIM: return "Out of system buffers";
610 case CO_ER_NOPROTO: return "Protocol or address family not supported";
611 case CO_ER_SOCK_ERR: return "General socket error";
612 case CO_ER_PORT_RANGE: return "Source port range exhausted";
613 case CO_ER_CANT_BIND: return "Can't bind to source address";
614 case CO_ER_FREE_PORTS: return "Out of local source ports on the system";
615 case CO_ER_ADDR_INUSE: return "Local source address already in use";
616
617 case CO_ER_PRX_EMPTY: return "Connection closed while waiting for PROXY protocol header";
618 case CO_ER_PRX_ABORT: return "Connection error while waiting for PROXY protocol header";
619 case CO_ER_PRX_TIMEOUT: return "Timeout while waiting for PROXY protocol header";
620 case CO_ER_PRX_TRUNCATED: return "Truncated PROXY protocol header received";
621 case CO_ER_PRX_NOT_HDR: return "Received something which does not look like a PROXY protocol header";
622 case CO_ER_PRX_BAD_HDR: return "Received an invalid PROXY protocol header";
623 case CO_ER_PRX_BAD_PROTO: return "Received an unhandled protocol in the PROXY protocol header";
624
625 case CO_ER_CIP_EMPTY: return "Connection closed while waiting for NetScaler Client IP header";
626 case CO_ER_CIP_ABORT: return "Connection error while waiting for NetScaler Client IP header";
627 case CO_ER_CIP_TIMEOUT: return "Timeout while waiting for a NetScaler Client IP header";
628 case CO_ER_CIP_TRUNCATED: return "Truncated NetScaler Client IP header received";
629 case CO_ER_CIP_BAD_MAGIC: return "Received an invalid NetScaler Client IP magic number";
630 case CO_ER_CIP_BAD_PROTO: return "Received an unhandled protocol in the NetScaler Client IP header";
631
632 case CO_ER_SSL_EMPTY: return "Connection closed during SSL handshake";
633 case CO_ER_SSL_ABORT: return "Connection error during SSL handshake";
634 case CO_ER_SSL_TIMEOUT: return "Timeout during SSL handshake";
635 case CO_ER_SSL_TOO_MANY: return "Too many SSL connections";
636 case CO_ER_SSL_NO_MEM: return "Out of memory when initializing an SSL connection";
637 case CO_ER_SSL_RENEG: return "Rejected a client-initiated SSL renegotiation attempt";
638 case CO_ER_SSL_CA_FAIL: return "SSL client CA chain cannot be verified";
639 case CO_ER_SSL_CRT_FAIL: return "SSL client certificate not trusted";
640 case CO_ER_SSL_MISMATCH: return "Server presented an SSL certificate different from the configured one";
641 case CO_ER_SSL_MISMATCH_SNI: return "Server presented an SSL certificate different from the expected one";
642 case CO_ER_SSL_HANDSHAKE: return "SSL handshake failure";
643 case CO_ER_SSL_HANDSHAKE_HB: return "SSL handshake failure after heartbeat";
644 case CO_ER_SSL_KILLED_HB: return "Stopped a TLSv1 heartbeat attack (CVE-2014-0160)";
645 case CO_ER_SSL_NO_TARGET: return "Attempt to use SSL on an unknown target (internal error)";
646 case CO_ER_SSL_EARLY_FAILED: return "Server refused early data";
647
648 case CO_ER_SOCKS4_SEND: return "SOCKS4 Proxy write error during handshake";
649 case CO_ER_SOCKS4_RECV: return "SOCKS4 Proxy read error during handshake";
650 case CO_ER_SOCKS4_DENY: return "SOCKS4 Proxy deny the request";
651 case CO_ER_SOCKS4_ABORT: return "SOCKS4 Proxy handshake aborted by server";
652
653 case CO_ERR_SSL_FATAL: return "SSL fatal error";
654 }
655 return NULL;
656}
657
Willy Tarreauff3e6482015-03-12 23:56:52 +0100658/* Send a message over an established connection. It makes use of send() and
659 * returns the same return code and errno. If the socket layer is not ready yet
660 * then -1 is returned and ENOTSOCK is set into errno. If the fd is not marked
661 * as ready, or if EAGAIN or ENOTCONN is returned, then we return 0. It returns
662 * EMSGSIZE if called with a zero length message. The purpose is to simplify
663 * some rare attempts to directly write on the socket from above the connection
664 * (typically send_proxy). In case of EAGAIN, the fd is marked as "cant_send".
665 * It automatically retries on EINTR. Other errors cause the connection to be
666 * marked as in error state. It takes similar arguments as send() except the
Willy Tarreau827fee72020-12-11 15:26:55 +0100667 * first one which is the connection instead of the file descriptor. <flags>
668 * only support CO_SFL_MSG_MORE.
Willy Tarreauff3e6482015-03-12 23:56:52 +0100669 */
Willy Tarreau827fee72020-12-11 15:26:55 +0100670int conn_ctrl_send(struct connection *conn, const void *buf, int len, int flags)
Willy Tarreauff3e6482015-03-12 23:56:52 +0100671{
Willy Tarreau827fee72020-12-11 15:26:55 +0100672 const struct buffer buffer = b_make((char*)buf, len, 0, len);
673 const struct xprt_ops *xprt = xprt_get(XPRT_RAW);
Willy Tarreauff3e6482015-03-12 23:56:52 +0100674 int ret;
675
676 ret = -1;
677 errno = ENOTSOCK;
678
679 if (conn->flags & CO_FL_SOCK_WR_SH)
680 goto fail;
681
682 if (!conn_ctrl_ready(conn))
683 goto fail;
684
685 errno = EMSGSIZE;
686 if (!len)
687 goto fail;
688
Willy Tarreau827fee72020-12-11 15:26:55 +0100689 /* snd_buf() already takes care of updating conn->flags and handling
690 * the FD polling status.
691 */
692 ret = xprt->snd_buf(conn, NULL, &buffer, buffer.data, flags);
693 if (conn->flags & CO_FL_ERROR)
694 ret = -1;
695 return ret;
Willy Tarreauff3e6482015-03-12 23:56:52 +0100696 fail:
697 conn->flags |= CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH | CO_FL_ERROR;
698 return ret;
699}
700
Willy Tarreau746b0512020-12-11 17:06:11 +0100701/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
702 * The event subscriber <es> is not allowed to change from a previous call as
703 * long as at least one event is still subscribed. The <event_type> must only
704 * be a combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0.
Willy Tarreauee1a6fc2020-01-17 07:52:13 +0100705 */
706int conn_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houchard83a0cd82018-09-28 17:57:58 +0200707{
Willy Tarreau7872d1f2020-01-10 07:06:05 +0100708 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +0100709 BUG_ON(conn->subs && conn->subs != es);
Willy Tarreau7872d1f2020-01-10 07:06:05 +0100710
Willy Tarreauee1a6fc2020-01-17 07:52:13 +0100711 es->events &= ~event_type;
712 if (!es->events)
Willy Tarreau7872d1f2020-01-10 07:06:05 +0100713 conn->subs = NULL;
714
Willy Tarreau746b0512020-12-11 17:06:11 +0100715 if (conn_ctrl_ready(conn) && conn->ctrl->ignore_events)
716 conn->ctrl->ignore_events(conn, event_type);
Willy Tarreau7872d1f2020-01-10 07:06:05 +0100717
Olivier Houchard83a0cd82018-09-28 17:57:58 +0200718 return 0;
719}
720
Willy Tarreau7e59c0a2020-02-28 14:24:49 +0100721/* Called from the upper layer, to subscribe <es> to events <event_type>.
722 * The <es> struct is not allowed to differ from the one passed during a
Willy Tarreau746b0512020-12-11 17:06:11 +0100723 * previous call to subscribe(). If the connection's ctrl layer is ready,
724 * the wait_event is immediately woken up and the subcription is cancelled.
725 * It always returns zero.
Willy Tarreauee1a6fc2020-01-17 07:52:13 +0100726 */
727int conn_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houchard6ff20392018-07-17 18:46:31 +0200728{
Willy Tarreau746b0512020-12-11 17:06:11 +0100729 int ret = 0;
730
Willy Tarreau7872d1f2020-01-10 07:06:05 +0100731 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +0100732 BUG_ON(conn->subs && conn->subs != es);
Willy Tarreau7872d1f2020-01-10 07:06:05 +0100733
Willy Tarreau7e59c0a2020-02-28 14:24:49 +0100734 if (conn->subs && (conn->subs->events & event_type) == event_type)
735 return 0;
736
Willy Tarreau746b0512020-12-11 17:06:11 +0100737 if (conn_ctrl_ready(conn) && conn->ctrl->check_events) {
738 ret = conn->ctrl->check_events(conn, event_type);
739 if (ret)
740 tasklet_wakeup(es->tasklet);
Willy Tarreaud1d14c32020-02-21 10:34:19 +0100741 }
Willy Tarreau746b0512020-12-11 17:06:11 +0100742
743 es->events = (es->events | event_type) & ~ret;
744 conn->subs = es->events ? es : NULL;
Olivier Houchard83a0cd82018-09-28 17:57:58 +0200745 return 0;
Olivier Houchard6ff20392018-07-17 18:46:31 +0200746}
747
Willy Tarreau2ded48d2020-12-11 16:20:34 +0100748/* Drains possibly pending incoming data on the connection and update the flags
749 * accordingly. This is used to know whether we need to disable lingering on
750 * close. Returns non-zero if it is safe to close without disabling lingering,
751 * otherwise zero. The CO_FL_SOCK_RD_SH flag may also be updated if the incoming
752 * shutdown was reported by the ->drain() function.
Willy Tarreaud85c4852015-03-13 00:40:28 +0100753 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +0100754int conn_ctrl_drain(struct connection *conn)
Willy Tarreaud85c4852015-03-13 00:40:28 +0100755{
Willy Tarreau2ded48d2020-12-11 16:20:34 +0100756 int ret = 0;
Willy Tarreaue215bba2018-08-24 14:31:53 +0200757
Willy Tarreau2ded48d2020-12-11 16:20:34 +0100758 if (!conn_ctrl_ready(conn) || conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH))
759 ret = 1;
760 else if (conn->ctrl->drain) {
761 ret = conn->ctrl->drain(conn);
762 if (ret)
763 conn->flags |= CO_FL_SOCK_RD_SH;
Willy Tarreaud85c4852015-03-13 00:40:28 +0100764 }
Willy Tarreau2ded48d2020-12-11 16:20:34 +0100765 return ret;
Willy Tarreaud85c4852015-03-13 00:40:28 +0100766}
767
KOVACS Krisztianb3e54fe2014-11-17 15:11:45 +0100768/*
769 * Get data length from tlv
770 */
Tim Duesterhusba837ec2020-03-05 23:11:02 +0100771static inline size_t get_tlv_length(const struct tlv *src)
KOVACS Krisztianb3e54fe2014-11-17 15:11:45 +0100772{
773 return (src->length_hi << 8) | src->length_lo;
774}
775
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200776/* This handshake handler waits a PROXY protocol header at the beginning of the
777 * raw data stream. The header looks like this :
778 *
779 * "PROXY" <SP> PROTO <SP> SRC3 <SP> DST3 <SP> SRC4 <SP> <DST4> "\r\n"
780 *
781 * There must be exactly one space between each field. Fields are :
782 * - PROTO : layer 4 protocol, which must be "TCP4" or "TCP6".
783 * - SRC3 : layer 3 (eg: IP) source address in standard text form
784 * - DST3 : layer 3 (eg: IP) destination address in standard text form
785 * - SRC4 : layer 4 (eg: TCP port) source address in standard text form
786 * - DST4 : layer 4 (eg: TCP port) destination address in standard text form
787 *
788 * This line MUST be at the beginning of the buffer and MUST NOT wrap.
789 *
790 * The header line is small and in all cases smaller than the smallest normal
791 * TCP MSS. So it MUST always be delivered as one segment, which ensures we
792 * can safely use MSG_PEEK and avoid buffering.
793 *
794 * Once the data is fetched, the values are set in the connection's address
795 * fields, and data are removed from the socket's buffer. The function returns
796 * zero if it needs to wait for more data or if it fails, or 1 if it completed
797 * and removed itself.
798 */
799int conn_recv_proxy(struct connection *conn, int flag)
800{
Christopher Fauletc105c922021-10-25 08:17:11 +0200801 struct session *sess = conn->owner;
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200802 char *line, *end;
Willy Tarreau77992672014-06-14 11:06:17 +0200803 struct proxy_hdr_v2 *hdr_v2;
804 const char v2sig[] = PP2_SIGNATURE;
Tim Duesterhus488ee7f2020-03-05 22:55:20 +0100805 size_t total_v2_len;
Tim Duesterhusba837ec2020-03-05 23:11:02 +0100806 size_t tlv_offset = 0;
Willy Tarreaub406b872018-08-22 05:20:32 +0200807 int ret;
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200808
Willy Tarreau3c728722014-01-23 13:50:42 +0100809 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +0200810 goto fail;
811
Willy Tarreau07ecfc52022-04-11 18:07:03 +0200812 BUG_ON(conn->flags & CO_FL_FDLESS);
813
Willy Tarreau585744b2017-08-24 14:31:19 +0200814 if (!fd_recv_ready(conn->handle.fd))
Willy Tarreau6499b9d2019-06-03 08:17:30 +0200815 goto not_ready;
Willy Tarreaufd803bb2014-01-20 15:13:07 +0100816
Willy Tarreau157788c2020-02-11 10:08:05 +0100817 while (1) {
Willy Tarreaub406b872018-08-22 05:20:32 +0200818 ret = recv(conn->handle.fd, trash.area, trash.size, MSG_PEEK);
819 if (ret < 0) {
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200820 if (errno == EINTR)
821 continue;
822 if (errno == EAGAIN) {
Willy Tarreau585744b2017-08-24 14:31:19 +0200823 fd_cant_recv(conn->handle.fd);
Willy Tarreau6499b9d2019-06-03 08:17:30 +0200824 goto not_ready;
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200825 }
Willy Tarreau8e3bf692012-12-03 15:41:18 +0100826 goto recv_abort;
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200827 }
Willy Tarreaub406b872018-08-22 05:20:32 +0200828 trash.data = ret;
Willy Tarreau157788c2020-02-11 10:08:05 +0100829 break;
830 }
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200831
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200832 if (!trash.data) {
Willy Tarreau8e3bf692012-12-03 15:41:18 +0100833 /* client shutdown */
834 conn->err_code = CO_ER_PRX_EMPTY;
835 goto fail;
836 }
837
Willy Tarreauc192b0a2020-01-23 09:11:58 +0100838 conn->flags &= ~CO_FL_WAIT_L4_CONN;
839
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200840 if (trash.data < 6)
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200841 goto missing;
842
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200843 line = trash.area;
844 end = trash.area + trash.data;
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200845
846 /* Decode a possible proxy request, fail early if it does not match */
Willy Tarreau77992672014-06-14 11:06:17 +0200847 if (strncmp(line, "PROXY ", 6) != 0)
848 goto not_v1;
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200849
850 line += 6;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200851 if (trash.data < 9) /* shortest possible line */
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200852 goto missing;
853
David CARLIER42ff05e2016-03-24 09:22:36 +0000854 if (memcmp(line, "TCP4 ", 5) == 0) {
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200855 u32 src3, dst3, sport, dport;
856
857 line += 5;
858
859 src3 = inetaddr_host_lim_ret(line, end, &line);
860 if (line == end)
861 goto missing;
862 if (*line++ != ' ')
Willy Tarreau8e3bf692012-12-03 15:41:18 +0100863 goto bad_header;
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200864
865 dst3 = inetaddr_host_lim_ret(line, end, &line);
866 if (line == end)
867 goto missing;
868 if (*line++ != ' ')
Willy Tarreau8e3bf692012-12-03 15:41:18 +0100869 goto bad_header;
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200870
871 sport = read_uint((const char **)&line, end);
872 if (line == end)
873 goto missing;
874 if (*line++ != ' ')
Willy Tarreau8e3bf692012-12-03 15:41:18 +0100875 goto bad_header;
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200876
877 dport = read_uint((const char **)&line, end);
878 if (line > end - 2)
879 goto missing;
880 if (*line++ != '\r')
Willy Tarreau8e3bf692012-12-03 15:41:18 +0100881 goto bad_header;
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200882 if (*line++ != '\n')
Willy Tarreau8e3bf692012-12-03 15:41:18 +0100883 goto bad_header;
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200884
Christopher Fauletc105c922021-10-25 08:17:11 +0200885 if (!sess || !sockaddr_alloc(&sess->src, NULL, 0) || !sockaddr_alloc(&sess->dst, NULL, 0))
886 goto fail;
887
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200888 /* update the session's addresses and mark them set */
Christopher Fauletc105c922021-10-25 08:17:11 +0200889 ((struct sockaddr_in *)sess->src)->sin_family = AF_INET;
890 ((struct sockaddr_in *)sess->src)->sin_addr.s_addr = htonl(src3);
891 ((struct sockaddr_in *)sess->src)->sin_port = htons(sport);
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200892
Christopher Fauletc105c922021-10-25 08:17:11 +0200893 ((struct sockaddr_in *)sess->dst)->sin_family = AF_INET;
894 ((struct sockaddr_in *)sess->dst)->sin_addr.s_addr = htonl(dst3);
895 ((struct sockaddr_in *)sess->dst)->sin_port = htons(dport);
896 sess->flags |= SESS_FL_ADDR_FROM_SET | SESS_FL_ADDR_TO_SET;
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200897 }
David CARLIER42ff05e2016-03-24 09:22:36 +0000898 else if (memcmp(line, "TCP6 ", 5) == 0) {
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200899 u32 sport, dport;
900 char *src_s;
901 char *dst_s, *sport_s, *dport_s;
902 struct in6_addr src3, dst3;
903
904 line += 5;
905
906 src_s = line;
907 dst_s = sport_s = dport_s = NULL;
908 while (1) {
909 if (line > end - 2) {
910 goto missing;
911 }
912 else if (*line == '\r') {
913 *line = 0;
914 line++;
915 if (*line++ != '\n')
Willy Tarreau8e3bf692012-12-03 15:41:18 +0100916 goto bad_header;
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200917 break;
918 }
919
920 if (*line == ' ') {
921 *line = 0;
922 if (!dst_s)
923 dst_s = line + 1;
924 else if (!sport_s)
925 sport_s = line + 1;
926 else if (!dport_s)
927 dport_s = line + 1;
928 }
929 line++;
930 }
931
932 if (!dst_s || !sport_s || !dport_s)
Willy Tarreau8e3bf692012-12-03 15:41:18 +0100933 goto bad_header;
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200934
935 sport = read_uint((const char **)&sport_s,dport_s - 1);
936 if (*sport_s != 0)
Willy Tarreau8e3bf692012-12-03 15:41:18 +0100937 goto bad_header;
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200938
939 dport = read_uint((const char **)&dport_s,line - 2);
940 if (*dport_s != 0)
Willy Tarreau8e3bf692012-12-03 15:41:18 +0100941 goto bad_header;
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200942
943 if (inet_pton(AF_INET6, src_s, (void *)&src3) != 1)
Willy Tarreau8e3bf692012-12-03 15:41:18 +0100944 goto bad_header;
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200945
946 if (inet_pton(AF_INET6, dst_s, (void *)&dst3) != 1)
Willy Tarreau8e3bf692012-12-03 15:41:18 +0100947 goto bad_header;
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200948
Christopher Fauletc105c922021-10-25 08:17:11 +0200949 if (!sess || !sockaddr_alloc(&sess->src, NULL, 0) || !sockaddr_alloc(&sess->dst, NULL, 0))
950 goto fail;
951
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200952 /* update the session's addresses and mark them set */
Christopher Fauletc105c922021-10-25 08:17:11 +0200953 ((struct sockaddr_in6 *)sess->src)->sin6_family = AF_INET6;
954 memcpy(&((struct sockaddr_in6 *)sess->src)->sin6_addr, &src3, sizeof(struct in6_addr));
955 ((struct sockaddr_in6 *)sess->src)->sin6_port = htons(sport);
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200956
Christopher Fauletc105c922021-10-25 08:17:11 +0200957 ((struct sockaddr_in6 *)sess->dst)->sin6_family = AF_INET6;
958 memcpy(&((struct sockaddr_in6 *)sess->dst)->sin6_addr, &dst3, sizeof(struct in6_addr));
959 ((struct sockaddr_in6 *)sess->dst)->sin6_port = htons(dport);
960 sess->flags |= SESS_FL_ADDR_FROM_SET | SESS_FL_ADDR_TO_SET;
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200961 }
Willy Tarreau4c20d292014-06-14 11:41:36 +0200962 else if (memcmp(line, "UNKNOWN\r\n", 9) == 0) {
963 /* This can be a UNIX socket forwarded by an haproxy upstream */
964 line += 9;
965 }
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200966 else {
Willy Tarreau4c20d292014-06-14 11:41:36 +0200967 /* The protocol does not match something known (TCP4/TCP6/UNKNOWN) */
Willy Tarreau8e3bf692012-12-03 15:41:18 +0100968 conn->err_code = CO_ER_PRX_BAD_PROTO;
Willy Tarreaue1e4a612012-10-05 00:10:55 +0200969 goto fail;
970 }
971
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200972 trash.data = line - trash.area;
Willy Tarreau77992672014-06-14 11:06:17 +0200973 goto eat_header;
974
975 not_v1:
976 /* try PPv2 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200977 if (trash.data < PP2_HEADER_LEN)
Willy Tarreau77992672014-06-14 11:06:17 +0200978 goto missing;
979
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200980 hdr_v2 = (struct proxy_hdr_v2 *) trash.area;
Willy Tarreau77992672014-06-14 11:06:17 +0200981
982 if (memcmp(hdr_v2->sig, v2sig, PP2_SIGNATURE_LEN) != 0 ||
983 (hdr_v2->ver_cmd & PP2_VERSION_MASK) != PP2_VERSION) {
984 conn->err_code = CO_ER_PRX_NOT_HDR;
985 goto fail;
986 }
987
Tim Duesterhus488ee7f2020-03-05 22:55:20 +0100988 total_v2_len = PP2_HEADER_LEN + ntohs(hdr_v2->len);
989 if (trash.data < total_v2_len)
Willy Tarreau77992672014-06-14 11:06:17 +0200990 goto missing;
991
992 switch (hdr_v2->ver_cmd & PP2_CMD_MASK) {
993 case 0x01: /* PROXY command */
994 switch (hdr_v2->fam) {
995 case 0x11: /* TCPv4 */
KOVACS Krisztianefd3aa92014-11-19 10:53:20 +0100996 if (ntohs(hdr_v2->len) < PP2_ADDR_LEN_INET)
997 goto bad_header;
998
Christopher Fauletc105c922021-10-25 08:17:11 +0200999 if (!sess || !sockaddr_alloc(&sess->src, NULL, 0) || !sockaddr_alloc(&sess->dst, NULL, 0))
1000 goto fail;
1001
1002 ((struct sockaddr_in *)sess->src)->sin_family = AF_INET;
1003 ((struct sockaddr_in *)sess->src)->sin_addr.s_addr = hdr_v2->addr.ip4.src_addr;
1004 ((struct sockaddr_in *)sess->src)->sin_port = hdr_v2->addr.ip4.src_port;
1005 ((struct sockaddr_in *)sess->dst)->sin_family = AF_INET;
1006 ((struct sockaddr_in *)sess->dst)->sin_addr.s_addr = hdr_v2->addr.ip4.dst_addr;
1007 ((struct sockaddr_in *)sess->dst)->sin_port = hdr_v2->addr.ip4.dst_port;
1008 sess->flags |= SESS_FL_ADDR_FROM_SET | SESS_FL_ADDR_TO_SET;
KOVACS Krisztian7209c202015-07-03 14:09:10 +02001009 tlv_offset = PP2_HEADER_LEN + PP2_ADDR_LEN_INET;
Willy Tarreau77992672014-06-14 11:06:17 +02001010 break;
1011 case 0x21: /* TCPv6 */
KOVACS Krisztianefd3aa92014-11-19 10:53:20 +01001012 if (ntohs(hdr_v2->len) < PP2_ADDR_LEN_INET6)
1013 goto bad_header;
1014
Christopher Fauletc105c922021-10-25 08:17:11 +02001015 if (!sess || !sockaddr_alloc(&sess->src, NULL, 0) || !sockaddr_alloc(&sess->dst, NULL, 0))
1016 goto fail;
1017
1018 ((struct sockaddr_in6 *)sess->src)->sin6_family = AF_INET6;
1019 memcpy(&((struct sockaddr_in6 *)sess->src)->sin6_addr, hdr_v2->addr.ip6.src_addr, 16);
1020 ((struct sockaddr_in6 *)sess->src)->sin6_port = hdr_v2->addr.ip6.src_port;
1021 ((struct sockaddr_in6 *)sess->dst)->sin6_family = AF_INET6;
1022 memcpy(&((struct sockaddr_in6 *)sess->dst)->sin6_addr, hdr_v2->addr.ip6.dst_addr, 16);
1023 ((struct sockaddr_in6 *)sess->dst)->sin6_port = hdr_v2->addr.ip6.dst_port;
1024 sess->flags |= SESS_FL_ADDR_FROM_SET | SESS_FL_ADDR_TO_SET;
KOVACS Krisztian7209c202015-07-03 14:09:10 +02001025 tlv_offset = PP2_HEADER_LEN + PP2_ADDR_LEN_INET6;
Willy Tarreau77992672014-06-14 11:06:17 +02001026 break;
1027 }
KOVACS Krisztianb3e54fe2014-11-17 15:11:45 +01001028
1029 /* TLV parsing */
Tim Duesterhus488ee7f2020-03-05 22:55:20 +01001030 while (tlv_offset < total_v2_len) {
1031 struct tlv *tlv_packet;
Tim Duesterhus56c176a2021-03-06 20:06:51 +01001032 struct ist tlv;
KOVACS Krisztianb3e54fe2014-11-17 15:11:45 +01001033
Tim Duesterhus488ee7f2020-03-05 22:55:20 +01001034 /* Verify that we have at least TLV_HEADER_SIZE bytes left */
1035 if (tlv_offset + TLV_HEADER_SIZE > total_v2_len)
1036 goto bad_header;
1037
1038 tlv_packet = (struct tlv *) &trash.area[tlv_offset];
Tim Duesterhus56c176a2021-03-06 20:06:51 +01001039 tlv = ist2((const char *)tlv_packet->value, get_tlv_length(tlv_packet));
1040 tlv_offset += istlen(tlv) + TLV_HEADER_SIZE;
Tim Duesterhus488ee7f2020-03-05 22:55:20 +01001041
1042 /* Verify that the TLV length does not exceed the total PROXYv2 length */
1043 if (tlv_offset > total_v2_len)
1044 goto bad_header;
1045
1046 switch (tlv_packet->type) {
1047 case PP2_TYPE_CRC32C: {
1048 uint32_t n_crc32c;
1049
1050 /* Verify that this TLV is exactly 4 bytes long */
Tim Duesterhus56c176a2021-03-06 20:06:51 +01001051 if (istlen(tlv) != 4)
Tim Duesterhus488ee7f2020-03-05 22:55:20 +01001052 goto bad_header;
1053
Tim Duesterhus56c176a2021-03-06 20:06:51 +01001054 n_crc32c = read_n32(istptr(tlv));
1055 write_n32(istptr(tlv), 0); // compute with CRC==0
Tim Duesterhus488ee7f2020-03-05 22:55:20 +01001056
1057 if (hash_crc32c(trash.area, total_v2_len) != n_crc32c)
1058 goto bad_header;
1059 break;
1060 }
Willy Tarreaue5733232019-05-22 19:24:06 +02001061#ifdef USE_NS
Tim Duesterhus488ee7f2020-03-05 22:55:20 +01001062 case PP2_TYPE_NETNS: {
1063 const struct netns_entry *ns;
1064
Tim Duesterhus56c176a2021-03-06 20:06:51 +01001065 ns = netns_store_lookup(istptr(tlv), istlen(tlv));
Tim Duesterhus488ee7f2020-03-05 22:55:20 +01001066 if (ns)
1067 conn->proxy_netns = ns;
1068 break;
1069 }
KOVACS Krisztianb3e54fe2014-11-17 15:11:45 +01001070#endif
Tim Duesterhus488ee7f2020-03-05 22:55:20 +01001071 case PP2_TYPE_AUTHORITY: {
Tim Duesterhus615f81e2021-03-06 20:06:50 +01001072 if (istlen(tlv) > PP2_AUTHORITY_MAX)
Tim Duesterhus488ee7f2020-03-05 22:55:20 +01001073 goto bad_header;
Tim Duesterhus615f81e2021-03-06 20:06:50 +01001074 conn->proxy_authority = ist2(pool_alloc(pool_head_authority), 0);
1075 if (!isttest(conn->proxy_authority))
Tim Duesterhus488ee7f2020-03-05 22:55:20 +01001076 goto fail;
Tim Duesterhus615f81e2021-03-06 20:06:50 +01001077 if (istcpy(&conn->proxy_authority, tlv, PP2_AUTHORITY_MAX) < 0) {
Tim Duesterhusf09af572022-02-25 21:44:26 +01001078 /* This is impossible, because we verified that the TLV value fits. */
1079 my_unreachable();
Tim Duesterhus615f81e2021-03-06 20:06:50 +01001080 goto fail;
1081 }
Tim Duesterhus488ee7f2020-03-05 22:55:20 +01001082 break;
1083 }
Tim Duesterhusd1b15b62020-03-13 12:34:23 +01001084 case PP2_TYPE_UNIQUE_ID: {
Tim Duesterhus002bd772021-03-06 20:06:49 +01001085 if (istlen(tlv) > UNIQUEID_LEN)
Tim Duesterhusd1b15b62020-03-13 12:34:23 +01001086 goto bad_header;
Tim Duesterhus2b7f6c22020-03-14 13:07:05 +01001087 conn->proxy_unique_id = ist2(pool_alloc(pool_head_uniqueid), 0);
Tim Duesterhusd1b15b62020-03-13 12:34:23 +01001088 if (!isttest(conn->proxy_unique_id))
1089 goto fail;
1090 if (istcpy(&conn->proxy_unique_id, tlv, UNIQUEID_LEN) < 0) {
Tim Duesterhusf09af572022-02-25 21:44:26 +01001091 /* This is impossible, because we verified that the TLV value fits. */
1092 my_unreachable();
Tim Duesterhusd1b15b62020-03-13 12:34:23 +01001093 goto fail;
1094 }
1095 break;
1096 }
Tim Duesterhus488ee7f2020-03-05 22:55:20 +01001097 default:
1098 break;
KOVACS Krisztianb3e54fe2014-11-17 15:11:45 +01001099 }
1100 }
1101
Tim Duesterhus488ee7f2020-03-05 22:55:20 +01001102 /* Verify that the PROXYv2 header ends at a TLV boundary.
Tim Duesterhus17e6b732022-02-25 21:44:27 +01001103 * This is can not be true, because the TLV parsing already
1104 * verifies that a TLV does not exceed the total length and
1105 * also that there is space for a TLV header.
Tim Duesterhus488ee7f2020-03-05 22:55:20 +01001106 */
Tim Duesterhus17e6b732022-02-25 21:44:27 +01001107 BUG_ON(tlv_offset != total_v2_len);
Tim Duesterhus488ee7f2020-03-05 22:55:20 +01001108
Willy Tarreau77992672014-06-14 11:06:17 +02001109 /* unsupported protocol, keep local connection address */
1110 break;
1111 case 0x00: /* LOCAL command */
1112 /* keep local connection address for LOCAL */
1113 break;
1114 default:
1115 goto bad_header; /* not a supported command */
1116 }
1117
Tim Duesterhus488ee7f2020-03-05 22:55:20 +01001118 trash.data = total_v2_len;
Willy Tarreau77992672014-06-14 11:06:17 +02001119 goto eat_header;
1120
1121 eat_header:
Willy Tarreaue1e4a612012-10-05 00:10:55 +02001122 /* remove the PROXY line from the request. For this we re-read the
1123 * exact line at once. If we don't get the exact same result, we
1124 * fail.
1125 */
Willy Tarreau157788c2020-02-11 10:08:05 +01001126 while (1) {
Tim Duesterhusa8692f32020-03-13 12:34:25 +01001127 ssize_t len2 = recv(conn->handle.fd, trash.area, trash.data, 0);
1128
Willy Tarreaue1e4a612012-10-05 00:10:55 +02001129 if (len2 < 0 && errno == EINTR)
1130 continue;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001131 if (len2 != trash.data)
Willy Tarreau8e3bf692012-12-03 15:41:18 +01001132 goto recv_abort;
Willy Tarreau157788c2020-02-11 10:08:05 +01001133 break;
1134 }
Willy Tarreaue1e4a612012-10-05 00:10:55 +02001135
1136 conn->flags &= ~flag;
Emeric Brun4f603012017-01-05 15:11:44 +01001137 conn->flags |= CO_FL_RCVD_PROXY;
Willy Tarreaue1e4a612012-10-05 00:10:55 +02001138 return 1;
1139
Willy Tarreau6499b9d2019-06-03 08:17:30 +02001140 not_ready:
Willy Tarreau6499b9d2019-06-03 08:17:30 +02001141 return 0;
1142
Willy Tarreaue1e4a612012-10-05 00:10:55 +02001143 missing:
1144 /* Missing data. Since we're using MSG_PEEK, we can only poll again if
1145 * we have not read anything. Otherwise we need to fail because we won't
1146 * be able to poll anymore.
1147 */
Willy Tarreau8e3bf692012-12-03 15:41:18 +01001148 conn->err_code = CO_ER_PRX_TRUNCATED;
1149 goto fail;
1150
1151 bad_header:
1152 /* This is not a valid proxy protocol header */
1153 conn->err_code = CO_ER_PRX_BAD_HDR;
1154 goto fail;
1155
1156 recv_abort:
1157 conn->err_code = CO_ER_PRX_ABORT;
Willy Tarreau26f4a042013-12-04 23:44:10 +01001158 conn->flags |= CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH;
Willy Tarreau8e3bf692012-12-03 15:41:18 +01001159 goto fail;
1160
Willy Tarreaue1e4a612012-10-05 00:10:55 +02001161 fail:
Willy Tarreaue1e4a612012-10-05 00:10:55 +02001162 conn->flags |= CO_FL_ERROR;
Willy Tarreaue1e4a612012-10-05 00:10:55 +02001163 return 0;
1164}
1165
Christopher Fauletaa91d622022-04-01 13:22:50 +02001166/* This callback is used to send a valid PROXY protocol line to a socket being
1167 * established. It returns 0 if it fails in a fatal way or needs to poll to go
1168 * further, otherwise it returns non-zero and removes itself from the connection's
1169 * flags (the bit is provided in <flag> by the caller). It is designed to be
1170 * called by the connection handler and relies on it to commit polling changes.
1171 * Note that it can emit a PROXY line by relying on the other end's address
1172 * when the connection is attached to a stream interface, or by resolving the
1173 * local address otherwise (also called a LOCAL line).
1174 */
1175int conn_send_proxy(struct connection *conn, unsigned int flag)
1176{
1177 if (!conn_ctrl_ready(conn))
1178 goto out_error;
1179
1180 /* If we have a PROXY line to send, we'll use this to validate the
1181 * connection, in which case the connection is validated only once
1182 * we've sent the whole proxy line. Otherwise we use connect().
1183 */
1184 if (conn->send_proxy_ofs) {
1185 struct conn_stream *cs;
1186 int ret;
1187
1188 /* If there is no mux attached to the connection, it means the
1189 * connection context is a conn-stream.
1190 */
1191 cs = (conn->mux ? cs_conn_get_first(conn) : conn->ctx);
1192
1193 /* The target server expects a PROXY line to be sent first.
1194 * If the send_proxy_ofs is negative, it corresponds to the
1195 * offset to start sending from then end of the proxy string
1196 * (which is recomputed every time since it's constant). If
1197 * it is positive, it means we have to send from the start.
1198 * We can only send a "normal" PROXY line when the connection
1199 * is attached to a stream interface. Otherwise we can only
1200 * send a LOCAL line (eg: for use with health checks).
1201 */
1202
1203 if (cs && cs_strm(cs)) {
1204 ret = make_proxy_line(trash.area, trash.size,
1205 objt_server(conn->target),
1206 cs_conn(cs_opposite(cs)),
1207 __cs_strm(cs));
1208 }
1209 else {
1210 /* The target server expects a LOCAL line to be sent first. Retrieving
1211 * local or remote addresses may fail until the connection is established.
1212 */
1213 if (!conn_get_src(conn) || !conn_get_dst(conn))
1214 goto out_wait;
1215
1216 ret = make_proxy_line(trash.area, trash.size,
1217 objt_server(conn->target), conn,
1218 NULL);
1219 }
1220
1221 if (!ret)
1222 goto out_error;
1223
1224 if (conn->send_proxy_ofs > 0)
1225 conn->send_proxy_ofs = -ret; /* first call */
1226
1227 /* we have to send trash from (ret+sp for -sp bytes). If the
1228 * data layer has a pending write, we'll also set MSG_MORE.
1229 */
1230 ret = conn_ctrl_send(conn,
1231 trash.area + ret + conn->send_proxy_ofs,
1232 -conn->send_proxy_ofs,
1233 (conn->subs && conn->subs->events & SUB_RETRY_SEND) ? CO_SFL_MSG_MORE : 0);
1234
1235 if (ret < 0)
1236 goto out_error;
1237
1238 conn->send_proxy_ofs += ret; /* becomes zero once complete */
1239 if (conn->send_proxy_ofs != 0)
1240 goto out_wait;
1241
1242 /* OK we've sent the whole line, we're connected */
1243 }
1244
1245 /* The connection is ready now, simply return and let the connection
1246 * handler notify upper layers if needed.
1247 */
1248 conn->flags &= ~CO_FL_WAIT_L4_CONN;
1249 conn->flags &= ~flag;
1250 return 1;
1251
1252 out_error:
1253 /* Write error on the file descriptor */
1254 conn->flags |= CO_FL_ERROR;
1255 return 0;
1256
1257 out_wait:
1258 return 0;
1259}
1260
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001261/* This handshake handler waits a NetScaler Client IP insertion header
Bertrand Jacquin72fa1ec2017-12-12 01:17:23 +00001262 * at the beginning of the raw data stream. The header format is
1263 * described in doc/netscaler-client-ip-insertion-protocol.txt
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001264 *
1265 * This line MUST be at the beginning of the buffer and MUST NOT be
1266 * fragmented.
1267 *
1268 * The header line is small and in all cases smaller than the smallest normal
1269 * TCP MSS. So it MUST always be delivered as one segment, which ensures we
1270 * can safely use MSG_PEEK and avoid buffering.
1271 *
1272 * Once the data is fetched, the values are set in the connection's address
1273 * fields, and data are removed from the socket's buffer. The function returns
1274 * zero if it needs to wait for more data or if it fails, or 1 if it completed
1275 * and removed itself.
1276 */
1277int conn_recv_netscaler_cip(struct connection *conn, int flag)
1278{
Christopher Faulete83e8822021-10-25 08:23:22 +02001279 struct session *sess = conn->owner;
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001280 char *line;
Bertrand Jacquin7d668f92017-12-13 01:23:39 +00001281 uint32_t hdr_len;
Willy Tarreau0ca24aa2019-03-29 17:35:32 +01001282 uint8_t ip_ver;
Willy Tarreaub406b872018-08-22 05:20:32 +02001283 int ret;
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001284
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001285 if (!conn_ctrl_ready(conn))
1286 goto fail;
1287
Willy Tarreau07ecfc52022-04-11 18:07:03 +02001288 BUG_ON(conn->flags & CO_FL_FDLESS);
1289
Willy Tarreau585744b2017-08-24 14:31:19 +02001290 if (!fd_recv_ready(conn->handle.fd))
Willy Tarreau6499b9d2019-06-03 08:17:30 +02001291 goto not_ready;
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001292
Willy Tarreau157788c2020-02-11 10:08:05 +01001293 while (1) {
Willy Tarreaub406b872018-08-22 05:20:32 +02001294 ret = recv(conn->handle.fd, trash.area, trash.size, MSG_PEEK);
1295 if (ret < 0) {
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001296 if (errno == EINTR)
1297 continue;
1298 if (errno == EAGAIN) {
Willy Tarreau585744b2017-08-24 14:31:19 +02001299 fd_cant_recv(conn->handle.fd);
Willy Tarreau6499b9d2019-06-03 08:17:30 +02001300 goto not_ready;
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001301 }
1302 goto recv_abort;
1303 }
Willy Tarreaub406b872018-08-22 05:20:32 +02001304 trash.data = ret;
Willy Tarreau157788c2020-02-11 10:08:05 +01001305 break;
1306 }
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001307
Willy Tarreauc192b0a2020-01-23 09:11:58 +01001308 conn->flags &= ~CO_FL_WAIT_L4_CONN;
1309
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001310 if (!trash.data) {
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001311 /* client shutdown */
1312 conn->err_code = CO_ER_CIP_EMPTY;
1313 goto fail;
1314 }
1315
1316 /* Fail if buffer length is not large enough to contain
Bertrand Jacquin72fa1ec2017-12-12 01:17:23 +00001317 * CIP magic, header length or
1318 * CIP magic, CIP length, CIP type, header length */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001319 if (trash.data < 12)
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001320 goto missing;
1321
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001322 line = trash.area;
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001323
1324 /* Decode a possible NetScaler Client IP request, fail early if
1325 * it does not match */
Willy Tarreau1ac83af2020-02-25 10:06:49 +01001326 if (ntohl(read_u32(line)) != __objt_listener(conn->target)->bind_conf->ns_cip_magic)
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001327 goto bad_magic;
1328
Bertrand Jacquin72fa1ec2017-12-12 01:17:23 +00001329 /* Legacy CIP protocol */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001330 if ((trash.area[8] & 0xD0) == 0x40) {
Willy Tarreau1ac83af2020-02-25 10:06:49 +01001331 hdr_len = ntohl(read_u32((line+4)));
Bertrand Jacquin72fa1ec2017-12-12 01:17:23 +00001332 line += 8;
1333 }
1334 /* Standard CIP protocol */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001335 else if (trash.area[8] == 0x00) {
Willy Tarreau1ac83af2020-02-25 10:06:49 +01001336 hdr_len = ntohs(read_u32((line+10)));
Bertrand Jacquin72fa1ec2017-12-12 01:17:23 +00001337 line += 12;
1338 }
1339 /* Unknown CIP protocol */
1340 else {
1341 conn->err_code = CO_ER_CIP_BAD_PROTO;
1342 goto fail;
1343 }
1344
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001345 /* Fail if buffer length is not large enough to contain
Bertrand Jacquin72fa1ec2017-12-12 01:17:23 +00001346 * a minimal IP header */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001347 if (trash.data < 20)
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001348 goto missing;
1349
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001350 /* Get IP version from the first four bits */
Willy Tarreau0ca24aa2019-03-29 17:35:32 +01001351 ip_ver = (*line & 0xf0) >> 4;
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001352
Willy Tarreau0ca24aa2019-03-29 17:35:32 +01001353 if (ip_ver == 4) {
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001354 struct ip *hdr_ip4;
David Carlier3015a2e2016-07-04 22:51:33 +01001355 struct my_tcphdr *hdr_tcp;
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001356
1357 hdr_ip4 = (struct ip *)line;
1358
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001359 if (trash.data < 40 || trash.data < hdr_len) {
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001360 /* Fail if buffer length is not large enough to contain
Bertrand Jacquin67de5a22017-12-13 01:15:05 +00001361 * IPv4 header, TCP header */
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001362 goto missing;
Bertrand Jacquinb3875912017-12-13 00:58:51 +00001363 }
1364 else if (hdr_ip4->ip_p != IPPROTO_TCP) {
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001365 /* The protocol does not include a TCP header */
1366 conn->err_code = CO_ER_CIP_BAD_PROTO;
1367 goto fail;
Bertrand Jacquinb3875912017-12-13 00:58:51 +00001368 }
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001369
David Carlier3015a2e2016-07-04 22:51:33 +01001370 hdr_tcp = (struct my_tcphdr *)(line + (hdr_ip4->ip_hl * 4));
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001371
Christopher Faulete83e8822021-10-25 08:23:22 +02001372 if (!sess || !sockaddr_alloc(&sess->src, NULL, 0) || !sockaddr_alloc(&sess->dst, NULL, 0))
1373 goto fail;
1374
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001375 /* update the session's addresses and mark them set */
Christopher Faulete83e8822021-10-25 08:23:22 +02001376 ((struct sockaddr_in *)sess->src)->sin_family = AF_INET;
1377 ((struct sockaddr_in *)sess->src)->sin_addr.s_addr = hdr_ip4->ip_src.s_addr;
1378 ((struct sockaddr_in *)sess->src)->sin_port = hdr_tcp->source;
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001379
Christopher Faulete83e8822021-10-25 08:23:22 +02001380 ((struct sockaddr_in *)sess->dst)->sin_family = AF_INET;
1381 ((struct sockaddr_in *)sess->dst)->sin_addr.s_addr = hdr_ip4->ip_dst.s_addr;
1382 ((struct sockaddr_in *)sess->dst)->sin_port = hdr_tcp->dest;
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001383
Christopher Faulete83e8822021-10-25 08:23:22 +02001384 sess->flags |= SESS_FL_ADDR_FROM_SET | SESS_FL_ADDR_TO_SET;
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001385 }
Willy Tarreau0ca24aa2019-03-29 17:35:32 +01001386 else if (ip_ver == 6) {
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001387 struct ip6_hdr *hdr_ip6;
David Carlier3015a2e2016-07-04 22:51:33 +01001388 struct my_tcphdr *hdr_tcp;
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001389
1390 hdr_ip6 = (struct ip6_hdr *)line;
1391
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001392 if (trash.data < 60 || trash.data < hdr_len) {
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001393 /* Fail if buffer length is not large enough to contain
Bertrand Jacquin67de5a22017-12-13 01:15:05 +00001394 * IPv6 header, TCP header */
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001395 goto missing;
Bertrand Jacquinb3875912017-12-13 00:58:51 +00001396 }
1397 else if (hdr_ip6->ip6_nxt != IPPROTO_TCP) {
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001398 /* The protocol does not include a TCP header */
1399 conn->err_code = CO_ER_CIP_BAD_PROTO;
1400 goto fail;
Bertrand Jacquinb3875912017-12-13 00:58:51 +00001401 }
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001402
David Carlier3015a2e2016-07-04 22:51:33 +01001403 hdr_tcp = (struct my_tcphdr *)(line + sizeof(struct ip6_hdr));
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001404
Christopher Faulete83e8822021-10-25 08:23:22 +02001405 if (!sess || !sockaddr_alloc(&sess->src, NULL, 0) || !sockaddr_alloc(&sess->dst, NULL, 0))
1406 goto fail;
1407
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001408 /* update the session's addresses and mark them set */
Christopher Faulete83e8822021-10-25 08:23:22 +02001409 ((struct sockaddr_in6 *)sess->src)->sin6_family = AF_INET6;
1410 ((struct sockaddr_in6 *)sess->src)->sin6_addr = hdr_ip6->ip6_src;
1411 ((struct sockaddr_in6 *)sess->src)->sin6_port = hdr_tcp->source;
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001412
Christopher Faulete83e8822021-10-25 08:23:22 +02001413 ((struct sockaddr_in6 *)sess->dst)->sin6_family = AF_INET6;
1414 ((struct sockaddr_in6 *)sess->dst)->sin6_addr = hdr_ip6->ip6_dst;
1415 ((struct sockaddr_in6 *)sess->dst)->sin6_port = hdr_tcp->dest;
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001416
Christopher Faulete83e8822021-10-25 08:23:22 +02001417 sess->flags |= SESS_FL_ADDR_FROM_SET | SESS_FL_ADDR_TO_SET;
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001418 }
1419 else {
1420 /* The protocol does not match something known (IPv4/IPv6) */
1421 conn->err_code = CO_ER_CIP_BAD_PROTO;
1422 goto fail;
1423 }
1424
Bertrand Jacquin7d668f92017-12-13 01:23:39 +00001425 line += hdr_len;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001426 trash.data = line - trash.area;
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001427
1428 /* remove the NetScaler Client IP header from the request. For this
1429 * we re-read the exact line at once. If we don't get the exact same
1430 * result, we fail.
1431 */
Willy Tarreau157788c2020-02-11 10:08:05 +01001432 while (1) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001433 int len2 = recv(conn->handle.fd, trash.area, trash.data, 0);
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001434 if (len2 < 0 && errno == EINTR)
1435 continue;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001436 if (len2 != trash.data)
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001437 goto recv_abort;
Willy Tarreau157788c2020-02-11 10:08:05 +01001438 break;
1439 }
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001440
1441 conn->flags &= ~flag;
1442 return 1;
1443
Willy Tarreau6499b9d2019-06-03 08:17:30 +02001444 not_ready:
Willy Tarreau6499b9d2019-06-03 08:17:30 +02001445 return 0;
1446
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001447 missing:
1448 /* Missing data. Since we're using MSG_PEEK, we can only poll again if
1449 * we have not read anything. Otherwise we need to fail because we won't
1450 * be able to poll anymore.
1451 */
1452 conn->err_code = CO_ER_CIP_TRUNCATED;
1453 goto fail;
1454
1455 bad_magic:
1456 conn->err_code = CO_ER_CIP_BAD_MAGIC;
1457 goto fail;
1458
1459 recv_abort:
1460 conn->err_code = CO_ER_CIP_ABORT;
1461 conn->flags |= CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH;
1462 goto fail;
1463
1464 fail:
Bertrand Jacquin93b227d2016-06-04 15:11:10 +01001465 conn->flags |= CO_FL_ERROR;
1466 return 0;
1467}
1468
Alexander Liu2a54bb72019-05-22 19:44:48 +08001469
1470int conn_send_socks4_proxy_request(struct connection *conn)
1471{
1472 struct socks4_request req_line;
1473
Alexander Liu2a54bb72019-05-22 19:44:48 +08001474 if (!conn_ctrl_ready(conn))
1475 goto out_error;
1476
Willy Tarreau226572f2019-07-17 14:46:00 +02001477 if (!conn_get_dst(conn))
1478 goto out_error;
1479
Alexander Liu2a54bb72019-05-22 19:44:48 +08001480 req_line.version = 0x04;
1481 req_line.command = 0x01;
Willy Tarreau226572f2019-07-17 14:46:00 +02001482 req_line.port = get_net_port(conn->dst);
1483 req_line.ip = is_inet_addr(conn->dst);
Alexander Liu2a54bb72019-05-22 19:44:48 +08001484 memcpy(req_line.user_id, "HAProxy\0", 8);
1485
1486 if (conn->send_proxy_ofs > 0) {
1487 /*
1488 * This is the first call to send the request
1489 */
1490 conn->send_proxy_ofs = -(int)sizeof(req_line);
1491 }
1492
1493 if (conn->send_proxy_ofs < 0) {
1494 int ret = 0;
1495
1496 /* we are sending the socks4_req_line here. If the data layer
1497 * has a pending write, we'll also set MSG_MORE.
1498 */
Willy Tarreau827fee72020-12-11 15:26:55 +01001499 ret = conn_ctrl_send(
Alexander Liu2a54bb72019-05-22 19:44:48 +08001500 conn,
1501 ((char *)(&req_line)) + (sizeof(req_line)+conn->send_proxy_ofs),
1502 -conn->send_proxy_ofs,
Willy Tarreau827fee72020-12-11 15:26:55 +01001503 (conn->subs && conn->subs->events & SUB_RETRY_SEND) ? CO_SFL_MSG_MORE : 0);
Alexander Liu2a54bb72019-05-22 19:44:48 +08001504
1505 DPRINTF(stderr, "SOCKS PROXY HS FD[%04X]: Before send remain is [%d], sent [%d]\n",
Willy Tarreau0e9c2642022-04-11 18:01:28 +02001506 conn_fd(conn), -conn->send_proxy_ofs, ret);
Alexander Liu2a54bb72019-05-22 19:44:48 +08001507
1508 if (ret < 0) {
1509 goto out_error;
1510 }
1511
1512 conn->send_proxy_ofs += ret; /* becomes zero once complete */
1513 if (conn->send_proxy_ofs != 0) {
1514 goto out_wait;
1515 }
1516 }
1517
1518 /* OK we've the whole request sent */
1519 conn->flags &= ~CO_FL_SOCKS4_SEND;
Alexander Liu2a54bb72019-05-22 19:44:48 +08001520
1521 /* The connection is ready now, simply return and let the connection
1522 * handler notify upper layers if needed.
1523 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01001524 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Alexander Liu2a54bb72019-05-22 19:44:48 +08001525
1526 if (conn->flags & CO_FL_SEND_PROXY) {
1527 /*
1528 * Get the send_proxy_ofs ready for the send_proxy due to we are
1529 * reusing the "send_proxy_ofs", and SOCKS4 handshake should be done
1530 * before sending PROXY Protocol.
1531 */
1532 conn->send_proxy_ofs = 1;
1533 }
1534 return 1;
1535
1536 out_error:
1537 /* Write error on the file descriptor */
1538 conn->flags |= CO_FL_ERROR;
1539 if (conn->err_code == CO_ER_NONE) {
1540 conn->err_code = CO_ER_SOCKS4_SEND;
1541 }
1542 return 0;
1543
1544 out_wait:
Alexander Liu2a54bb72019-05-22 19:44:48 +08001545 return 0;
1546}
1547
1548int conn_recv_socks4_proxy_response(struct connection *conn)
1549{
1550 char line[SOCKS4_HS_RSP_LEN];
1551 int ret;
1552
Alexander Liu2a54bb72019-05-22 19:44:48 +08001553 if (!conn_ctrl_ready(conn))
1554 goto fail;
1555
Willy Tarreau07ecfc52022-04-11 18:07:03 +02001556 BUG_ON(conn->flags & CO_FL_FDLESS);
1557
Alexander Liu2a54bb72019-05-22 19:44:48 +08001558 if (!fd_recv_ready(conn->handle.fd))
Willy Tarreau6499b9d2019-06-03 08:17:30 +02001559 goto not_ready;
Alexander Liu2a54bb72019-05-22 19:44:48 +08001560
Willy Tarreau157788c2020-02-11 10:08:05 +01001561 while (1) {
Alexander Liu2a54bb72019-05-22 19:44:48 +08001562 /* SOCKS4 Proxy will response with 8 bytes, 0x00 | 0x5A | 0x00 0x00 | 0x00 0x00 0x00 0x00
1563 * Try to peek into it, before all 8 bytes ready.
1564 */
1565 ret = recv(conn->handle.fd, line, SOCKS4_HS_RSP_LEN, MSG_PEEK);
1566
1567 if (ret == 0) {
1568 /* the socket has been closed or shutdown for send */
1569 DPRINTF(stderr, "SOCKS PROXY HS FD[%04X]: Received ret[%d], errno[%d], looks like the socket has been closed or shutdown for send\n",
1570 conn->handle.fd, ret, errno);
1571 if (conn->err_code == CO_ER_NONE) {
1572 conn->err_code = CO_ER_SOCKS4_RECV;
1573 }
1574 goto fail;
1575 }
1576
1577 if (ret > 0) {
1578 if (ret == SOCKS4_HS_RSP_LEN) {
1579 DPRINTF(stderr, "SOCKS PROXY HS FD[%04X]: Received 8 bytes, the response is [%02X|%02X|%02X %02X|%02X %02X %02X %02X]\n",
1580 conn->handle.fd, line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7]);
1581 }else{
1582 DPRINTF(stderr, "SOCKS PROXY HS FD[%04X]: Received ret[%d], first byte is [%02X], last bye is [%02X]\n", conn->handle.fd, ret, line[0], line[ret-1]);
1583 }
1584 } else {
1585 DPRINTF(stderr, "SOCKS PROXY HS FD[%04X]: Received ret[%d], errno[%d]\n", conn->handle.fd, ret, errno);
1586 }
1587
1588 if (ret < 0) {
1589 if (errno == EINTR) {
1590 continue;
1591 }
1592 if (errno == EAGAIN) {
1593 fd_cant_recv(conn->handle.fd);
Willy Tarreau6499b9d2019-06-03 08:17:30 +02001594 goto not_ready;
Alexander Liu2a54bb72019-05-22 19:44:48 +08001595 }
1596 goto recv_abort;
1597 }
Willy Tarreau157788c2020-02-11 10:08:05 +01001598 break;
1599 }
Alexander Liu2a54bb72019-05-22 19:44:48 +08001600
Willy Tarreauc192b0a2020-01-23 09:11:58 +01001601 conn->flags &= ~CO_FL_WAIT_L4_CONN;
1602
Alexander Liu2a54bb72019-05-22 19:44:48 +08001603 if (ret < SOCKS4_HS_RSP_LEN) {
1604 /* Missing data. Since we're using MSG_PEEK, we can only poll again if
1605 * we are not able to read enough data.
1606 */
Willy Tarreau6499b9d2019-06-03 08:17:30 +02001607 goto not_ready;
Alexander Liu2a54bb72019-05-22 19:44:48 +08001608 }
1609
1610 /*
1611 * Base on the SOCSK4 protocol:
1612 *
1613 * +----+----+----+----+----+----+----+----+
1614 * | VN | CD | DSTPORT | DSTIP |
1615 * +----+----+----+----+----+----+----+----+
1616 * # of bytes: 1 1 2 4
1617 * VN is the version of the reply code and should be 0. CD is the result
1618 * code with one of the following values:
1619 * 90: request granted
1620 * 91: request rejected or failed
Ilya Shipitsince7b00f2020-03-23 22:28:40 +05001621 * 92: request rejected because SOCKS server cannot connect to identd on the client
Alexander Liu2a54bb72019-05-22 19:44:48 +08001622 * 93: request rejected because the client program and identd report different user-ids
1623 * The remaining fields are ignored.
1624 */
1625 if (line[1] != 90) {
1626 conn->flags &= ~CO_FL_SOCKS4_RECV;
1627
1628 DPRINTF(stderr, "SOCKS PROXY HS FD[%04X]: FAIL, the response is [%02X|%02X|%02X %02X|%02X %02X %02X %02X]\n",
1629 conn->handle.fd, line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7]);
1630 if (conn->err_code == CO_ER_NONE) {
1631 conn->err_code = CO_ER_SOCKS4_DENY;
1632 }
1633 goto fail;
1634 }
1635
1636 /* remove the 8 bytes response from the stream */
Willy Tarreau157788c2020-02-11 10:08:05 +01001637 while (1) {
Alexander Liu2a54bb72019-05-22 19:44:48 +08001638 ret = recv(conn->handle.fd, line, SOCKS4_HS_RSP_LEN, 0);
1639 if (ret < 0 && errno == EINTR) {
1640 continue;
1641 }
1642 if (ret != SOCKS4_HS_RSP_LEN) {
1643 if (conn->err_code == CO_ER_NONE) {
1644 conn->err_code = CO_ER_SOCKS4_RECV;
1645 }
1646 goto fail;
1647 }
Willy Tarreau157788c2020-02-11 10:08:05 +01001648 break;
1649 }
Alexander Liu2a54bb72019-05-22 19:44:48 +08001650
1651 conn->flags &= ~CO_FL_SOCKS4_RECV;
1652 return 1;
1653
Willy Tarreau6499b9d2019-06-03 08:17:30 +02001654 not_ready:
Willy Tarreau6499b9d2019-06-03 08:17:30 +02001655 return 0;
1656
Alexander Liu2a54bb72019-05-22 19:44:48 +08001657 recv_abort:
1658 if (conn->err_code == CO_ER_NONE) {
1659 conn->err_code = CO_ER_SOCKS4_ABORT;
1660 }
1661 conn->flags |= (CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH);
1662 goto fail;
1663
1664 fail:
Alexander Liu2a54bb72019-05-22 19:44:48 +08001665 conn->flags |= CO_FL_ERROR;
1666 return 0;
1667}
1668
Willy Tarreaud318e4e2022-03-02 14:46:45 +01001669/* registers proto mux list <list>. Modifies the list element! */
1670void register_mux_proto(struct mux_proto_list *list)
1671{
1672 LIST_APPEND(&mux_proto_list.list, &list->list);
1673}
1674
Willy Tarreauadd43062022-02-18 11:07:40 +01001675/* Lists the known proto mux on <out>. This function is used by "haproxy -vv"
1676 * and is suitable for early boot just after the "REGISTER" stage because it
1677 * doesn't depend on anything to be already allocated.
1678 */
Willy Tarreaue59b5162021-05-08 14:06:09 +02001679void list_mux_proto(FILE *out)
1680{
1681 struct mux_proto_list *item;
Willy Tarreaue59b5162021-05-08 14:06:09 +02001682 struct ist proto;
1683 char *mode, *side;
Willy Tarreauadd43062022-02-18 11:07:40 +01001684 int done;
Willy Tarreaue59b5162021-05-08 14:06:09 +02001685
1686 fprintf(out, "Available multiplexer protocols :\n"
1687 "(protocols marked as <default> cannot be specified using 'proto' keyword)\n");
1688 list_for_each_entry(item, &mux_proto_list.list, list) {
1689 proto = item->token;
1690
1691 if (item->mode == PROTO_MODE_ANY)
1692 mode = "TCP|HTTP";
1693 else if (item->mode == PROTO_MODE_TCP)
1694 mode = "TCP";
1695 else if (item->mode == PROTO_MODE_HTTP)
1696 mode = "HTTP";
1697 else
1698 mode = "NONE";
1699
1700 if (item->side == PROTO_SIDE_BOTH)
1701 side = "FE|BE";
1702 else if (item->side == PROTO_SIDE_FE)
1703 side = "FE";
1704 else if (item->side == PROTO_SIDE_BE)
1705 side = "BE";
1706 else
1707 side = "NONE";
1708
Willy Tarreaudddfec52022-04-09 11:37:35 +02001709 fprintf(out, " %10s : mode=%-5s side=%-6s mux=%-5s flags=",
Willy Tarreauadd43062022-02-18 11:07:40 +01001710 (proto.len ? proto.ptr : "<default>"), mode, side, item->mux->name);
1711
1712 done = 0;
1713
1714 /* note: the block below could be simplied using macros but for only
1715 * 4 flags it's not worth it.
1716 */
Willy Tarreaue59b5162021-05-08 14:06:09 +02001717 if (item->mux->flags & MX_FL_HTX)
Willy Tarreauadd43062022-02-18 11:07:40 +01001718 done |= fprintf(out, "%sHTX", done ? "|" : "");
1719
Willy Tarreaue59b5162021-05-08 14:06:09 +02001720 if (item->mux->flags & MX_FL_CLEAN_ABRT)
Willy Tarreauadd43062022-02-18 11:07:40 +01001721 done |= fprintf(out, "%sCLEAN_ABRT", done ? "|" : "");
1722
Willy Tarreaue59b5162021-05-08 14:06:09 +02001723 if (item->mux->flags & MX_FL_HOL_RISK)
Willy Tarreauadd43062022-02-18 11:07:40 +01001724 done |= fprintf(out, "%sHOL_RISK", done ? "|" : "");
1725
Willy Tarreaue59b5162021-05-08 14:06:09 +02001726 if (item->mux->flags & MX_FL_NO_UPG)
Willy Tarreauadd43062022-02-18 11:07:40 +01001727 done |= fprintf(out, "%sNO_UPG", done ? "|" : "");
Willy Tarreaue59b5162021-05-08 14:06:09 +02001728
Willy Tarreauadd43062022-02-18 11:07:40 +01001729 fprintf(out, "\n");
Willy Tarreaue59b5162021-05-08 14:06:09 +02001730 }
1731}
1732
Willy Tarreaue1e4a612012-10-05 00:10:55 +02001733/* Makes a PROXY protocol line from the two addresses. The output is sent to
1734 * buffer <buf> for a maximum size of <buf_len> (including the trailing zero).
1735 * It returns the number of bytes composing this line (including the trailing
1736 * LF), or zero in case of failure (eg: not enough space). It supports TCP4,
Willy Tarreau2e1401a2013-10-01 11:41:55 +02001737 * TCP6 and "UNKNOWN" formats. If any of <src> or <dst> is null, UNKNOWN is
1738 * emitted as well.
Willy Tarreaue1e4a612012-10-05 00:10:55 +02001739 */
Christopher Fauletb097aef2021-10-25 08:05:28 +02001740static int make_proxy_line_v1(char *buf, int buf_len, const struct sockaddr_storage *src, const struct sockaddr_storage *dst)
Willy Tarreaue1e4a612012-10-05 00:10:55 +02001741{
1742 int ret = 0;
Tim Duesterhus7fec0212018-07-27 18:46:13 +02001743 char * protocol;
1744 char src_str[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN)];
1745 char dst_str[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN)];
1746 in_port_t src_port;
1747 in_port_t dst_port;
Willy Tarreaue1e4a612012-10-05 00:10:55 +02001748
Tim Duesterhus7fec0212018-07-27 18:46:13 +02001749 if ( !src
1750 || !dst
1751 || (src->ss_family != AF_INET && src->ss_family != AF_INET6)
1752 || (dst->ss_family != AF_INET && dst->ss_family != AF_INET6)) {
1753 /* unknown family combination */
1754 ret = snprintf(buf, buf_len, "PROXY UNKNOWN\r\n");
Willy Tarreaue1e4a612012-10-05 00:10:55 +02001755 if (ret >= buf_len)
1756 return 0;
1757
Tim Duesterhus7fec0212018-07-27 18:46:13 +02001758 return ret;
1759 }
Willy Tarreaue1e4a612012-10-05 00:10:55 +02001760
Tim Duesterhus7fec0212018-07-27 18:46:13 +02001761 /* IPv4 for both src and dst */
1762 if (src->ss_family == AF_INET && dst->ss_family == AF_INET) {
1763 protocol = "TCP4";
1764 if (!inet_ntop(AF_INET, &((struct sockaddr_in *)src)->sin_addr, src_str, sizeof(src_str)))
Willy Tarreaue1e4a612012-10-05 00:10:55 +02001765 return 0;
Tim Duesterhus7fec0212018-07-27 18:46:13 +02001766 src_port = ((struct sockaddr_in *)src)->sin_port;
1767 if (!inet_ntop(AF_INET, &((struct sockaddr_in *)dst)->sin_addr, dst_str, sizeof(dst_str)))
Willy Tarreaue1e4a612012-10-05 00:10:55 +02001768 return 0;
Tim Duesterhus7fec0212018-07-27 18:46:13 +02001769 dst_port = ((struct sockaddr_in *)dst)->sin_port;
Willy Tarreaue1e4a612012-10-05 00:10:55 +02001770 }
Tim Duesterhus7fec0212018-07-27 18:46:13 +02001771 /* IPv6 for at least one of src and dst */
1772 else {
1773 struct in6_addr tmp;
Willy Tarreaue1e4a612012-10-05 00:10:55 +02001774
Tim Duesterhus7fec0212018-07-27 18:46:13 +02001775 protocol = "TCP6";
Willy Tarreaue1e4a612012-10-05 00:10:55 +02001776
Tim Duesterhus7fec0212018-07-27 18:46:13 +02001777 if (src->ss_family == AF_INET) {
1778 /* Convert src to IPv6 */
1779 v4tov6(&tmp, &((struct sockaddr_in *)src)->sin_addr);
1780 src_port = ((struct sockaddr_in *)src)->sin_port;
1781 }
1782 else {
1783 tmp = ((struct sockaddr_in6 *)src)->sin6_addr;
1784 src_port = ((struct sockaddr_in6 *)src)->sin6_port;
1785 }
Willy Tarreaue1e4a612012-10-05 00:10:55 +02001786
Tim Duesterhus7fec0212018-07-27 18:46:13 +02001787 if (!inet_ntop(AF_INET6, &tmp, src_str, sizeof(src_str)))
Willy Tarreaue1e4a612012-10-05 00:10:55 +02001788 return 0;
1789
Tim Duesterhus7fec0212018-07-27 18:46:13 +02001790 if (dst->ss_family == AF_INET) {
1791 /* Convert dst to IPv6 */
1792 v4tov6(&tmp, &((struct sockaddr_in *)dst)->sin_addr);
1793 dst_port = ((struct sockaddr_in *)dst)->sin_port;
1794 }
1795 else {
1796 tmp = ((struct sockaddr_in6 *)dst)->sin6_addr;
1797 dst_port = ((struct sockaddr_in6 *)dst)->sin6_port;
1798 }
Willy Tarreaue1e4a612012-10-05 00:10:55 +02001799
Tim Duesterhus7fec0212018-07-27 18:46:13 +02001800 if (!inet_ntop(AF_INET6, &tmp, dst_str, sizeof(dst_str)))
Willy Tarreaue1e4a612012-10-05 00:10:55 +02001801 return 0;
1802 }
Tim Duesterhus7fec0212018-07-27 18:46:13 +02001803
1804 ret = snprintf(buf, buf_len, "PROXY %s %s %s %u %u\r\n", protocol, src_str, dst_str, ntohs(src_port), ntohs(dst_port));
1805 if (ret >= buf_len)
1806 return 0;
1807
Willy Tarreaue1e4a612012-10-05 00:10:55 +02001808 return ret;
1809}
David Safb76832014-05-08 23:42:08 -04001810
KOVACS Krisztianb3e54fe2014-11-17 15:11:45 +01001811static int make_tlv(char *dest, int dest_len, char type, uint16_t length, const char *value)
David Safb76832014-05-08 23:42:08 -04001812{
1813 struct tlv *tlv;
1814
1815 if (!dest || (length + sizeof(*tlv) > dest_len))
1816 return 0;
1817
1818 tlv = (struct tlv *)dest;
1819
1820 tlv->type = type;
1821 tlv->length_hi = length >> 8;
1822 tlv->length_lo = length & 0x00ff;
1823 memcpy(tlv->value, value, length);
1824 return length + sizeof(*tlv);
1825}
David Safb76832014-05-08 23:42:08 -04001826
Ilya Shipitsinca56fce2018-09-15 00:50:05 +05001827/* Note: <remote> is explicitly allowed to be NULL */
Christopher Faulet4bfce392021-10-22 14:33:59 +02001828static int make_proxy_line_v2(char *buf, int buf_len, struct server *srv, struct connection *remote, struct stream *strm)
David Safb76832014-05-08 23:42:08 -04001829{
Willy Tarreau8fccfa22014-06-14 08:28:06 +02001830 const char pp2_signature[] = PP2_SIGNATURE;
Emmanuel Hocdet4399c752018-02-05 15:26:43 +01001831 void *tlv_crc32c_p = NULL;
David Safb76832014-05-08 23:42:08 -04001832 int ret = 0;
Willy Tarreau8fccfa22014-06-14 08:28:06 +02001833 struct proxy_hdr_v2 *hdr = (struct proxy_hdr_v2 *)buf;
Vincent Bernat6e615892016-05-18 16:17:44 +02001834 struct sockaddr_storage null_addr = { .ss_family = 0 };
Christopher Fauletb097aef2021-10-25 08:05:28 +02001835 const struct sockaddr_storage *src = &null_addr;
1836 const struct sockaddr_storage *dst = &null_addr;
Emmanuel Hocdet404d9782017-10-24 10:55:14 +02001837 const char *value;
1838 int value_len;
David Safb76832014-05-08 23:42:08 -04001839
1840 if (buf_len < PP2_HEADER_LEN)
1841 return 0;
Willy Tarreau8fccfa22014-06-14 08:28:06 +02001842 memcpy(hdr->sig, pp2_signature, PP2_SIGNATURE_LEN);
David Safb76832014-05-08 23:42:08 -04001843
Christopher Fauletb097aef2021-10-25 08:05:28 +02001844 if (strm) {
Christopher Faulet8da67aa2022-03-29 17:53:09 +02001845 src = cs_src(strm->csf);
1846 dst = cs_dst(strm->csf);
Christopher Fauletb097aef2021-10-25 08:05:28 +02001847 }
1848 else if (remote && conn_get_src(remote) && conn_get_dst(remote)) {
1849 src = conn_src(remote);
1850 dst = conn_dst(remote);
David Safb76832014-05-08 23:42:08 -04001851 }
KOVACS Krisztianb3e54fe2014-11-17 15:11:45 +01001852
Tim Duesterhus7fec0212018-07-27 18:46:13 +02001853 /* At least one of src or dst is not of AF_INET or AF_INET6 */
1854 if ( !src
1855 || !dst
Willy Tarreau119e50e2020-05-22 13:53:29 +02001856 || (!pp2_never_send_local && conn_is_back(remote)) // locally initiated connection
Tim Duesterhus7fec0212018-07-27 18:46:13 +02001857 || (src->ss_family != AF_INET && src->ss_family != AF_INET6)
1858 || (dst->ss_family != AF_INET && dst->ss_family != AF_INET6)) {
David Safb76832014-05-08 23:42:08 -04001859 if (buf_len < PP2_HDR_LEN_UNSPEC)
1860 return 0;
Willy Tarreau8fccfa22014-06-14 08:28:06 +02001861 hdr->ver_cmd = PP2_VERSION | PP2_CMD_LOCAL;
1862 hdr->fam = PP2_FAM_UNSPEC | PP2_TRANS_UNSPEC;
David Safb76832014-05-08 23:42:08 -04001863 ret = PP2_HDR_LEN_UNSPEC;
1864 }
Tim Duesterhus7fec0212018-07-27 18:46:13 +02001865 else {
Willy Tarreau02c88032020-04-14 12:54:10 +02001866 hdr->ver_cmd = PP2_VERSION | PP2_CMD_PROXY;
Tim Duesterhus7fec0212018-07-27 18:46:13 +02001867 /* IPv4 for both src and dst */
1868 if (src->ss_family == AF_INET && dst->ss_family == AF_INET) {
1869 if (buf_len < PP2_HDR_LEN_INET)
1870 return 0;
Tim Duesterhus7fec0212018-07-27 18:46:13 +02001871 hdr->fam = PP2_FAM_INET | PP2_TRANS_STREAM;
1872 hdr->addr.ip4.src_addr = ((struct sockaddr_in *)src)->sin_addr.s_addr;
1873 hdr->addr.ip4.src_port = ((struct sockaddr_in *)src)->sin_port;
1874 hdr->addr.ip4.dst_addr = ((struct sockaddr_in *)dst)->sin_addr.s_addr;
1875 hdr->addr.ip4.dst_port = ((struct sockaddr_in *)dst)->sin_port;
1876 ret = PP2_HDR_LEN_INET;
1877 }
1878 /* IPv6 for at least one of src and dst */
1879 else {
1880 struct in6_addr tmp;
1881
1882 if (buf_len < PP2_HDR_LEN_INET6)
1883 return 0;
Tim Duesterhus7fec0212018-07-27 18:46:13 +02001884 hdr->fam = PP2_FAM_INET6 | PP2_TRANS_STREAM;
1885 if (src->ss_family == AF_INET) {
1886 v4tov6(&tmp, &((struct sockaddr_in *)src)->sin_addr);
1887 memcpy(hdr->addr.ip6.src_addr, &tmp, 16);
1888 hdr->addr.ip6.src_port = ((struct sockaddr_in *)src)->sin_port;
1889 }
1890 else {
1891 memcpy(hdr->addr.ip6.src_addr, &((struct sockaddr_in6 *)src)->sin6_addr, 16);
1892 hdr->addr.ip6.src_port = ((struct sockaddr_in6 *)src)->sin6_port;
1893 }
1894 if (dst->ss_family == AF_INET) {
1895 v4tov6(&tmp, &((struct sockaddr_in *)dst)->sin_addr);
1896 memcpy(hdr->addr.ip6.dst_addr, &tmp, 16);
William Dauchybd8bf672020-01-26 19:06:39 +01001897 hdr->addr.ip6.dst_port = ((struct sockaddr_in *)dst)->sin_port;
Tim Duesterhus7fec0212018-07-27 18:46:13 +02001898 }
1899 else {
1900 memcpy(hdr->addr.ip6.dst_addr, &((struct sockaddr_in6 *)dst)->sin6_addr, 16);
1901 hdr->addr.ip6.dst_port = ((struct sockaddr_in6 *)dst)->sin6_port;
1902 }
1903
1904 ret = PP2_HDR_LEN_INET6;
1905 }
1906 }
David Safb76832014-05-08 23:42:08 -04001907
Emmanuel Hocdet4399c752018-02-05 15:26:43 +01001908 if (srv->pp_opts & SRV_PP_V2_CRC32C) {
1909 uint32_t zero_crc32c = 0;
Tim Duesterhusa8692f32020-03-13 12:34:25 +01001910
Emmanuel Hocdet4399c752018-02-05 15:26:43 +01001911 if ((buf_len - ret) < sizeof(struct tlv))
1912 return 0;
1913 tlv_crc32c_p = (void *)((struct tlv *)&buf[ret])->value;
1914 ret += make_tlv(&buf[ret], (buf_len - ret), PP2_TYPE_CRC32C, sizeof(zero_crc32c), (const char *)&zero_crc32c);
1915 }
1916
Ilya Shipitsinca56fce2018-09-15 00:50:05 +05001917 if (remote && conn_get_alpn(remote, &value, &value_len)) {
Emmanuel Hocdet404d9782017-10-24 10:55:14 +02001918 if ((buf_len - ret) < sizeof(struct tlv))
1919 return 0;
Emmanuel Hocdet571c7ac2017-10-31 18:24:05 +01001920 ret += make_tlv(&buf[ret], (buf_len - ret), PP2_TYPE_ALPN, value_len, value);
Emmanuel Hocdet404d9782017-10-24 10:55:14 +02001921 }
1922
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01001923 if (srv->pp_opts & SRV_PP_V2_AUTHORITY) {
Emmanuel Hocdet8a4ffa02019-08-29 11:54:51 +02001924 value = NULL;
Tim Duesterhus615f81e2021-03-06 20:06:50 +01001925 if (remote && isttest(remote->proxy_authority)) {
1926 value = istptr(remote->proxy_authority);
1927 value_len = istlen(remote->proxy_authority);
Emmanuel Hocdet8a4ffa02019-08-29 11:54:51 +02001928 }
1929#ifdef USE_OPENSSL
1930 else {
Jerome Magnin78891c72019-09-02 09:53:41 +02001931 if ((value = ssl_sock_get_sni(remote)))
Emmanuel Hocdet8a4ffa02019-08-29 11:54:51 +02001932 value_len = strlen(value);
1933 }
1934#endif
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01001935 if (value) {
1936 if ((buf_len - ret) < sizeof(struct tlv))
1937 return 0;
Emmanuel Hocdet8a4ffa02019-08-29 11:54:51 +02001938 ret += make_tlv(&buf[ret], (buf_len - ret), PP2_TYPE_AUTHORITY, value_len, value);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01001939 }
1940 }
1941
Christopher Faulet3ab504f2020-05-26 15:16:01 +02001942 if (strm && (srv->pp_opts & SRV_PP_V2_UNIQUE_ID)) {
Tim Duesterhuscf6e0c82020-03-13 12:34:24 +01001943 struct session* sess = strm_sess(strm);
1944 struct ist unique_id = stream_generate_unique_id(strm, &sess->fe->format_unique_id);
1945
1946 value = unique_id.ptr;
1947 value_len = unique_id.len;
1948
1949 if (value_len >= 0) {
1950 if ((buf_len - ret) < sizeof(struct tlv))
1951 return 0;
1952 ret += make_tlv(&buf[ret], (buf_len - ret), PP2_TYPE_UNIQUE_ID, value_len, value);
1953 }
1954 }
1955
Emmanuel Hocdet8a4ffa02019-08-29 11:54:51 +02001956#ifdef USE_OPENSSL
David Safb76832014-05-08 23:42:08 -04001957 if (srv->pp_opts & SRV_PP_V2_SSL) {
Emmanuel Hocdet404d9782017-10-24 10:55:14 +02001958 struct tlv_ssl *tlv;
1959 int ssl_tlv_len = 0;
Tim Duesterhusa8692f32020-03-13 12:34:25 +01001960
David Safb76832014-05-08 23:42:08 -04001961 if ((buf_len - ret) < sizeof(struct tlv_ssl))
1962 return 0;
1963 tlv = (struct tlv_ssl *)&buf[ret];
1964 memset(tlv, 0, sizeof(struct tlv_ssl));
1965 ssl_tlv_len += sizeof(struct tlv_ssl);
1966 tlv->tlv.type = PP2_TYPE_SSL;
Willy Tarreau1057bee2021-10-06 11:38:44 +02001967 if (conn_is_ssl(remote)) {
David Safb76832014-05-08 23:42:08 -04001968 tlv->client |= PP2_CLIENT_SSL;
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02001969 value = ssl_sock_get_proto_version(remote);
David Safb76832014-05-08 23:42:08 -04001970 if (value) {
Emmanuel Hocdet8c0c34b2018-02-28 12:02:14 +01001971 ssl_tlv_len += make_tlv(&buf[ret+ssl_tlv_len], (buf_len-ret-ssl_tlv_len), PP2_SUBTYPE_SSL_VERSION, strlen(value), value);
David Safb76832014-05-08 23:42:08 -04001972 }
Dave McCowan328fb582014-07-30 10:39:13 -04001973 if (ssl_sock_get_cert_used_sess(remote)) {
1974 tlv->client |= PP2_CLIENT_CERT_SESS;
David Safb76832014-05-08 23:42:08 -04001975 tlv->verify = htonl(ssl_sock_get_verify_result(remote));
Dave McCowan328fb582014-07-30 10:39:13 -04001976 if (ssl_sock_get_cert_used_conn(remote))
1977 tlv->client |= PP2_CLIENT_CERT_CONN;
David Safb76832014-05-08 23:42:08 -04001978 }
1979 if (srv->pp_opts & SRV_PP_V2_SSL_CN) {
Willy Tarreau83061a82018-07-13 11:56:34 +02001980 struct buffer *cn_trash = get_trash_chunk();
Willy Tarreau3b9a0c92014-07-19 06:37:33 +02001981 if (ssl_sock_get_remote_common_name(remote, cn_trash) > 0) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001982 ssl_tlv_len += make_tlv(&buf[ret+ssl_tlv_len], (buf_len - ret - ssl_tlv_len), PP2_SUBTYPE_SSL_CN,
1983 cn_trash->data,
1984 cn_trash->area);
David Safb76832014-05-08 23:42:08 -04001985 }
1986 }
Emmanuel Hocdetfa8d0f12018-02-01 15:53:52 +01001987 if (srv->pp_opts & SRV_PP_V2_SSL_KEY_ALG) {
Willy Tarreau83061a82018-07-13 11:56:34 +02001988 struct buffer *pkey_trash = get_trash_chunk();
Emmanuel Hocdetfa8d0f12018-02-01 15:53:52 +01001989 if (ssl_sock_get_pkey_algo(remote, pkey_trash) > 0) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001990 ssl_tlv_len += make_tlv(&buf[ret+ssl_tlv_len], (buf_len - ret - ssl_tlv_len), PP2_SUBTYPE_SSL_KEY_ALG,
1991 pkey_trash->data,
1992 pkey_trash->area);
Emmanuel Hocdetfa8d0f12018-02-01 15:53:52 +01001993 }
1994 }
1995 if (srv->pp_opts & SRV_PP_V2_SSL_SIG_ALG) {
1996 value = ssl_sock_get_cert_sig(remote);
1997 if (value) {
1998 ssl_tlv_len += make_tlv(&buf[ret+ssl_tlv_len], (buf_len - ret - ssl_tlv_len), PP2_SUBTYPE_SSL_SIG_ALG, strlen(value), value);
1999 }
2000 }
2001 if (srv->pp_opts & SRV_PP_V2_SSL_CIPHER) {
2002 value = ssl_sock_get_cipher_name(remote);
2003 if (value) {
2004 ssl_tlv_len += make_tlv(&buf[ret+ssl_tlv_len], (buf_len - ret - ssl_tlv_len), PP2_SUBTYPE_SSL_CIPHER, strlen(value), value);
2005 }
2006 }
David Safb76832014-05-08 23:42:08 -04002007 }
2008 tlv->tlv.length_hi = (uint16_t)(ssl_tlv_len - sizeof(struct tlv)) >> 8;
2009 tlv->tlv.length_lo = (uint16_t)(ssl_tlv_len - sizeof(struct tlv)) & 0x00ff;
2010 ret += ssl_tlv_len;
2011 }
2012#endif
2013
Willy Tarreaue5733232019-05-22 19:24:06 +02002014#ifdef USE_NS
KOVACS Krisztianb3e54fe2014-11-17 15:11:45 +01002015 if (remote && (remote->proxy_netns)) {
2016 if ((buf_len - ret) < sizeof(struct tlv))
2017 return 0;
Emmanuel Hocdet571c7ac2017-10-31 18:24:05 +01002018 ret += make_tlv(&buf[ret], (buf_len - ret), PP2_TYPE_NETNS, remote->proxy_netns->name_len, remote->proxy_netns->node.key);
KOVACS Krisztianb3e54fe2014-11-17 15:11:45 +01002019 }
2020#endif
2021
Willy Tarreau8fccfa22014-06-14 08:28:06 +02002022 hdr->len = htons((uint16_t)(ret - PP2_HEADER_LEN));
David Safb76832014-05-08 23:42:08 -04002023
Emmanuel Hocdet4399c752018-02-05 15:26:43 +01002024 if (tlv_crc32c_p) {
2025 write_u32(tlv_crc32c_p, htonl(hash_crc32c(buf, ret)));
2026 }
2027
David Safb76832014-05-08 23:42:08 -04002028 return ret;
2029}
Emeric Brun4f603012017-01-05 15:11:44 +01002030
Christopher Faulet4bfce392021-10-22 14:33:59 +02002031/* Note: <remote> is explicitly allowed to be NULL */
2032int make_proxy_line(char *buf, int buf_len, struct server *srv, struct connection *remote, struct stream *strm)
2033{
2034 int ret = 0;
2035
2036 if (srv && (srv->pp_opts & SRV_PP_V2)) {
2037 ret = make_proxy_line_v2(buf, buf_len, srv, remote, strm);
2038 }
2039 else {
Christopher Fauletb097aef2021-10-25 08:05:28 +02002040 const struct sockaddr_storage *src = NULL;
2041 const struct sockaddr_storage *dst = NULL;
2042
2043 if (strm) {
Christopher Faulet8da67aa2022-03-29 17:53:09 +02002044 src = cs_src(strm->csf);
2045 dst = cs_dst(strm->csf);
Christopher Fauletb097aef2021-10-25 08:05:28 +02002046 }
2047 else if (remote && conn_get_src(remote) && conn_get_dst(remote)) {
2048 src = conn_src(remote);
2049 dst = conn_dst(remote);
2050 }
2051
2052 if (src && dst)
2053 ret = make_proxy_line_v1(buf, buf_len, src, dst);
Christopher Faulet4bfce392021-10-22 14:33:59 +02002054 else
2055 ret = make_proxy_line_v1(buf, buf_len, NULL, NULL);
2056 }
2057
2058 return ret;
2059}
2060
Willy Tarreau119e50e2020-05-22 13:53:29 +02002061/* returns 0 on success */
2062static int cfg_parse_pp2_never_send_local(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01002063 const struct proxy *defpx, const char *file, int line,
Willy Tarreau119e50e2020-05-22 13:53:29 +02002064 char **err)
2065{
2066 if (too_many_args(0, args, err, NULL))
2067 return -1;
2068 pp2_never_send_local = 1;
2069 return 0;
2070}
2071
Willy Tarreaud943a042021-06-16 17:35:20 +02002072/* extracts some info from the connection and appends them to buffer <buf>. The
2073 * connection's pointer, its direction, target (fe/be/srv), xprt/ctrl, source
2074 * when set, destination when set, are printed in a compact human-readable format
2075 * fitting on a single line. This is handy to complete traces or debug output.
2076 * It is permitted to pass a NULL conn pointer. The number of characters emitted
2077 * is returned. A prefix <pfx> might be prepended before the first field if not
2078 * NULL.
2079 */
2080int conn_append_debug_info(struct buffer *buf, const struct connection *conn, const char *pfx)
2081{
2082 const struct listener *li;
2083 const struct server *sv;
2084 const struct proxy *px;
2085 char addr[40];
2086 int old_len = buf->data;
2087
2088 if (!conn)
2089 return 0;
2090
2091 chunk_appendf(buf, "%sconn=%p(%s)", pfx ? pfx : "", conn, conn_is_back(conn) ? "OUT" : "IN");
2092
2093 if ((li = objt_listener(conn->target)))
2094 chunk_appendf(buf, " fe=%s", li->bind_conf->frontend->id);
2095 else if ((sv = objt_server(conn->target)))
2096 chunk_appendf(buf, " sv=%s/%s", sv->proxy->id, sv->id);
2097 else if ((px = objt_proxy(conn->target)))
2098 chunk_appendf(buf, " be=%s", px->id);
2099
2100 chunk_appendf(buf, " %s/%s", conn_get_xprt_name(conn), conn_get_ctrl_name(conn));
2101
2102 if (conn->flags & CO_FL_ADDR_FROM_SET && addr_to_str(conn->src, addr, sizeof(addr)))
2103 chunk_appendf(buf, " src=%s:%d", addr, get_host_port(conn->src));
2104
2105 if (conn->flags & CO_FL_ADDR_TO_SET && addr_to_str(conn->dst, addr, sizeof(addr)))
2106 chunk_appendf(buf, " dst=%s:%d", addr, get_host_port(conn->dst));
2107
2108 return buf->data - old_len;
2109}
2110
Willy Tarreau60ca10a2017-08-18 15:26:54 +02002111/* return the major HTTP version as 1 or 2 depending on how the request arrived
2112 * before being processed.
Christopher Fauletf4dd9ae2021-04-14 15:40:30 +02002113 *
2114 * WARNING: Should be updated if a new major HTTP version is added.
Willy Tarreau60ca10a2017-08-18 15:26:54 +02002115 */
2116static int
2117smp_fetch_fc_http_major(const struct arg *args, struct sample *smp, const char *kw, void *private)
2118{
Christopher Faulet242f8ce2021-04-14 15:46:49 +02002119 struct connection *conn = NULL;
2120
2121 if (obj_type(smp->sess->origin) == OBJ_TYPE_CHECK)
2122 conn = (kw[0] == 'b') ? cs_conn(__objt_check(smp->sess->origin)->cs) : NULL;
2123 else
2124 conn = (kw[0] != 'b') ? objt_conn(smp->sess->origin) :
Christopher Faulet95a61e82021-12-22 14:22:03 +01002125 smp->strm ? cs_conn(smp->strm->csb) : NULL;
Willy Tarreau60ca10a2017-08-18 15:26:54 +02002126
Christopher Fauletf4dd9ae2021-04-14 15:40:30 +02002127 /* No connection or a connection with a RAW muxx */
2128 if (!conn || (conn->mux && !(conn->mux->flags & MX_FL_HTX)))
2129 return 0;
2130
2131 /* No mux install, this may change */
2132 if (!conn->mux) {
2133 smp->flags |= SMP_F_MAY_CHANGE;
2134 return 0;
2135 }
2136
Willy Tarreau60ca10a2017-08-18 15:26:54 +02002137 smp->data.type = SMP_T_SINT;
Christopher Fauletf4dd9ae2021-04-14 15:40:30 +02002138 smp->data.u.sint = (strcmp(conn_get_mux_name(conn), "H2") == 0) ? 2 : 1;
Willy Tarreau60ca10a2017-08-18 15:26:54 +02002139 return 1;
2140}
2141
Emeric Brun4f603012017-01-05 15:11:44 +01002142/* fetch if the received connection used a PROXY protocol header */
2143int smp_fetch_fc_rcvd_proxy(const struct arg *args, struct sample *smp, const char *kw, void *private)
2144{
2145 struct connection *conn;
2146
2147 conn = objt_conn(smp->sess->origin);
2148 if (!conn)
2149 return 0;
2150
Willy Tarreau911db9b2020-01-23 16:27:54 +01002151 if (conn->flags & CO_FL_WAIT_XPRT) {
Emeric Brun4f603012017-01-05 15:11:44 +01002152 smp->flags |= SMP_F_MAY_CHANGE;
2153 return 0;
2154 }
2155
2156 smp->flags = 0;
2157 smp->data.type = SMP_T_BOOL;
2158 smp->data.u.sint = (conn->flags & CO_FL_RCVD_PROXY) ? 1 : 0;
2159
2160 return 1;
2161}
2162
Geoff Simmons7185b782019-08-27 18:31:16 +02002163/* fetch the authority TLV from a PROXY protocol header */
2164int smp_fetch_fc_pp_authority(const struct arg *args, struct sample *smp, const char *kw, void *private)
2165{
2166 struct connection *conn;
2167
2168 conn = objt_conn(smp->sess->origin);
2169 if (!conn)
2170 return 0;
2171
Willy Tarreau911db9b2020-01-23 16:27:54 +01002172 if (conn->flags & CO_FL_WAIT_XPRT) {
Geoff Simmons7185b782019-08-27 18:31:16 +02002173 smp->flags |= SMP_F_MAY_CHANGE;
2174 return 0;
2175 }
2176
Tim Duesterhus615f81e2021-03-06 20:06:50 +01002177 if (!isttest(conn->proxy_authority))
Geoff Simmons7185b782019-08-27 18:31:16 +02002178 return 0;
2179
2180 smp->flags = 0;
2181 smp->data.type = SMP_T_STR;
Tim Duesterhus615f81e2021-03-06 20:06:50 +01002182 smp->data.u.str.area = istptr(conn->proxy_authority);
2183 smp->data.u.str.data = istlen(conn->proxy_authority);
Geoff Simmons7185b782019-08-27 18:31:16 +02002184
2185 return 1;
2186}
2187
Tim Duesterhusd1b15b62020-03-13 12:34:23 +01002188/* fetch the unique ID TLV from a PROXY protocol header */
2189int smp_fetch_fc_pp_unique_id(const struct arg *args, struct sample *smp, const char *kw, void *private)
2190{
2191 struct connection *conn;
2192
2193 conn = objt_conn(smp->sess->origin);
2194 if (!conn)
2195 return 0;
2196
2197 if (conn->flags & CO_FL_WAIT_XPRT) {
2198 smp->flags |= SMP_F_MAY_CHANGE;
2199 return 0;
2200 }
2201
2202 if (!isttest(conn->proxy_unique_id))
2203 return 0;
2204
2205 smp->flags = 0;
2206 smp->data.type = SMP_T_STR;
Tim Duesterhus002bd772021-03-06 20:06:49 +01002207 smp->data.u.str.area = istptr(conn->proxy_unique_id);
2208 smp->data.u.str.data = istlen(conn->proxy_unique_id);
Tim Duesterhusd1b15b62020-03-13 12:34:23 +01002209
2210 return 1;
2211}
2212
Remi Tricot-Le Breton3d2093a2021-07-29 09:45:49 +02002213/* fetch the error code of a connection */
Willy Tarreau6f749762021-11-05 17:07:03 +01002214int smp_fetch_fc_err(const struct arg *args, struct sample *smp, const char *kw, void *private)
Remi Tricot-Le Breton3d2093a2021-07-29 09:45:49 +02002215{
2216 struct connection *conn;
2217
Remi Tricot-Le Breton942c1672021-09-01 15:52:15 +02002218 if (obj_type(smp->sess->origin) == OBJ_TYPE_CHECK)
2219 conn = (kw[0] == 'b') ? cs_conn(__objt_check(smp->sess->origin)->cs) : NULL;
2220 else
2221 conn = (kw[0] != 'b') ? objt_conn(smp->sess->origin) :
Christopher Faulet95a61e82021-12-22 14:22:03 +01002222 smp->strm ? cs_conn(smp->strm->csb) : NULL;
Remi Tricot-Le Breton942c1672021-09-01 15:52:15 +02002223
Remi Tricot-Le Breton3d2093a2021-07-29 09:45:49 +02002224 if (!conn)
2225 return 0;
2226
2227 if (conn->flags & CO_FL_WAIT_XPRT && !conn->err_code) {
2228 smp->flags |= SMP_F_MAY_CHANGE;
2229 return 0;
2230 }
2231
2232 smp->flags = 0;
2233 smp->data.type = SMP_T_SINT;
2234 smp->data.u.sint = (unsigned long long int)conn->err_code;
2235
2236 return 1;
2237}
2238
2239/* fetch a string representation of the error code of a connection */
Willy Tarreau6f749762021-11-05 17:07:03 +01002240int smp_fetch_fc_err_str(const struct arg *args, struct sample *smp, const char *kw, void *private)
Remi Tricot-Le Breton3d2093a2021-07-29 09:45:49 +02002241{
2242 struct connection *conn;
2243 const char *err_code_str;
2244
Remi Tricot-Le Breton942c1672021-09-01 15:52:15 +02002245 if (obj_type(smp->sess->origin) == OBJ_TYPE_CHECK)
2246 conn = (kw[0] == 'b') ? cs_conn(__objt_check(smp->sess->origin)->cs) : NULL;
2247 else
2248 conn = (kw[0] != 'b') ? objt_conn(smp->sess->origin) :
Christopher Faulet95a61e82021-12-22 14:22:03 +01002249 smp->strm ? cs_conn(smp->strm->csb) : NULL;
Remi Tricot-Le Breton942c1672021-09-01 15:52:15 +02002250
Remi Tricot-Le Breton3d2093a2021-07-29 09:45:49 +02002251 if (!conn)
2252 return 0;
2253
2254 if (conn->flags & CO_FL_WAIT_XPRT && !conn->err_code) {
2255 smp->flags |= SMP_F_MAY_CHANGE;
2256 return 0;
2257 }
2258
2259 err_code_str = conn_err_code_str(conn);
2260
2261 if (!err_code_str)
2262 return 0;
2263
2264 smp->flags = 0;
2265 smp->data.type = SMP_T_STR;
2266 smp->data.u.str.area = (char*)err_code_str;
2267 smp->data.u.str.data = strlen(err_code_str);
2268
2269 return 1;
2270}
2271
Emeric Brun4f603012017-01-05 15:11:44 +01002272/* Note: must not be declared <const> as its list will be overwritten.
2273 * Note: fetches that may return multiple types must be declared as the lowest
2274 * common denominator, the type that can be casted into all other ones. For
2275 * instance v4/v6 must be declared v4.
2276 */
2277static struct sample_fetch_kw_list sample_fetch_keywords = {ILH, {
Willy Tarreau6f749762021-11-05 17:07:03 +01002278 { "bc_err", smp_fetch_fc_err, 0, NULL, SMP_T_SINT, SMP_USE_L4SRV },
2279 { "bc_err_str", smp_fetch_fc_err_str, 0, NULL, SMP_T_STR, SMP_USE_L4SRV },
Jérôme Magnin86577422018-12-07 09:03:11 +01002280 { "bc_http_major", smp_fetch_fc_http_major, 0, NULL, SMP_T_SINT, SMP_USE_L4SRV },
Willy Tarreau6f749762021-11-05 17:07:03 +01002281 { "fc_err", smp_fetch_fc_err, 0, NULL, SMP_T_SINT, SMP_USE_L4CLI },
2282 { "fc_err_str", smp_fetch_fc_err_str, 0, NULL, SMP_T_STR, SMP_USE_L4CLI },
2283 { "fc_http_major", smp_fetch_fc_http_major, 0, NULL, SMP_T_SINT, SMP_USE_L4CLI },
Emeric Brun4f603012017-01-05 15:11:44 +01002284 { "fc_rcvd_proxy", smp_fetch_fc_rcvd_proxy, 0, NULL, SMP_T_BOOL, SMP_USE_L4CLI },
Geoff Simmons7185b782019-08-27 18:31:16 +02002285 { "fc_pp_authority", smp_fetch_fc_pp_authority, 0, NULL, SMP_T_STR, SMP_USE_L4CLI },
Tim Duesterhusd1b15b62020-03-13 12:34:23 +01002286 { "fc_pp_unique_id", smp_fetch_fc_pp_unique_id, 0, NULL, SMP_T_STR, SMP_USE_L4CLI },
Emeric Brun4f603012017-01-05 15:11:44 +01002287 { /* END */ },
2288}};
2289
Willy Tarreau0108d902018-11-25 19:14:37 +01002290INITCALL1(STG_REGISTER, sample_register_fetches, &sample_fetch_keywords);
Willy Tarreau119e50e2020-05-22 13:53:29 +02002291
2292static struct cfg_kw_list cfg_kws = {ILH, {
2293 { CFG_GLOBAL, "pp2-never-send-local", cfg_parse_pp2_never_send_local },
2294 { /* END */ },
2295}};
2296
2297INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
Amaury Denoyelle81c6f762021-01-18 14:57:50 +01002298
Amaury Denoyelle01a287f2021-02-11 16:46:53 +01002299/* private function to handle sockaddr as input for connection hash */
2300static void conn_calculate_hash_sockaddr(const struct sockaddr_storage *ss,
2301 char *buf, size_t *idx,
2302 enum conn_hash_params_t *hash_flags,
2303 enum conn_hash_params_t param_type_addr,
2304 enum conn_hash_params_t param_type_port)
2305{
2306 struct sockaddr_in *addr;
2307 struct sockaddr_in6 *addr6;
2308
2309 switch (ss->ss_family) {
2310 case AF_INET:
2311 addr = (struct sockaddr_in *)ss;
2312
2313 conn_hash_update(buf, idx,
2314 &addr->sin_addr, sizeof(addr->sin_addr),
2315 hash_flags, param_type_addr);
2316
2317 if (addr->sin_port) {
2318 conn_hash_update(buf, idx,
2319 &addr->sin_port, sizeof(addr->sin_port),
2320 hash_flags, param_type_port);
2321 }
2322
2323 break;
2324
2325 case AF_INET6:
2326 addr6 = (struct sockaddr_in6 *)ss;
2327
2328 conn_hash_update(buf, idx,
2329 &addr6->sin6_addr, sizeof(addr6->sin6_addr),
2330 hash_flags, param_type_addr);
2331
2332 if (addr6->sin6_port) {
2333 conn_hash_update(buf, idx,
2334 &addr6->sin6_port, sizeof(addr6->sin6_port),
2335 hash_flags, param_type_port);
2336 }
2337
2338 break;
2339 }
2340}
2341
Willy Tarreaue5983ff2021-10-06 17:14:49 +02002342/* Generate the hash of a connection with params as input
2343 * Each non-null field of params is taken into account for the hash calcul.
2344 */
2345uint64_t conn_hash_prehash(char *buf, size_t size)
2346{
2347 return XXH64(buf, size, 0);
2348}
2349
2350/* Append <data> into <buf> at <idx> offset in preparation for connection hash
2351 * calcul. <idx> is incremented beyond data <size>. In the same time, <flags>
2352 * are updated with <type> for the hash header.
2353 */
2354void conn_hash_update(char *buf, size_t *idx,
2355 const void *data, size_t size,
2356 enum conn_hash_params_t *flags,
2357 enum conn_hash_params_t type)
2358{
2359 memcpy(&buf[*idx], data, size);
2360 *idx += size;
2361 *flags |= type;
2362}
2363
2364uint64_t conn_hash_digest(char *buf, size_t bufsize,
2365 enum conn_hash_params_t flags)
2366{
2367 const uint64_t flags_u64 = (uint64_t)flags;
2368 const uint64_t hash = XXH64(buf, bufsize, 0);
2369
2370 return (flags_u64 << CONN_HASH_PAYLOAD_LEN) | CONN_HASH_GET_PAYLOAD(hash);
2371}
2372
Willy Tarreaufd21c6c2021-10-06 17:09:41 +02002373uint64_t conn_calculate_hash(const struct conn_hash_params *params)
Amaury Denoyelle81c6f762021-01-18 14:57:50 +01002374{
2375 char *buf;
2376 size_t idx = 0;
Willy Tarreaufd21c6c2021-10-06 17:09:41 +02002377 uint64_t hash = 0;
Amaury Denoyelle81c6f762021-01-18 14:57:50 +01002378 enum conn_hash_params_t hash_flags = 0;
2379
2380 buf = trash.area;
2381
Amaury Denoyelle8ede3db2021-03-02 14:38:53 +01002382 conn_hash_update(buf, &idx, &params->target, sizeof(params->target), &hash_flags, 0);
Amaury Denoyelle1a58aca2021-01-22 16:47:46 +01002383
Amaury Denoyelle9b626e32021-01-06 17:03:27 +01002384 if (params->sni_prehash) {
2385 conn_hash_update(buf, &idx,
Amaury Denoyelle36441f42021-02-17 16:25:31 +01002386 &params->sni_prehash, sizeof(params->sni_prehash),
Amaury Denoyelle9b626e32021-01-06 17:03:27 +01002387 &hash_flags, CONN_HASH_PARAMS_TYPE_SNI);
2388 }
2389
Amaury Denoyelle01a287f2021-02-11 16:46:53 +01002390 if (params->dst_addr) {
2391 conn_calculate_hash_sockaddr(params->dst_addr,
2392 buf, &idx, &hash_flags,
2393 CONN_HASH_PARAMS_TYPE_DST_ADDR,
2394 CONN_HASH_PARAMS_TYPE_DST_PORT);
2395 }
2396
Amaury Denoyelled10a2002021-02-11 19:45:19 +01002397 if (params->src_addr) {
2398 conn_calculate_hash_sockaddr(params->src_addr,
2399 buf, &idx, &hash_flags,
2400 CONN_HASH_PARAMS_TYPE_SRC_ADDR,
2401 CONN_HASH_PARAMS_TYPE_SRC_PORT);
2402 }
2403
Amaury Denoyelle1921d202021-01-14 10:15:29 +01002404 if (params->proxy_prehash) {
2405 conn_hash_update(buf, &idx,
Amaury Denoyelle36441f42021-02-17 16:25:31 +01002406 &params->proxy_prehash, sizeof(params->proxy_prehash),
Amaury Denoyelle1921d202021-01-14 10:15:29 +01002407 &hash_flags, CONN_HASH_PARAMS_TYPE_PROXY);
2408 }
Amaury Denoyelle01a287f2021-02-11 16:46:53 +01002409
Amaury Denoyelle1921d202021-01-14 10:15:29 +01002410 hash = conn_hash_digest(buf, idx, hash_flags);
Amaury Denoyelle81c6f762021-01-18 14:57:50 +01002411 return hash;
2412}
Amaury Denoyelle48372932021-09-16 12:15:12 +02002413
2414/* Handler of the task of mux_stopping_data.
2415 * Called on soft-stop.
2416 */
2417static struct task *mux_stopping_process(struct task *t, void *ctx, unsigned int state)
2418{
2419 struct connection *conn, *back;
2420
2421 list_for_each_entry_safe(conn, back, &mux_stopping_data[tid].list, stopping_list) {
2422 if (conn->mux && conn->mux->wake)
2423 conn->mux->wake(conn);
2424 }
2425
2426 return t;
2427}
2428
2429static int allocate_mux_cleanup(void)
2430{
2431 /* allocates the thread bound mux_stopping_data task */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02002432 mux_stopping_data[tid].task = task_new_here();
Amaury Denoyelle48372932021-09-16 12:15:12 +02002433 if (!mux_stopping_data[tid].task) {
2434 ha_alert("Failed to allocate the task for connection cleanup on thread %d.\n", tid);
2435 return 0;
2436 }
2437
2438 mux_stopping_data[tid].task->process = mux_stopping_process;
2439 LIST_INIT(&mux_stopping_data[tid].list);
2440
2441 return 1;
2442}
2443REGISTER_PER_THREAD_ALLOC(allocate_mux_cleanup);
2444
2445static int deallocate_mux_cleanup(void)
2446{
2447 task_destroy(mux_stopping_data[tid].task);
2448 return 1;
2449}
2450REGISTER_PER_THREAD_FREE(deallocate_mux_cleanup);