1 /*
2  * Session management functions.
3  *
4  * Copyright 2000-2015 Willy Tarreau <w@1wt.eu>
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version
9  * 2 of the License, or (at your option) any later version.
10  *
11  */
12 
13 #include <haproxy/api.h>
14 #include <haproxy/connection.h>
15 #include <haproxy/global.h>
16 #include <haproxy/http.h>
17 #include <haproxy/listener.h>
18 #include <haproxy/log.h>
19 #include <haproxy/pool.h>
20 #include <haproxy/proxy.h>
21 #include <haproxy/session.h>
22 #include <haproxy/tcp_rules.h>
23 #include <haproxy/vars.h>
24 
25 
26 DECLARE_POOL(pool_head_session, "session", sizeof(struct session));
27 DECLARE_POOL(pool_head_sess_srv_list, "session server list",
28 		sizeof(struct sess_srv_list));
29 
30 int conn_complete_session(struct connection *conn);
31 static struct task *session_expire_embryonic(struct task *t, void *context, unsigned short state);
32 
33 /* Create a a new session and assign it to frontend <fe>, listener <li>,
34  * origin <origin>, set the current date and clear the stick counters pointers.
35  * Returns the session upon success or NULL. The session may be released using
36  * session_free(). Note: <li> may be NULL.
37  */
session_new(struct proxy * fe,struct listener * li,enum obj_type * origin)38 struct session *session_new(struct proxy *fe, struct listener *li, enum obj_type *origin)
39 {
40 	struct session *sess;
41 
42 	sess = pool_alloc(pool_head_session);
43 	if (sess) {
44 		sess->listener = li;
45 		sess->fe = fe;
46 		sess->origin = origin;
47 		sess->accept_date = date; /* user-visible date for logging */
48 		sess->tv_accept   = now;  /* corrected date for internal use */
49 		memset(sess->stkctr, 0, sizeof(sess->stkctr));
50 		vars_init(&sess->vars, SCOPE_SESS);
51 		sess->task = NULL;
52 		sess->t_handshake = -1; /* handshake not done yet */
53 		_HA_ATOMIC_ADD(&totalconn, 1);
54 		_HA_ATOMIC_ADD(&jobs, 1);
55 		LIST_INIT(&sess->srv_list);
56 		sess->idle_conns = 0;
57 		sess->flags = SESS_FL_NONE;
58 	}
59 	return sess;
60 }
61 
session_free(struct session * sess)62 void session_free(struct session *sess)
63 {
64 	struct connection *conn, *conn_back;
65 	struct sess_srv_list *srv_list, *srv_list_back;
66 
67 	if (sess->listener)
68 		listener_release(sess->listener);
69 	session_store_counters(sess);
70 	vars_prune_per_sess(&sess->vars);
71 	conn = objt_conn(sess->origin);
72 	if (conn != NULL && conn->mux)
73 		conn->mux->destroy(conn->ctx);
74 	list_for_each_entry_safe(srv_list, srv_list_back, &sess->srv_list, srv_list) {
75 		list_for_each_entry_safe(conn, conn_back, &srv_list->conn_list, session_list) {
76 			LIST_DEL_INIT(&conn->session_list);
77 			if (conn->mux) {
78 				conn->owner = NULL;
79 				conn->flags &= ~CO_FL_SESS_IDLE;
80 				conn->mux->destroy(conn->ctx);
81 			} else {
82 				/* We have a connection, but not yet an associated mux.
83 				 * So destroy it now.
84 				 */
85 				conn_stop_tracking(conn);
86 				conn_full_close(conn);
87 				conn_free(conn);
88 			}
89 		}
90 		pool_free(pool_head_sess_srv_list, srv_list);
91 	}
92 	pool_free(pool_head_session, sess);
93 	_HA_ATOMIC_SUB(&jobs, 1);
94 }
95 
96 /* callback used from the connection/mux layer to notify that a connection is
97  * going to be released.
98  */
conn_session_free(struct connection * conn)99 void conn_session_free(struct connection *conn)
100 {
101 	session_free(conn->owner);
102 	conn->owner = NULL;
103 }
104 
105 /* count a new session to keep frontend, listener and track stats up to date */
session_count_new(struct session * sess)106 static void session_count_new(struct session *sess)
107 {
108 	struct stkctr *stkctr;
109 	void *ptr;
110 	int i;
111 
112 	proxy_inc_fe_sess_ctr(sess->listener, sess->fe);
113 
114 	for (i = 0; i < MAX_SESS_STKCTR; i++) {
115 		stkctr = &sess->stkctr[i];
116 		if (!stkctr_entry(stkctr))
117 			continue;
118 
119 		ptr = stktable_data_ptr(stkctr->table, stkctr_entry(stkctr), STKTABLE_DT_SESS_CNT);
120 		if (ptr)
121 			HA_ATOMIC_ADD(&stktable_data_cast(ptr, sess_cnt), 1);
122 
123 		ptr = stktable_data_ptr(stkctr->table, stkctr_entry(stkctr), STKTABLE_DT_SESS_RATE);
124 		if (ptr)
125 			update_freq_ctr_period(&stktable_data_cast(ptr, sess_rate),
126 					       stkctr->table->data_arg[STKTABLE_DT_SESS_RATE].u, 1);
127 	}
128 }
129 
130 /* This function is called from the protocol layer accept() in order to
131  * instantiate a new session on behalf of a given listener and frontend. It
132  * returns a positive value upon success, 0 if the connection can be ignored,
133  * or a negative value upon critical failure. The accepted connection is
134  * closed if we return <= 0. If no handshake is needed, it immediately tries
135  * to instantiate a new stream. The connection must already have been filled
136  * with the incoming connection handle (a fd), a target (the listener) and a
137  * source address.
138  */
session_accept_fd(struct connection * cli_conn)139 int session_accept_fd(struct connection *cli_conn)
140 {
141 	struct listener *l = __objt_listener(cli_conn->target);
142 	struct proxy *p = l->bind_conf->frontend;
143 	int cfd = cli_conn->handle.fd;
144 	struct session *sess;
145 	int ret;
146 
147 	ret = -1; /* assume unrecoverable error by default */
148 
149 	cli_conn->proxy_netns = l->rx.settings->netns;
150 
151 	conn_prepare(cli_conn, l->rx.proto, l->bind_conf->xprt);
152 	conn_ctrl_init(cli_conn);
153 
154 	/* wait for a PROXY protocol header */
155 	if (l->options & LI_O_ACC_PROXY)
156 		cli_conn->flags |= CO_FL_ACCEPT_PROXY;
157 
158 	/* wait for a NetScaler client IP insertion protocol header */
159 	if (l->options & LI_O_ACC_CIP)
160 		cli_conn->flags |= CO_FL_ACCEPT_CIP;
161 
162 	if (conn_xprt_init(cli_conn) < 0)
163 		goto out_free_conn;
164 
165 	/* Add the handshake pseudo-XPRT */
166 	if (cli_conn->flags & (CO_FL_ACCEPT_PROXY | CO_FL_ACCEPT_CIP)) {
167 		if (xprt_add_hs(cli_conn) != 0)
168 			goto out_free_conn;
169 	}
170 	sess = session_new(p, l, &cli_conn->obj_type);
171 	if (!sess)
172 		goto out_free_conn;
173 
174 	conn_set_owner(cli_conn, sess, NULL);
175 
176 	/* now evaluate the tcp-request layer4 rules. We only need a session
177 	 * and no stream for these rules.
178 	 */
179 	if ((l->options & LI_O_TCP_L4_RULES) && !tcp_exec_l4_rules(sess)) {
180 		/* let's do a no-linger now to close with a single RST. */
181 		setsockopt(cfd, SOL_SOCKET, SO_LINGER, (struct linger *) &nolinger, sizeof(struct linger));
182 		ret = 0; /* successful termination */
183 		goto out_free_sess;
184 	}
185 
186 	/* Adjust some socket options */
187 	if (l->rx.addr.ss_family == AF_INET || l->rx.addr.ss_family == AF_INET6) {
188 		setsockopt(cfd, IPPROTO_TCP, TCP_NODELAY, (char *) &one, sizeof(one));
189 
190 		if (p->options & PR_O_TCP_CLI_KA) {
191 			setsockopt(cfd, SOL_SOCKET, SO_KEEPALIVE, (char *) &one, sizeof(one));
192 
193 #ifdef TCP_KEEPCNT
194 			if (p->clitcpka_cnt)
195 				setsockopt(cfd, IPPROTO_TCP, TCP_KEEPCNT, &p->clitcpka_cnt, sizeof(p->clitcpka_cnt));
196 #endif
197 
198 #ifdef TCP_KEEPIDLE
199 			if (p->clitcpka_idle)
200 				setsockopt(cfd, IPPROTO_TCP, TCP_KEEPIDLE, &p->clitcpka_idle, sizeof(p->clitcpka_idle));
201 #endif
202 
203 #ifdef TCP_KEEPINTVL
204 			if (p->clitcpka_intvl)
205 				setsockopt(cfd, IPPROTO_TCP, TCP_KEEPINTVL, &p->clitcpka_intvl, sizeof(p->clitcpka_intvl));
206 #endif
207 		}
208 
209 		if (p->options & PR_O_TCP_NOLING)
210 			fdtab[cfd].linger_risk = 1;
211 
212 #if defined(TCP_MAXSEG)
213 		if (l->maxseg < 0) {
214 			/* we just want to reduce the current MSS by that value */
215 			int mss;
216 			socklen_t mss_len = sizeof(mss);
217 			if (getsockopt(cfd, IPPROTO_TCP, TCP_MAXSEG, &mss, &mss_len) == 0) {
218 				mss += l->maxseg; /* remember, it's < 0 */
219 				setsockopt(cfd, IPPROTO_TCP, TCP_MAXSEG, &mss, sizeof(mss));
220 			}
221 		}
222 #endif
223 	}
224 
225 	if (global.tune.client_sndbuf)
226 		setsockopt(cfd, SOL_SOCKET, SO_SNDBUF, &global.tune.client_sndbuf, sizeof(global.tune.client_sndbuf));
227 
228 	if (global.tune.client_rcvbuf)
229 		setsockopt(cfd, SOL_SOCKET, SO_RCVBUF, &global.tune.client_rcvbuf, sizeof(global.tune.client_rcvbuf));
230 
231 	/* OK, now either we have a pending handshake to execute with and then
232 	 * we must return to the I/O layer, or we can proceed with the end of
233 	 * the stream initialization. In case of handshake, we also set the I/O
234 	 * timeout to the frontend's client timeout and register a task in the
235 	 * session for this purpose. The connection's owner is left to the
236 	 * session during this period.
237 	 *
238 	 * At this point we set the relation between sess/task/conn this way :
239 	 *
240 	 *                   +----------------- task
241 	 *                   |                    |
242 	 *          orig -- sess <-- context      |
243 	 *           |       ^           |        |
244 	 *           v       |           |        |
245 	 *          conn -- owner ---> task <-----+
246 	 */
247 	if (cli_conn->flags & (CO_FL_WAIT_XPRT | CO_FL_EARLY_SSL_HS)) {
248 		if (unlikely((sess->task = task_new(tid_bit)) == NULL))
249 			goto out_free_sess;
250 
251 		sess->task->context = sess;
252 		sess->task->nice    = l->nice;
253 		sess->task->process = session_expire_embryonic;
254 		sess->task->expire  = tick_add_ifset(now_ms, p->timeout.client);
255 		task_queue(sess->task);
256 		return 1;
257 	}
258 
259 	/* OK let's complete stream initialization since there is no handshake */
260 	if (conn_complete_session(cli_conn) >= 0)
261 		return 1;
262 
263 	/* if we reach here we have deliberately decided not to keep this
264 	 * session (e.g. tcp-request rule), so that's not an error we should
265 	 * try to protect against.
266 	 */
267 	ret = 0;
268 
269 	/* error unrolling */
270  out_free_sess:
271 	 /* prevent call to listener_release during session_free. It will be
272 	  * done below, for all errors. */
273 	sess->listener = NULL;
274 	session_free(sess);
275 
276  out_free_conn:
277 	if (ret < 0 && l->bind_conf->xprt == xprt_get(XPRT_RAW) &&
278 	    p->mode == PR_MODE_HTTP && l->bind_conf->mux_proto == NULL) {
279 		/* critical error, no more memory, try to emit a 500 response */
280 		send(cfd, http_err_msgs[HTTP_ERR_500], strlen(http_err_msgs[HTTP_ERR_500]),
281 		     MSG_DONTWAIT|MSG_NOSIGNAL);
282 	}
283 
284 	conn_stop_tracking(cli_conn);
285 	conn_full_close(cli_conn);
286 	conn_free(cli_conn);
287 	listener_release(l);
288 	return ret;
289 }
290 
291 
292 /* prepare the trash with a log prefix for session <sess>. It only works with
293  * embryonic sessions based on a real connection. This function requires that
294  * at sess->origin points to the incoming connection.
295  */
session_prepare_log_prefix(struct session * sess)296 static void session_prepare_log_prefix(struct session *sess)
297 {
298 	struct tm tm;
299 	char pn[INET6_ADDRSTRLEN];
300 	int ret;
301 	char *end;
302 	struct connection *cli_conn = __objt_conn(sess->origin);
303 
304 	ret = conn_get_src(cli_conn) ? addr_to_str(cli_conn->src, pn, sizeof(pn)) : 0;
305 	if (ret <= 0)
306 		chunk_printf(&trash, "unknown [");
307 	else if (ret == AF_UNIX)
308 		chunk_printf(&trash, "%s:%d [", pn, sess->listener->luid);
309 	else
310 		chunk_printf(&trash, "%s:%d [", pn, get_host_port(cli_conn->src));
311 
312 	get_localtime(sess->accept_date.tv_sec, &tm);
313 	end = date2str_log(trash.area + trash.data, &tm, &(sess->accept_date),
314 		           trash.size - trash.data);
315 	trash.data = end - trash.area;
316 	if (sess->listener->name)
317 		chunk_appendf(&trash, "] %s/%s", sess->fe->id, sess->listener->name);
318 	else
319 		chunk_appendf(&trash, "] %s/%d", sess->fe->id, sess->listener->luid);
320 }
321 
322 /* This function kills an existing embryonic session. It stops the connection's
323  * transport layer, releases assigned resources, resumes the listener if it was
324  * disabled and finally kills the file descriptor. This function requires that
325  * sess->origin points to the incoming connection.
326  */
session_kill_embryonic(struct session * sess,unsigned short state)327 static void session_kill_embryonic(struct session *sess, unsigned short state)
328 {
329 	int level = LOG_INFO;
330 	struct connection *conn = __objt_conn(sess->origin);
331 	struct task *task = sess->task;
332 	unsigned int log = sess->fe->to_log;
333 	const char *err_msg;
334 
335 	if (sess->fe->options2 & PR_O2_LOGERRORS)
336 		level = LOG_ERR;
337 
338 	if (log && (sess->fe->options & PR_O_NULLNOLOG)) {
339 		/* with "option dontlognull", we don't log connections with no transfer */
340 		if (!conn->err_code ||
341 		    conn->err_code == CO_ER_PRX_EMPTY || conn->err_code == CO_ER_PRX_ABORT ||
342 		    conn->err_code == CO_ER_CIP_EMPTY || conn->err_code == CO_ER_CIP_ABORT ||
343 		    conn->err_code == CO_ER_SSL_EMPTY || conn->err_code == CO_ER_SSL_ABORT)
344 			log = 0;
345 	}
346 
347 	if (log) {
348 		if (!conn->err_code && (state & TASK_WOKEN_TIMER)) {
349 			if (conn->flags & CO_FL_ACCEPT_PROXY)
350 				conn->err_code = CO_ER_PRX_TIMEOUT;
351 			else if (conn->flags & CO_FL_ACCEPT_CIP)
352 				conn->err_code = CO_ER_CIP_TIMEOUT;
353 			else if (conn->flags & CO_FL_SSL_WAIT_HS)
354 				conn->err_code = CO_ER_SSL_TIMEOUT;
355 		}
356 
357 		session_prepare_log_prefix(sess);
358 		err_msg = conn_err_code_str(conn);
359 		if (err_msg)
360 			send_log(sess->fe, level, "%s: %s\n", trash.area,
361 				 err_msg);
362 		else
363 			send_log(sess->fe, level, "%s: unknown connection error (code=%d flags=%08x)\n",
364 				 trash.area, conn->err_code, conn->flags);
365 	}
366 
367 	/* kill the connection now */
368 	conn_stop_tracking(conn);
369 	conn_full_close(conn);
370 	conn_free(conn);
371 	sess->origin = NULL;
372 
373 	task_destroy(task);
374 	session_free(sess);
375 }
376 
377 /* Manages the embryonic session timeout. It is only called when the timeout
378  * strikes and performs the required cleanup.
379  */
session_expire_embryonic(struct task * t,void * context,unsigned short state)380 static struct task *session_expire_embryonic(struct task *t, void *context, unsigned short state)
381 {
382 	struct session *sess = context;
383 
384 	if (!(state & TASK_WOKEN_TIMER))
385 		return t;
386 
387 	session_kill_embryonic(sess, state);
388 	return NULL;
389 }
390 
391 /* Finish initializing a session from a connection, or kills it if the
392  * connection shows and error. Returns <0 if the connection was killed. It may
393  * be called either asynchronously when ssl handshake is done with an embryonic
394  * session, or synchronously to finalize the session. The distinction is made
395  * on sess->task which is only set in the embryonic session case.
396  */
conn_complete_session(struct connection * conn)397 int conn_complete_session(struct connection *conn)
398 {
399 	struct session *sess = conn->owner;
400 
401 	sess->t_handshake = tv_ms_elapsed(&sess->tv_accept, &now);
402 
403 	if (conn->flags & CO_FL_ERROR)
404 		goto fail;
405 
406 	/* if logs require transport layer information, note it on the connection */
407 	if (sess->fe->to_log & LW_XPRT)
408 		conn->flags |= CO_FL_XPRT_TRACKED;
409 
410 	/* we may have some tcp-request-session rules */
411 	if ((sess->listener->options & LI_O_TCP_L5_RULES) && !tcp_exec_l5_rules(sess))
412 		goto fail;
413 
414 	session_count_new(sess);
415 	if (conn_install_mux_fe(conn, NULL) < 0)
416 		goto fail;
417 
418 	/* the embryonic session's task is not needed anymore */
419 	task_destroy(sess->task);
420 	sess->task = NULL;
421 	conn_set_owner(conn, sess, conn_session_free);
422 
423 	return 0;
424 
425  fail:
426 	if (sess->task)
427 		session_kill_embryonic(sess, 0);
428 	return -1;
429 }
430 
431 /*
432  * Local variables:
433  *  c-indent-level: 8
434  *  c-basic-offset: 8
435  * End:
436  */
437