1 /*
2  * include/proto/connection.h
3  * This file contains connection function prototypes
4  *
5  * Copyright (C) 2000-2012 Willy Tarreau - w@1wt.eu
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation, version 2.1
10  * exclusively.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21 
22 #ifndef _PROTO_CONNECTION_H
23 #define _PROTO_CONNECTION_H
24 
25 #include <common/config.h>
26 #include <common/ist.h>
27 #include <common/memory.h>
28 #include <types/connection.h>
29 #include <types/listener.h>
30 #include <proto/fd.h>
31 #include <proto/obj_type.h>
32 #include <proto/session.h>
33 #include <proto/task.h>
34 
35 extern struct pool_head *pool_head_connection;
36 extern struct pool_head *pool_head_connstream;
37 extern struct pool_head *pool_head_sockaddr;
38 extern struct pool_head *pool_head_authority;
39 extern struct xprt_ops *registered_xprt[XPRT_ENTRIES];
40 extern struct mux_proto_list mux_proto_list;
41 
42 /* I/O callback for fd-based connections. It calls the read/write handlers
43  * provided by the connection's sock_ops.
44  */
45 void conn_fd_handler(int fd);
46 
47 /* receive a PROXY protocol header over a connection */
48 int conn_recv_proxy(struct connection *conn, int flag);
49 int make_proxy_line(char *buf, int buf_len, struct server *srv, struct connection *remote);
50 int make_proxy_line_v1(char *buf, int buf_len, struct sockaddr_storage *src, struct sockaddr_storage *dst);
51 int make_proxy_line_v2(char *buf, int buf_len, struct server *srv, struct connection *remote);
52 
53 int conn_subscribe(struct connection *conn, void *xprt_ctx, int event_type, void *param);
54 int conn_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, void *param);
55 
56 /* receive a NetScaler Client IP insertion header over a connection */
57 int conn_recv_netscaler_cip(struct connection *conn, int flag);
58 
59 /* raw send() directly on the socket */
60 int conn_sock_send(struct connection *conn, const void *buf, int len, int flags);
61 
62 /* drains any pending bytes from the socket */
63 int conn_sock_drain(struct connection *conn);
64 
65 /* scoks4 proxy handshake */
66 int conn_send_socks4_proxy_request(struct connection *conn);
67 int conn_recv_socks4_proxy_response(struct connection *conn);
68 
69 __decl_hathreads(extern HA_SPINLOCK_T toremove_lock[MAX_THREADS]);
70 
71 /* returns true is the transport layer is ready */
conn_xprt_ready(const struct connection * conn)72 static inline int conn_xprt_ready(const struct connection *conn)
73 {
74 	return (conn->flags & CO_FL_XPRT_READY);
75 }
76 
77 /* returns true is the control layer is ready */
conn_ctrl_ready(const struct connection * conn)78 static inline int conn_ctrl_ready(const struct connection *conn)
79 {
80 	return (conn->flags & CO_FL_CTRL_READY);
81 }
82 
83 /* Calls the init() function of the transport layer if any and if not done yet,
84  * and sets the CO_FL_XPRT_READY flag to indicate it was properly initialized.
85  * Returns <0 in case of error.
86  */
conn_xprt_init(struct connection * conn)87 static inline int conn_xprt_init(struct connection *conn)
88 {
89 	int ret = 0;
90 
91 	if (!conn_xprt_ready(conn) && conn->xprt && conn->xprt->init)
92 		ret = conn->xprt->init(conn, &conn->xprt_ctx);
93 
94 	if (ret >= 0)
95 		conn->flags |= CO_FL_XPRT_READY;
96 
97 	return ret;
98 }
99 
100 /* Calls the close() function of the transport layer if any and if not done
101  * yet, and clears the CO_FL_XPRT_READY flag. However this is not done if the
102  * CO_FL_XPRT_TRACKED flag is set, which allows logs to take data from the
103  * transport layer very late if needed.
104  */
conn_xprt_close(struct connection * conn)105 static inline void conn_xprt_close(struct connection *conn)
106 {
107 	if ((conn->flags & (CO_FL_XPRT_READY|CO_FL_XPRT_TRACKED)) == CO_FL_XPRT_READY) {
108 		if (conn->xprt->close)
109 			conn->xprt->close(conn, conn->xprt_ctx);
110 		conn->xprt_ctx = NULL;
111 		conn->flags &= ~CO_FL_XPRT_READY;
112 	}
113 }
114 
115 /* Initializes the connection's control layer which essentially consists in
116  * registering the file descriptor for polling and setting the CO_FL_CTRL_READY
117  * flag. The caller is responsible for ensuring that the control layer is
118  * already assigned to the connection prior to the call.
119  */
conn_ctrl_init(struct connection * conn)120 static inline void conn_ctrl_init(struct connection *conn)
121 {
122 	if (!conn_ctrl_ready(conn)) {
123 		int fd = conn->handle.fd;
124 
125 		fd_insert(fd, conn, conn_fd_handler, tid_bit);
126 		conn->flags |= CO_FL_CTRL_READY;
127 	}
128 }
129 
130 /* Deletes the FD if the transport layer is already gone. Once done,
131  * it then removes the CO_FL_CTRL_READY flag.
132  */
conn_ctrl_close(struct connection * conn)133 static inline void conn_ctrl_close(struct connection *conn)
134 {
135 	if ((conn->flags & (CO_FL_XPRT_READY|CO_FL_CTRL_READY)) == CO_FL_CTRL_READY) {
136 		fd_delete(conn->handle.fd);
137 		conn->handle.fd = DEAD_FD_MAGIC;
138 		conn->flags &= ~CO_FL_CTRL_READY;
139 	}
140 }
141 
142 /* If the connection still has a transport layer, then call its close() function
143  * if any, and delete the file descriptor if a control layer is set. This is
144  * used to close everything at once and atomically. However this is not done if
145  * the CO_FL_XPRT_TRACKED flag is set, which allows logs to take data from the
146  * transport layer very late if needed.
147  */
conn_full_close(struct connection * conn)148 static inline void conn_full_close(struct connection *conn)
149 {
150 	conn_xprt_close(conn);
151 	conn_ctrl_close(conn);
152 }
153 
154 /* stop tracking a connection, allowing conn_full_close() to always
155  * succeed.
156  */
conn_stop_tracking(struct connection * conn)157 static inline void conn_stop_tracking(struct connection *conn)
158 {
159 	conn->flags &= ~CO_FL_XPRT_TRACKED;
160 }
161 
162 /* Update polling on connection <c>'s file descriptor depending on its current
163  * state as reported in the connection's CO_FL_CURR_* flags, reports of EAGAIN
164  * in CO_FL_WAIT_*, and the upper layer expectations indicated by CO_FL_XPRT_*.
165  * The connection flags are updated with the new flags at the end of the
166  * operation. Polling is totally disabled if an error was reported.
167  */
168 void conn_update_xprt_polling(struct connection *c);
169 
170 /* Refresh the connection's polling flags from its file descriptor status.
171  * This should be called at the beginning of a connection handler. It does
172  * nothing if CO_FL_WILL_UPDATE is present, indicating that an upper caller
173  * has already done it.
174  */
conn_refresh_polling_flags(struct connection * conn)175 static inline void conn_refresh_polling_flags(struct connection *conn)
176 {
177 	if (conn_ctrl_ready(conn) && !(conn->flags & CO_FL_WILL_UPDATE)) {
178 		unsigned int flags = conn->flags;
179 
180 		flags &= ~(CO_FL_CURR_RD_ENA | CO_FL_CURR_WR_ENA | CO_FL_WAIT_ROOM);
181 		if (fd_recv_active(conn->handle.fd))
182 			flags |= CO_FL_CURR_RD_ENA;
183 		if (fd_send_active(conn->handle.fd))
184 			flags |= CO_FL_CURR_WR_ENA;
185 		conn->flags = flags;
186 	}
187 }
188 
189 /* inspects c->flags and returns non-zero if XPRT ENA changes from the CURR ENA
190  * or if the WAIT flags are set with their respective ENA flags. Additionally,
191  * non-zero is also returned if an error was reported on the connection. This
192  * function is used quite often and is inlined. In order to proceed optimally
193  * with very little code and CPU cycles, the bits are arranged so that a change
194  * can be detected by a few left shifts, a xor, and a mask. These operations
195  * detect when W&D are both enabled for either direction, when C&D differ for
196  * either direction and when Error is set. The trick consists in first keeping
197  * only the bits we're interested in, since they don't collide when shifted,
198  * and to perform the AND at the end. In practice, the compiler is able to
199  * replace the last AND with a TEST in boolean conditions. This results in
200  * checks that are done in 4-6 cycles and less than 30 bytes.
201  */
conn_xprt_polling_changes(const struct connection * c)202 static inline unsigned int conn_xprt_polling_changes(const struct connection *c)
203 {
204 	unsigned int f = c->flags;
205 	f &= CO_FL_XPRT_WR_ENA | CO_FL_XPRT_RD_ENA | CO_FL_CURR_WR_ENA |
206 	     CO_FL_CURR_RD_ENA | CO_FL_ERROR;
207 
208 	f = (f ^ (f << 1)) & (CO_FL_CURR_WR_ENA|CO_FL_CURR_RD_ENA);    /* test C ^ D */
209 	return f & (CO_FL_CURR_WR_ENA | CO_FL_CURR_RD_ENA | CO_FL_ERROR);
210 }
211 
212 /* Automatically updates polling on connection <c> depending on the XPRT flags.
213  * It does nothing if CO_FL_WILL_UPDATE is present, indicating that an upper
214  * caller is going to do it again later.
215  */
conn_cond_update_xprt_polling(struct connection * c)216 static inline void conn_cond_update_xprt_polling(struct connection *c)
217 {
218 	if (!(c->flags & CO_FL_WILL_UPDATE))
219 		if (conn_xprt_polling_changes(c))
220 			conn_update_xprt_polling(c);
221 }
222 
223 /* Stop all polling on the fd. This might be used when an error is encountered
224  * for example. It does not propage the change to the fd layer if
225  * CO_FL_WILL_UPDATE is present, indicating that an upper caller is going to do
226  * it later.
227  */
conn_stop_polling(struct connection * c)228 static inline void conn_stop_polling(struct connection *c)
229 {
230 	c->flags &= ~(CO_FL_CURR_RD_ENA | CO_FL_CURR_WR_ENA |
231 		      CO_FL_XPRT_RD_ENA | CO_FL_XPRT_WR_ENA);
232 	if (!(c->flags & CO_FL_WILL_UPDATE) && conn_ctrl_ready(c))
233 		fd_stop_both(c->handle.fd);
234 }
235 
236 /* Automatically update polling on connection <c> depending on the XPRT and
237  * SOCK flags, and on whether a handshake is in progress or not. This may be
238  * called at any moment when there is a doubt about the effectiveness of the
239  * polling state, for instance when entering or leaving the handshake state.
240  * It does nothing if CO_FL_WILL_UPDATE is present, indicating that an upper
241  * caller is going to do it again later.
242  */
conn_cond_update_polling(struct connection * c)243 static inline void conn_cond_update_polling(struct connection *c)
244 {
245 	if (unlikely(c->flags & CO_FL_ERROR))
246 		conn_stop_polling(c);
247 	else if (!(c->flags & CO_FL_WILL_UPDATE)) {
248 		if (conn_xprt_polling_changes(c))
249 			conn_update_xprt_polling(c);
250 	}
251 }
252 
253 /***** Event manipulation primitives for use by DATA I/O callbacks *****/
254 /* The __conn_* versions do not propagate to lower layers and are only meant
255  * to be used by handlers called by the connection handler. The other ones
256  * may be used anywhere.
257  */
__conn_xprt_want_recv(struct connection * c)258 static inline void __conn_xprt_want_recv(struct connection *c)
259 {
260 	c->flags |= CO_FL_XPRT_RD_ENA;
261 }
262 
__conn_xprt_stop_recv(struct connection * c)263 static inline void __conn_xprt_stop_recv(struct connection *c)
264 {
265 	c->flags &= ~CO_FL_XPRT_RD_ENA;
266 }
267 
__conn_xprt_want_send(struct connection * c)268 static inline void __conn_xprt_want_send(struct connection *c)
269 {
270 	c->flags |= CO_FL_XPRT_WR_ENA;
271 }
272 
__conn_xprt_stop_send(struct connection * c)273 static inline void __conn_xprt_stop_send(struct connection *c)
274 {
275 	c->flags &= ~CO_FL_XPRT_WR_ENA;
276 }
277 
__conn_xprt_stop_both(struct connection * c)278 static inline void __conn_xprt_stop_both(struct connection *c)
279 {
280 	c->flags &= ~(CO_FL_XPRT_WR_ENA | CO_FL_XPRT_RD_ENA);
281 }
282 
conn_xprt_want_recv(struct connection * c)283 static inline void conn_xprt_want_recv(struct connection *c)
284 {
285 	__conn_xprt_want_recv(c);
286 	conn_cond_update_xprt_polling(c);
287 }
288 
conn_xprt_stop_recv(struct connection * c)289 static inline void conn_xprt_stop_recv(struct connection *c)
290 {
291 	__conn_xprt_stop_recv(c);
292 	conn_cond_update_xprt_polling(c);
293 }
294 
conn_xprt_want_send(struct connection * c)295 static inline void conn_xprt_want_send(struct connection *c)
296 {
297 	__conn_xprt_want_send(c);
298 	conn_cond_update_xprt_polling(c);
299 }
300 
conn_xprt_stop_send(struct connection * c)301 static inline void conn_xprt_stop_send(struct connection *c)
302 {
303 	__conn_xprt_stop_send(c);
304 	conn_cond_update_xprt_polling(c);
305 }
306 
conn_xprt_stop_both(struct connection * c)307 static inline void conn_xprt_stop_both(struct connection *c)
308 {
309 	__conn_xprt_stop_both(c);
310 	conn_cond_update_xprt_polling(c);
311 }
312 
313 /* read shutdown, called from the rcv_buf/rcv_pipe handlers when
314  * detecting an end of connection.
315  */
conn_sock_read0(struct connection * c)316 static inline void conn_sock_read0(struct connection *c)
317 {
318 	c->flags |= CO_FL_SOCK_RD_SH;
319 	__conn_xprt_stop_recv(c);
320 	/* we don't risk keeping ports unusable if we found the
321 	 * zero from the other side.
322 	 */
323 	if (conn_ctrl_ready(c))
324 		fdtab[c->handle.fd].linger_risk = 0;
325 }
326 
327 /* write shutdown, indication that the upper layer is not willing to send
328  * anything anymore and wants to close after pending data are sent. The
329  * <clean> argument will allow not to perform the socket layer shutdown if
330  * equal to 0.
331  */
conn_sock_shutw(struct connection * c,int clean)332 static inline void conn_sock_shutw(struct connection *c, int clean)
333 {
334 	c->flags |= CO_FL_SOCK_WR_SH;
335 	conn_refresh_polling_flags(c);
336 	__conn_xprt_stop_send(c);
337 	conn_cond_update_xprt_polling(c);
338 
339 	/* don't perform a clean shutdown if we're going to reset or
340 	 * if the shutr was already received.
341 	 */
342 	if (conn_ctrl_ready(c) && !(c->flags & CO_FL_SOCK_RD_SH) && clean)
343 		shutdown(c->handle.fd, SHUT_WR);
344 }
345 
conn_xprt_shutw(struct connection * c)346 static inline void conn_xprt_shutw(struct connection *c)
347 {
348 	__conn_xprt_stop_send(c);
349 
350 	/* clean data-layer shutdown */
351 	if (c->xprt && c->xprt->shutw)
352 		c->xprt->shutw(c, c->xprt_ctx, 1);
353 }
354 
conn_xprt_shutw_hard(struct connection * c)355 static inline void conn_xprt_shutw_hard(struct connection *c)
356 {
357 	__conn_xprt_stop_send(c);
358 
359 	/* unclean data-layer shutdown */
360 	if (c->xprt && c->xprt->shutw)
361 		c->xprt->shutw(c, c->xprt_ctx, 0);
362 }
363 
364 /* shut read */
cs_shutr(struct conn_stream * cs,enum cs_shr_mode mode)365 static inline void cs_shutr(struct conn_stream *cs, enum cs_shr_mode mode)
366 {
367 
368 	/* clean data-layer shutdown */
369 	if (cs->conn->mux && cs->conn->mux->shutr)
370 		cs->conn->mux->shutr(cs, mode);
371 	cs->flags |= (mode == CS_SHR_DRAIN) ? CS_FL_SHRD : CS_FL_SHRR;
372 }
373 
374 /* shut write */
cs_shutw(struct conn_stream * cs,enum cs_shw_mode mode)375 static inline void cs_shutw(struct conn_stream *cs, enum cs_shw_mode mode)
376 {
377 
378 	/* clean data-layer shutdown */
379 	if (cs->conn->mux && cs->conn->mux->shutw)
380 		cs->conn->mux->shutw(cs, mode);
381 	cs->flags |= (mode == CS_SHW_NORMAL) ? CS_FL_SHWN : CS_FL_SHWS;
382 }
383 
384 /* completely close a conn_stream (but do not detach it) */
cs_close(struct conn_stream * cs)385 static inline void cs_close(struct conn_stream *cs)
386 {
387 	cs_shutw(cs, CS_SHW_SILENT);
388 	cs_shutr(cs, CS_SHR_RESET);
389 	cs->flags = CS_FL_NONE;
390 }
391 
392 /* sets CS_FL_ERROR or CS_FL_ERR_PENDING on the cs */
cs_set_error(struct conn_stream * cs)393 static inline void cs_set_error(struct conn_stream *cs)
394 {
395 	if (cs->flags & CS_FL_EOS)
396 		cs->flags |= CS_FL_ERROR;
397 	else
398 		cs->flags |= CS_FL_ERR_PENDING;
399 }
400 
401 /* detect sock->data read0 transition */
conn_xprt_read0_pending(struct connection * c)402 static inline int conn_xprt_read0_pending(struct connection *c)
403 {
404 	return (c->flags & CO_FL_SOCK_RD_SH) != 0;
405 }
406 
407 /* prepares a connection to work with protocol <proto> and transport <xprt>.
408  * The transport's is initialized as well, and the mux and its context are
409  * cleared. The target is not reinitialized and it is recommended that it is
410  * set prior to calling this function so that the function may make use of it
411  * in the future to refine the mux choice if needed.
412  */
conn_prepare(struct connection * conn,const struct protocol * proto,const struct xprt_ops * xprt)413 static inline void conn_prepare(struct connection *conn, const struct protocol *proto, const struct xprt_ops *xprt)
414 {
415 	conn->ctrl = proto;
416 	conn->xprt = xprt;
417 	conn->mux  = NULL;
418 	conn->xprt_ctx = NULL;
419 	conn->ctx = NULL;
420 }
421 
422 /*
423  * Initializes all required fields for a new conn_strema.
424  */
cs_init(struct conn_stream * cs,struct connection * conn)425 static inline void cs_init(struct conn_stream *cs, struct connection *conn)
426 {
427 	cs->obj_type = OBJ_TYPE_CS;
428 	cs->flags = CS_FL_NONE;
429 	cs->conn = conn;
430 }
431 
432 /* Initializes all required fields for a new connection. Note that it does the
433  * minimum acceptable initialization for a connection that already exists and
434  * is about to be reused. It also leaves the addresses untouched, which makes
435  * it usable across connection retries to reset a connection to a known state.
436  */
conn_init(struct connection * conn)437 static inline void conn_init(struct connection *conn)
438 {
439 	conn->obj_type = OBJ_TYPE_CONN;
440 	conn->flags = CO_FL_NONE;
441 	conn->mux = NULL;
442 	conn->ctx = NULL;
443 	conn->owner = NULL;
444 	conn->send_proxy_ofs = 0;
445 	conn->handle.fd = DEAD_FD_MAGIC;
446 	conn->err_code = CO_ER_NONE;
447 	conn->target = NULL;
448 	conn->xprt_done_cb = NULL;
449 	conn->destroy_cb = NULL;
450 	conn->proxy_netns = NULL;
451 	LIST_INIT(&conn->list);
452 	LIST_INIT(&conn->session_list);
453 	conn->send_wait = NULL;
454 	conn->recv_wait = NULL;
455 	conn->idle_time = 0;
456 	conn->src = NULL;
457 	conn->dst = NULL;
458 	conn->proxy_authority = NULL;
459 }
460 
461 /* sets <owner> as the connection's owner */
conn_set_owner(struct connection * conn,void * owner,void (* cb)(struct connection *))462 static inline void conn_set_owner(struct connection *conn, void *owner, void (*cb)(struct connection *))
463 {
464 	conn->owner = owner;
465 	conn->destroy_cb = cb;
466 }
467 
468 /* registers <cb> as a callback to notify for transport's readiness or failure */
conn_set_xprt_done_cb(struct connection * conn,int (* cb)(struct connection *))469 static inline void conn_set_xprt_done_cb(struct connection *conn, int (*cb)(struct connection *))
470 {
471 	conn->xprt_done_cb = cb;
472 }
473 
474 /* unregisters the callback to notify for transport's readiness or failure */
conn_clear_xprt_done_cb(struct connection * conn)475 static inline void conn_clear_xprt_done_cb(struct connection *conn)
476 {
477 	conn->xprt_done_cb = NULL;
478 }
479 
480 /* Allocates a struct sockaddr from the pool if needed, assigns it to *sap and
481  * returns it. If <sap> is NULL, the address is always allocated and returned.
482  * if <sap> is non-null, an address will only be allocated if it points to a
483  * non-null pointer. In this case the allocated address will be assigned there.
484  * In both situations the new pointer is returned.
485  */
sockaddr_alloc(struct sockaddr_storage ** sap)486 static inline struct sockaddr_storage *sockaddr_alloc(struct sockaddr_storage **sap)
487 {
488 	struct sockaddr_storage *sa;
489 
490 	if (sap && *sap)
491 		return *sap;
492 
493 	sa = pool_alloc(pool_head_sockaddr);
494 	if (sap)
495 		*sap = sa;
496 	return sa;
497 }
498 
499 /* Releases the struct sockaddr potentially pointed to by <sap> to the pool. It
500  * may be NULL or may point to NULL. If <sap> is not NULL, a NULL is placed
501  * there.
502  */
sockaddr_free(struct sockaddr_storage ** sap)503 static inline void sockaddr_free(struct sockaddr_storage **sap)
504 {
505 	if (!sap)
506 		return;
507 	pool_free(pool_head_sockaddr, *sap);
508 	*sap = NULL;
509 }
510 
511 /* Tries to allocate a new connection and initialized its main fields. The
512  * connection is returned on success, NULL on failure. The connection must
513  * be released using pool_free() or conn_free().
514  */
conn_new()515 static inline struct connection *conn_new()
516 {
517 	struct connection *conn;
518 
519 	conn = pool_alloc(pool_head_connection);
520 	if (likely(conn != NULL))
521 		conn_init(conn);
522 	return conn;
523 }
524 
525 /* Releases a conn_stream previously allocated by cs_new(), as well as any
526  * buffer it would still hold.
527  */
cs_free(struct conn_stream * cs)528 static inline void cs_free(struct conn_stream *cs)
529 {
530 
531 	pool_free(pool_head_connstream, cs);
532 }
533 
534 /* Tries to allocate a new conn_stream and initialize its main fields. If
535  * <conn> is NULL, then a new connection is allocated on the fly, initialized,
536  * and assigned to cs->conn ; this connection will then have to be released
537  * using pool_free() or conn_free(). The conn_stream is initialized and added
538  * to the mux's stream list on success, then returned. On failure, nothing is
539  * allocated and NULL is returned.
540  */
cs_new(struct connection * conn)541 static inline struct conn_stream *cs_new(struct connection *conn)
542 {
543 	struct conn_stream *cs;
544 
545 	cs = pool_alloc(pool_head_connstream);
546 	if (!likely(cs))
547 		return NULL;
548 
549 	if (!conn) {
550 		conn = conn_new();
551 		if (!likely(conn)) {
552 			cs_free(cs);
553 			return NULL;
554 		}
555 		conn_init(conn);
556 	}
557 
558 	cs_init(cs, conn);
559 	return cs;
560 }
561 
562 /* Retrieves any valid conn_stream from this connection, preferably the first
563  * valid one. The purpose is to be able to figure one other end of a private
564  * connection for purposes like source binding or proxy protocol header
565  * emission. In such cases, any conn_stream is expected to be valid so the
566  * mux is encouraged to return the first one it finds. If the connection has
567  * no mux or the mux has no get_first_cs() method or the mux has no valid
568  * conn_stream, NULL is returned. The output pointer is purposely marked
569  * const to discourage the caller from modifying anything there.
570  */
cs_get_first(const struct connection * conn)571 static inline const struct conn_stream *cs_get_first(const struct connection *conn)
572 {
573 	if (!conn || !conn->mux || !conn->mux->get_first_cs)
574 		return NULL;
575 	return conn->mux->get_first_cs(conn);
576 }
577 
conn_force_unsubscribe(struct connection * conn)578 static inline void conn_force_unsubscribe(struct connection *conn)
579 {
580 	if (conn->recv_wait) {
581 		conn->recv_wait->events &= ~SUB_RETRY_RECV;
582 		conn->recv_wait = NULL;
583 	}
584 	if (conn->send_wait) {
585 		conn->send_wait->events &= ~SUB_RETRY_SEND;
586 		conn->send_wait = NULL;
587 	}
588 
589 }
590 
591 /* Releases a connection previously allocated by conn_new() */
conn_free(struct connection * conn)592 static inline void conn_free(struct connection *conn)
593 {
594 	/* Remove ourself from the session's connections list, if any. */
595 	if (!LIST_ISEMPTY(&conn->session_list)) {
596 		struct session *sess = conn->owner;
597 		if (conn->flags & CO_FL_SESS_IDLE)
598 			sess->idle_conns--;
599 		session_unown_conn(sess, conn);
600 	}
601 
602 	sockaddr_free(&conn->src);
603 	sockaddr_free(&conn->dst);
604 
605 	if (conn->proxy_authority != NULL) {
606 		pool_free(pool_head_authority, conn->proxy_authority);
607 		conn->proxy_authority = NULL;
608 	}
609 
610 	/* By convention we always place a NULL where the ctx points to if the
611 	 * mux is null. It may have been used to store the connection as a
612 	 * stream_interface's end point for example.
613 	 */
614 	if (conn->ctx != NULL && conn->mux == NULL)
615 		*(void **)conn->ctx = NULL;
616 
617 	/* The connection is currently in the server's idle list, so tell it
618 	 * there's one less connection available in that list.
619 	 */
620 	if (conn->idle_time > 0) {
621 		struct server *srv = __objt_server(conn->target);
622 		_HA_ATOMIC_SUB(&srv->curr_idle_conns, 1);
623 		srv->curr_idle_thr[tid]--;
624 	}
625 
626 	conn_force_unsubscribe(conn);
627 	HA_SPIN_LOCK(OTHER_LOCK, &toremove_lock[tid]);
628 	MT_LIST_DEL((struct mt_list *)&conn->list);
629 	HA_SPIN_UNLOCK(OTHER_LOCK, &toremove_lock[tid]);
630 	pool_free(pool_head_connection, conn);
631 }
632 
633 /* Release a conn_stream */
cs_destroy(struct conn_stream * cs)634 static inline void cs_destroy(struct conn_stream *cs)
635 {
636 	if (cs->conn->mux)
637 		cs->conn->mux->detach(cs);
638 	else {
639 		/* It's too early to have a mux, let's just destroy
640 		 * the connection
641 		 */
642 		struct connection *conn = cs->conn;
643 
644 		conn_stop_tracking(conn);
645 		conn_full_close(conn);
646 		if (conn->destroy_cb)
647 			conn->destroy_cb(conn);
648 		conn_free(conn);
649 	}
650 	cs_free(cs);
651 }
652 
653 /* Returns the conn from a cs. If cs is NULL, returns NULL */
cs_conn(const struct conn_stream * cs)654 static inline struct connection *cs_conn(const struct conn_stream *cs)
655 {
656 	return cs ? cs->conn : NULL;
657 }
658 
659 /* Retrieves the connection's original source address. Returns non-zero on
660  * success or zero on failure. The operation is only performed once and the
661  * address is stored in the connection for future use.
662  */
conn_get_src(struct connection * conn)663 static inline int conn_get_src(struct connection *conn)
664 {
665 	if (conn->flags & CO_FL_ADDR_FROM_SET)
666 		return 1;
667 
668 	if (!conn_ctrl_ready(conn) || !conn->ctrl->get_src)
669 		return 0;
670 
671 	if (!sockaddr_alloc(&conn->src))
672 		return 0;
673 
674 	if (conn->ctrl->get_src(conn->handle.fd, (struct sockaddr *)conn->src,
675 	                        sizeof(*conn->src),
676 	                        obj_type(conn->target) != OBJ_TYPE_LISTENER) == -1)
677 		return 0;
678 	conn->flags |= CO_FL_ADDR_FROM_SET;
679 	return 1;
680 }
681 
682 /* Retrieves the connection's original destination address. Returns non-zero on
683  * success or zero on failure. The operation is only performed once and the
684  * address is stored in the connection for future use.
685  */
conn_get_dst(struct connection * conn)686 static inline int conn_get_dst(struct connection *conn)
687 {
688 	if (conn->flags & CO_FL_ADDR_TO_SET)
689 		return 1;
690 
691 	if (!conn_ctrl_ready(conn) || !conn->ctrl->get_dst)
692 		return 0;
693 
694 	if (!sockaddr_alloc(&conn->dst))
695 		return 0;
696 
697 	if (conn->ctrl->get_dst(conn->handle.fd, (struct sockaddr *)conn->dst,
698 	                        sizeof(*conn->dst),
699 	                        obj_type(conn->target) != OBJ_TYPE_LISTENER) == -1)
700 		return 0;
701 	conn->flags |= CO_FL_ADDR_TO_SET;
702 	return 1;
703 }
704 
705 /* Sets the TOS header in IPv4 and the traffic class header in IPv6 packets
706  * (as per RFC3260 #4 and BCP37 #4.2 and #5.2). The connection is tested and if
707  * it is null, nothing is done.
708  */
conn_set_tos(const struct connection * conn,int tos)709 static inline void conn_set_tos(const struct connection *conn, int tos)
710 {
711 	if (!conn || !conn_ctrl_ready(conn))
712 		return;
713 
714 #ifdef IP_TOS
715 	if (conn->src->ss_family == AF_INET)
716 		setsockopt(conn->handle.fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
717 #endif
718 #ifdef IPV6_TCLASS
719 	if (conn->src->ss_family == AF_INET6) {
720 		if (IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)conn->src)->sin6_addr))
721 			/* v4-mapped addresses need IP_TOS */
722 			setsockopt(conn->handle.fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
723 		else
724 			setsockopt(conn->handle.fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos));
725 	}
726 #endif
727 }
728 
729 /* Sets the netfilter mark on the connection's socket. The connection is tested
730  * and if it is null, nothing is done.
731  */
conn_set_mark(const struct connection * conn,int mark)732 static inline void conn_set_mark(const struct connection *conn, int mark)
733 {
734 	if (!conn || !conn_ctrl_ready(conn))
735 		return;
736 
737 #ifdef SO_MARK
738 	setsockopt(conn->handle.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
739 #endif
740 }
741 
742 /* Sets adjust the TCP quick-ack feature on the connection's socket. The
743  * connection is tested and if it is null, nothing is done.
744  */
conn_set_quickack(const struct connection * conn,int value)745 static inline void conn_set_quickack(const struct connection *conn, int value)
746 {
747 	if (!conn || !conn_ctrl_ready(conn))
748 		return;
749 
750 #ifdef TCP_QUICKACK
751 	setsockopt(conn->handle.fd, IPPROTO_TCP, TCP_QUICKACK, &value, sizeof(value));
752 #endif
753 }
754 
755 /* Attaches a conn_stream to a data layer and sets the relevant callbacks */
cs_attach(struct conn_stream * cs,void * data,const struct data_cb * data_cb)756 static inline void cs_attach(struct conn_stream *cs, void *data, const struct data_cb *data_cb)
757 {
758 	cs->data_cb = data_cb;
759 	cs->data = data;
760 }
761 
wl_set_waitcb(struct wait_event * wl,struct task * (* cb)(struct task *,void *,unsigned short),void * ctx)762 static inline struct wait_event *wl_set_waitcb(struct wait_event *wl, struct task *(*cb)(struct task *, void *, unsigned short), void *ctx)
763 {
764 	if (!wl->tasklet->process) {
765 		wl->tasklet->process = cb;
766 		wl->tasklet->context = ctx;
767 	}
768 	return wl;
769 }
770 
771 /* Installs the connection's mux layer for upper context <ctx>.
772  * Returns < 0 on error.
773  */
conn_install_mux(struct connection * conn,const struct mux_ops * mux,void * ctx,struct proxy * prx,struct session * sess)774 static inline int conn_install_mux(struct connection *conn, const struct mux_ops *mux,
775                                    void *ctx, struct proxy *prx, struct session *sess)
776 {
777 	int ret;
778 
779 	conn->mux = mux;
780 	conn->ctx = ctx;
781 	ret = mux->init ? mux->init(conn, prx, sess, &BUF_NULL) : 0;
782 	if (ret < 0) {
783 		conn->mux = NULL;
784 		conn->ctx = NULL;
785 	}
786 	return ret;
787 }
788 
789 /* returns a human-readable error code for conn->err_code, or NULL if the code
790  * is unknown.
791  */
conn_err_code_str(struct connection * c)792 static inline const char *conn_err_code_str(struct connection *c)
793 {
794 	switch (c->err_code) {
795 	case CO_ER_NONE:          return "Success";
796 
797 	case CO_ER_CONF_FDLIM:    return "Reached configured maxconn value";
798 	case CO_ER_PROC_FDLIM:    return "Too many sockets on the process";
799 	case CO_ER_SYS_FDLIM:     return "Too many sockets on the system";
800 	case CO_ER_SYS_MEMLIM:    return "Out of system buffers";
801 	case CO_ER_NOPROTO:       return "Protocol or address family not supported";
802 	case CO_ER_SOCK_ERR:      return "General socket error";
803 	case CO_ER_PORT_RANGE:    return "Source port range exhausted";
804 	case CO_ER_CANT_BIND:     return "Can't bind to source address";
805 	case CO_ER_FREE_PORTS:    return "Out of local source ports on the system";
806 	case CO_ER_ADDR_INUSE:    return "Local source address already in use";
807 
808 	case CO_ER_PRX_EMPTY:     return "Connection closed while waiting for PROXY protocol header";
809 	case CO_ER_PRX_ABORT:     return "Connection error while waiting for PROXY protocol header";
810 	case CO_ER_PRX_TIMEOUT:   return "Timeout while waiting for PROXY protocol header";
811 	case CO_ER_PRX_TRUNCATED: return "Truncated PROXY protocol header received";
812 	case CO_ER_PRX_NOT_HDR:   return "Received something which does not look like a PROXY protocol header";
813 	case CO_ER_PRX_BAD_HDR:   return "Received an invalid PROXY protocol header";
814 	case CO_ER_PRX_BAD_PROTO: return "Received an unhandled protocol in the PROXY protocol header";
815 
816 	case CO_ER_CIP_EMPTY:     return "Connection closed while waiting for NetScaler Client IP header";
817 	case CO_ER_CIP_ABORT:     return "Connection error while waiting for NetScaler Client IP header";
818 	case CO_ER_CIP_TRUNCATED: return "Truncated NetScaler Client IP header received";
819 	case CO_ER_CIP_BAD_MAGIC: return "Received an invalid NetScaler Client IP magic number";
820 	case CO_ER_CIP_BAD_PROTO: return "Received an unhandled protocol in the NetScaler Client IP header";
821 
822 	case CO_ER_SSL_EMPTY:     return "Connection closed during SSL handshake";
823 	case CO_ER_SSL_ABORT:     return "Connection error during SSL handshake";
824 	case CO_ER_SSL_TIMEOUT:   return "Timeout during SSL handshake";
825 	case CO_ER_SSL_TOO_MANY:  return "Too many SSL connections";
826 	case CO_ER_SSL_NO_MEM:    return "Out of memory when initializing an SSL connection";
827 	case CO_ER_SSL_RENEG:     return "Rejected a client-initiated SSL renegociation attempt";
828 	case CO_ER_SSL_CA_FAIL:   return "SSL client CA chain cannot be verified";
829 	case CO_ER_SSL_CRT_FAIL:  return "SSL client certificate not trusted";
830 	case CO_ER_SSL_MISMATCH:  return "Server presented an SSL certificate different from the configured one";
831 	case CO_ER_SSL_MISMATCH_SNI: return "Server presented an SSL certificate different from the expected one";
832 	case CO_ER_SSL_HANDSHAKE: return "SSL handshake failure";
833 	case CO_ER_SSL_HANDSHAKE_HB: return "SSL handshake failure after heartbeat";
834 	case CO_ER_SSL_KILLED_HB: return "Stopped a TLSv1 heartbeat attack (CVE-2014-0160)";
835 	case CO_ER_SSL_NO_TARGET: return "Attempt to use SSL on an unknown target (internal error)";
836 
837 	case CO_ER_SOCKS4_SEND:    return "SOCKS4 Proxy write error during handshake";
838 	case CO_ER_SOCKS4_RECV:    return "SOCKS4 Proxy read error during handshake";
839 	case CO_ER_SOCKS4_DENY:    return "SOCKS4 Proxy deny the request";
840 	case CO_ER_SOCKS4_ABORT:   return "SOCKS4 Proxy handshake aborted by server";
841 	}
842 	return NULL;
843 }
844 
conn_get_ctrl_name(const struct connection * conn)845 static inline const char *conn_get_ctrl_name(const struct connection *conn)
846 {
847 	if (!conn || !conn_ctrl_ready(conn))
848 		return "NONE";
849 	return conn->ctrl->name;
850 }
851 
conn_get_xprt_name(const struct connection * conn)852 static inline const char *conn_get_xprt_name(const struct connection *conn)
853 {
854 	if (!conn || !conn_xprt_ready(conn))
855 		return "NONE";
856 	return conn->xprt->name;
857 }
858 
conn_get_mux_name(const struct connection * conn)859 static inline const char *conn_get_mux_name(const struct connection *conn)
860 {
861 	if (!conn || !conn->mux)
862 		return "NONE";
863 	return conn->mux->name;
864 }
865 
cs_get_data_name(const struct conn_stream * cs)866 static inline const char *cs_get_data_name(const struct conn_stream *cs)
867 {
868 	if (!cs || !cs->data_cb)
869 		return "NONE";
870 	return cs->data_cb->name;
871 }
872 
873 /* registers pointer to transport layer <id> (XPRT_*) */
xprt_register(int id,struct xprt_ops * xprt)874 static inline void xprt_register(int id, struct xprt_ops *xprt)
875 {
876 	if (id >= XPRT_ENTRIES)
877 		return;
878 	registered_xprt[id] = xprt;
879 }
880 
881 /* returns pointer to transport layer <id> (XPRT_*) or NULL if not registered */
xprt_get(int id)882 static inline struct xprt_ops *xprt_get(int id)
883 {
884 	if (id >= XPRT_ENTRIES)
885 		return NULL;
886 	return registered_xprt[id];
887 }
888 
889 /* Try to add a handshake pseudo-XPRT. If the connection's first XPRT is
890  * raw_sock, then just use the new XPRT as the connection XPRT, otherwise
891  * call the xprt's add_xprt() method.
892  * Returns 0 on success, or non-zero on failure.
893  */
xprt_add_hs(struct connection * conn)894 static inline int xprt_add_hs(struct connection *conn)
895 {
896 	void *xprt_ctx = NULL;
897 	const struct xprt_ops *ops = xprt_get(XPRT_HANDSHAKE);
898 	void *nextxprt_ctx = NULL;
899 	const struct xprt_ops *nextxprt_ops = NULL;
900 
901 	if (conn->flags & CO_FL_ERROR)
902 		return -1;
903 	if (ops->init(conn, &xprt_ctx) < 0)
904 		return -1;
905 	if (conn->xprt == xprt_get(XPRT_RAW)) {
906 		nextxprt_ctx = conn->xprt_ctx;
907 		nextxprt_ops = conn->xprt;
908 		conn->xprt_ctx = xprt_ctx;
909 		conn->xprt = ops;
910 	} else {
911 		if (conn->xprt->add_xprt(conn, conn->xprt_ctx, xprt_ctx, ops,
912 		                         &nextxprt_ctx, &nextxprt_ops) != 0) {
913 			ops->close(conn, xprt_ctx);
914 			return -1;
915 		}
916 	}
917 	if (ops->add_xprt(conn, xprt_ctx, nextxprt_ctx, nextxprt_ops, NULL, NULL) != 0) {
918 		ops->close(conn, xprt_ctx);
919 		return -1;
920 	}
921 	return 0;
922 }
923 
conn_get_alpn(const struct connection * conn,const char ** str,int * len)924 static inline int conn_get_alpn(const struct connection *conn, const char **str, int *len)
925 {
926 	if (!conn_xprt_ready(conn) || !conn->xprt->get_alpn)
927 		return 0;
928 	return conn->xprt->get_alpn(conn, conn->xprt_ctx, str, len);
929 }
930 
931 /* registers proto mux list <list>. Modifies the list element! */
register_mux_proto(struct mux_proto_list * list)932 static inline void register_mux_proto(struct mux_proto_list *list)
933 {
934 	LIST_ADDQ(&mux_proto_list.list, &list->list);
935 }
936 
937 /* unregisters proto mux list <list> */
unregister_mux_proto(struct mux_proto_list * list)938 static inline void unregister_mux_proto(struct mux_proto_list *list)
939 {
940 	LIST_DEL(&list->list);
941 	LIST_INIT(&list->list);
942 }
943 
get_mux_proto(const struct ist proto)944 static inline struct mux_proto_list *get_mux_proto(const struct ist proto)
945 {
946 	struct mux_proto_list *item;
947 
948 	list_for_each_entry(item, &mux_proto_list.list, list) {
949 		if (isteq(proto, item->token))
950 			return item;
951 	}
952 	return NULL;
953 }
954 
955 /* Lists the known proto mux on <out> */
list_mux_proto(FILE * out)956 static inline void list_mux_proto(FILE *out)
957 {
958 	struct mux_proto_list *item;
959 	struct ist proto;
960 	char *mode, *side;
961 
962 	fprintf(out, "Available multiplexer protocols :\n"
963 		"(protocols marked as <default> cannot be specified using 'proto' keyword)\n");
964 	list_for_each_entry(item, &mux_proto_list.list, list) {
965 		proto = item->token;
966 
967 		if (item->mode == PROTO_MODE_ANY)
968 			mode = "TCP|HTTP";
969 		else if (item->mode == PROTO_MODE_TCP)
970 			mode = "TCP";
971 		else if (item->mode == PROTO_MODE_HTTP)
972 			mode = "HTTP";
973 		else
974 			mode = "NONE";
975 
976 		if (item->side == PROTO_SIDE_BOTH)
977 			side = "FE|BE";
978 		else if (item->side == PROTO_SIDE_FE)
979 			side = "FE";
980 		else if (item->side == PROTO_SIDE_BE)
981 			side = "BE";
982 		else
983 			side = "NONE";
984 
985 		fprintf(out, " %15s : mode=%-10s side=%-8s  mux=%s\n",
986 			(proto.len ? proto.ptr : "<default>"), mode, side, item->mux->name);
987 	}
988 }
989 
990 /* returns the first mux entry in the list matching the exact same <mux_proto>
991  * and compatible with the <proto_side> (FE or BE) and the <proto_mode> (TCP or
992  * HTTP). <mux_proto> can be empty. Will fall back to the first compatible mux
993  * with exactly the same <proto_mode> or with an empty name. May return
994  * null if the code improperly registered the default mux to use as a fallback.
995  */
conn_get_best_mux_entry(const struct ist mux_proto,int proto_side,int proto_mode)996 static inline const struct mux_proto_list *conn_get_best_mux_entry(
997         const struct ist mux_proto,
998         int proto_side, int proto_mode)
999 {
1000 	struct mux_proto_list *item;
1001 	struct mux_proto_list *fallback = NULL;
1002 
1003 	list_for_each_entry(item, &mux_proto_list.list, list) {
1004 		if (!(item->side & proto_side) || !(item->mode & proto_mode))
1005 			continue;
1006 		if (istlen(mux_proto) && isteq(mux_proto, item->token))
1007 			return item;
1008 		else if (!istlen(item->token)) {
1009 			if (!fallback || (item->mode == proto_mode && fallback->mode != proto_mode))
1010 				fallback = item;
1011 		}
1012 	}
1013 	return fallback;
1014 
1015 }
1016 
1017 /* returns the first mux in the list matching the exact same <mux_proto> and
1018  * compatible with the <proto_side> (FE or BE) and the <proto_mode> (TCP or
1019  * HTTP). <mux_proto> can be empty. Will fall back to the first compatible mux
1020  * with exactly the same <proto_mode> or with an empty name. May return
1021  * null if the code improperly registered the default mux to use as a fallback.
1022  */
conn_get_best_mux(struct connection * conn,const struct ist mux_proto,int proto_side,int proto_mode)1023 static inline const struct mux_ops *conn_get_best_mux(struct connection *conn,
1024 						      const struct ist mux_proto,
1025 						      int proto_side, int proto_mode)
1026 {
1027 	const struct mux_proto_list *item;
1028 
1029 	item = conn_get_best_mux_entry(mux_proto, proto_side, proto_mode);
1030 
1031 	return item ? item->mux : NULL;
1032 }
1033 
1034 /* returns 0 if the connection is valid and is a frontend connection, otherwise
1035  * returns 1 indicating it's a backend connection. And uninitialized connection
1036  * also returns 1 to better handle the usage in the middle of initialization.
1037  */
conn_is_back(const struct connection * conn)1038 static inline int conn_is_back(const struct connection *conn)
1039 {
1040 	return !objt_listener(conn->target);
1041 }
1042 
1043 /* returns a pointer to the proxy associated with this connection. For a front
1044  * connection it returns a pointer to the frontend ; for a back connection, it
1045  * returns a pointer to the backend.
1046  */
conn_get_proxy(const struct connection * conn)1047 static inline struct proxy *conn_get_proxy(const struct connection *conn)
1048 {
1049 	struct listener *l;
1050 	struct server *s;
1051 
1052 	/* check if it's a frontend connection */
1053 	l = objt_listener(conn->target);
1054 	if (l)
1055 		return l->bind_conf->frontend;
1056 
1057 	/* check if it's a backend connection */
1058 	s = objt_server(conn->target);
1059 	if (s)
1060 		return s->proxy;
1061 
1062 	return objt_proxy(conn->target);
1063 }
1064 
1065 /* installs the best mux for incoming connection <conn> using the upper context
1066  * <ctx>. If the mux protocol is forced, we use it to find the best
1067  * mux. Otherwise we use the ALPN name, if any. Returns < 0 on error.
1068  */
conn_install_mux_fe(struct connection * conn,void * ctx)1069 static inline int conn_install_mux_fe(struct connection *conn, void *ctx)
1070 {
1071 	struct bind_conf     *bind_conf = __objt_listener(conn->target)->bind_conf;
1072 	const struct mux_ops *mux_ops;
1073 
1074 	if (bind_conf->mux_proto)
1075 		mux_ops = bind_conf->mux_proto->mux;
1076 	else {
1077 		struct ist mux_proto;
1078 		const char *alpn_str = NULL;
1079 		int alpn_len = 0;
1080 		int mode;
1081 
1082 		if (bind_conf->frontend->mode == PR_MODE_HTTP)
1083 			mode = PROTO_MODE_HTTP;
1084 		else
1085 			mode = PROTO_MODE_TCP;
1086 
1087 		conn_get_alpn(conn, &alpn_str, &alpn_len);
1088 		mux_proto = ist2(alpn_str, alpn_len);
1089 		mux_ops = conn_get_best_mux(conn, mux_proto, PROTO_SIDE_FE, mode);
1090 		if (!mux_ops)
1091 			return -1;
1092 	}
1093 	return conn_install_mux(conn, mux_ops, ctx, bind_conf->frontend, conn->owner);
1094 }
1095 
1096 /* installs the best mux for outgoing connection <conn> using the upper context
1097  * <ctx>. If the mux protocol is forced, we use it to find the best mux. Returns
1098  * < 0 on error.
1099  */
conn_install_mux_be(struct connection * conn,void * ctx,struct session * sess)1100 static inline int conn_install_mux_be(struct connection *conn, void *ctx, struct session *sess)
1101 {
1102 	struct server *srv = objt_server(conn->target);
1103 	struct proxy  *prx = objt_proxy(conn->target);
1104 	const struct mux_ops *mux_ops;
1105 
1106 	if (srv)
1107 		prx = srv->proxy;
1108 
1109 	if (!prx) // target must be either proxy or server
1110 		return -1;
1111 
1112 	if (srv && srv->mux_proto)
1113 		mux_ops = srv->mux_proto->mux;
1114 	else {
1115 		struct ist mux_proto;
1116 		const char *alpn_str = NULL;
1117 		int alpn_len = 0;
1118 		int mode;
1119 
1120 		if (prx->mode == PR_MODE_HTTP)
1121 			mode = PROTO_MODE_HTTP;
1122 		else
1123 			mode = PROTO_MODE_TCP;
1124 
1125 		conn_get_alpn(conn, &alpn_str, &alpn_len);
1126 		mux_proto = ist2(alpn_str, alpn_len);
1127 
1128 		mux_ops = conn_get_best_mux(conn, mux_proto, PROTO_SIDE_BE, mode);
1129 		if (!mux_ops)
1130 			return -1;
1131 	}
1132 	return conn_install_mux(conn, mux_ops, ctx, prx, sess);
1133 }
1134 
1135 /* Change the mux for the connection.
1136  * The caller should make sure he's not subscribed to the underlying XPRT.
1137  */
conn_upgrade_mux_fe(struct connection * conn,void * ctx,struct buffer * buf,struct ist mux_proto,int mode)1138 static inline int conn_upgrade_mux_fe(struct connection *conn, void *ctx, struct buffer *buf,
1139 				      struct ist mux_proto, int mode)
1140 {
1141 	struct bind_conf *bind_conf = __objt_listener(conn->target)->bind_conf;
1142 	const struct mux_ops *old_mux, *new_mux;
1143 	void *old_mux_ctx;
1144 	const char *alpn_str = NULL;
1145 	int alpn_len = 0;
1146 
1147 	if (!mux_proto.len) {
1148 		conn_get_alpn(conn, &alpn_str, &alpn_len);
1149 		mux_proto = ist2(alpn_str, alpn_len);
1150 	}
1151 	new_mux = conn_get_best_mux(conn, mux_proto, PROTO_SIDE_FE, mode);
1152 	old_mux = conn->mux;
1153 
1154 	/* No mux found */
1155 	if (!new_mux)
1156 		return -1;
1157 
1158 	/* Same mux, nothing to do */
1159 	if (old_mux == new_mux)
1160 		return 0;
1161 
1162 	old_mux_ctx = conn->ctx;
1163 	conn->mux = new_mux;
1164 	conn->ctx = ctx;
1165 	if (new_mux->init(conn, bind_conf->frontend, conn->owner, buf) == -1) {
1166 		/* The mux upgrade failed, so restore the old mux */
1167 		conn->ctx = old_mux_ctx;
1168 		conn->mux = old_mux;
1169 		return -1;
1170 	}
1171 
1172 	/* The mux was upgraded, destroy the old one */
1173 	*buf = BUF_NULL;
1174 	old_mux->destroy(old_mux_ctx);
1175 	return 0;
1176 }
1177 
1178 #endif /* _PROTO_CONNECTION_H */
1179 
1180 /*
1181  * Local variables:
1182  *  c-indent-level: 8
1183  *  c-basic-offset: 8
1184  * End:
1185  */
1186