blob: fdb24045b5e69d5b382f417e6a4be4e73a84b8fc [file] [log] [blame]
Willy Tarreaub1ec8c42015-04-03 13:53:24 +02001/*
Willy Tarreau9903f0e2015-04-04 18:50:31 +02002 * Session management functions.
Willy Tarreaub1ec8c42015-04-03 13:53:24 +02003 *
Willy Tarreau9903f0e2015-04-04 18:50:31 +02004 * Copyright 2000-2015 Willy Tarreau <w@1wt.eu>
Willy Tarreaub1ec8c42015-04-03 13:53:24 +02005 *
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 <common/config.h>
14#include <common/buffer.h>
15#include <common/debug.h>
16#include <common/memory.h>
17
18#include <types/global.h>
19#include <types/session.h>
20
Willy Tarreau9903f0e2015-04-04 18:50:31 +020021#include <proto/connection.h>
22#include <proto/listener.h>
23#include <proto/log.h>
24#include <proto/proto_http.h>
25#include <proto/proto_tcp.h>
26#include <proto/proxy.h>
27#include <proto/raw_sock.h>
Willy Tarreaubb2ef122015-04-04 16:31:16 +020028#include <proto/session.h>
Willy Tarreau9903f0e2015-04-04 18:50:31 +020029#include <proto/stream.h>
Willy Tarreauebcd4842015-06-19 11:59:02 +020030#include <proto/vars.h>
Willy Tarreaubb2ef122015-04-04 16:31:16 +020031
Willy Tarreaub1ec8c42015-04-03 13:53:24 +020032struct pool_head *pool2_session;
33
Willy Tarreau9903f0e2015-04-04 18:50:31 +020034static int conn_complete_session(struct connection *conn);
35static int conn_update_session(struct connection *conn);
36static struct task *session_expire_embryonic(struct task *t);
37
38/* data layer callbacks for an embryonic stream */
39struct data_cb sess_conn_cb = {
40 .recv = NULL,
41 .send = NULL,
42 .wake = conn_update_session,
43 .init = conn_complete_session,
44};
45
Willy Tarreauc38f71c2015-04-05 00:38:48 +020046/* Create a a new session and assign it to frontend <fe>, listener <li>,
47 * origin <origin>, set the current date and clear the stick counters pointers.
48 * Returns the session upon success or NULL. The session may be released using
49 * session_free().
50 */
51struct session *session_new(struct proxy *fe, struct listener *li, enum obj_type *origin)
52{
53 struct session *sess;
54
55 sess = pool_alloc2(pool2_session);
56 if (sess) {
57 sess->listener = li;
58 sess->fe = fe;
59 sess->origin = origin;
60 sess->accept_date = date; /* user-visible date for logging */
61 sess->tv_accept = now; /* corrected date for internal use */
62 memset(sess->stkctr, 0, sizeof(sess->stkctr));
Willy Tarreauebcd4842015-06-19 11:59:02 +020063 vars_init(&sess->vars, SCOPE_SESS);
Willy Tarreauc38f71c2015-04-05 00:38:48 +020064 }
65 return sess;
66}
67
Willy Tarreau11c36242015-04-04 15:54:03 +020068void session_free(struct session *sess)
69{
Willy Tarreaubb2ef122015-04-04 16:31:16 +020070 session_store_counters(sess);
Willy Tarreauebcd4842015-06-19 11:59:02 +020071 vars_prune_per_sess(&sess->vars);
Willy Tarreau11c36242015-04-04 15:54:03 +020072 pool_free2(pool2_session, sess);
73}
74
Willy Tarreaub1ec8c42015-04-03 13:53:24 +020075/* perform minimal intializations, report 0 in case of error, 1 if OK. */
76int init_session()
77{
78 pool2_session = create_pool("session", sizeof(struct session), MEM_F_SHARED);
79 return pool2_session != NULL;
80}
81
Willy Tarreau042cd752015-04-08 18:10:49 +020082/* count a new session to keep frontend, listener and track stats up to date */
83static void session_count_new(struct session *sess)
84{
85 struct stkctr *stkctr;
86 void *ptr;
87 int i;
88
89 proxy_inc_fe_sess_ctr(sess->listener, sess->fe);
90
91 for (i = 0; i < MAX_SESS_STKCTR; i++) {
92 stkctr = &sess->stkctr[i];
93 if (!stkctr_entry(stkctr))
94 continue;
95
96 ptr = stktable_data_ptr(stkctr->table, stkctr_entry(stkctr), STKTABLE_DT_SESS_CNT);
97 if (ptr)
98 stktable_data_cast(ptr, sess_cnt)++;
99
100 ptr = stktable_data_ptr(stkctr->table, stkctr_entry(stkctr), STKTABLE_DT_SESS_RATE);
101 if (ptr)
102 update_freq_ctr_period(&stktable_data_cast(ptr, sess_rate),
103 stkctr->table->data_arg[STKTABLE_DT_SESS_RATE].u, 1);
104 }
105}
106
Willy Tarreau9903f0e2015-04-04 18:50:31 +0200107/* This function is called from the protocol layer accept() in order to
108 * instanciate a new session on behalf of a given listener and frontend. It
109 * returns a positive value upon success, 0 if the connection can be ignored,
110 * or a negative value upon critical failure. The accepted file descriptor is
111 * closed if we return <= 0. If no handshake is needed, it immediately tries
112 * to instanciate a new stream.
113 */
114int session_accept_fd(struct listener *l, int cfd, struct sockaddr_storage *addr)
115{
116 struct connection *cli_conn;
117 struct proxy *p = l->frontend;
118 struct session *sess;
Willy Tarreaud1769b82015-04-06 00:25:48 +0200119 struct stream *strm;
Willy Tarreau9903f0e2015-04-04 18:50:31 +0200120 struct task *t;
121 int ret;
122
123
124 ret = -1; /* assume unrecoverable error by default */
125
126 if (unlikely((cli_conn = conn_new()) == NULL))
127 goto out_close;
128
129 conn_prepare(cli_conn, l->proto, l->xprt);
130
131 cli_conn->t.sock.fd = cfd;
132 cli_conn->addr.from = *addr;
133 cli_conn->flags |= CO_FL_ADDR_FROM_SET;
134 cli_conn->target = &l->obj_type;
135 cli_conn->proxy_netns = l->netns;
136
137 conn_ctrl_init(cli_conn);
138
139 /* wait for a PROXY protocol header */
140 if (l->options & LI_O_ACC_PROXY) {
141 cli_conn->flags |= CO_FL_ACCEPT_PROXY;
142 conn_sock_want_recv(cli_conn);
143 }
144
145 conn_data_want_recv(cli_conn);
146 if (conn_xprt_init(cli_conn) < 0)
147 goto out_free_conn;
148
Willy Tarreau64beab22015-04-05 00:39:16 +0200149 sess = session_new(p, l, &cli_conn->obj_type);
Willy Tarreau9903f0e2015-04-04 18:50:31 +0200150 if (!sess)
151 goto out_free_conn;
152
153 p->feconn++;
154 /* This session was accepted, count it now */
155 if (p->feconn > p->fe_counters.conn_max)
156 p->fe_counters.conn_max = p->feconn;
157
158 proxy_inc_fe_conn_ctr(l, p);
159
Willy Tarreau9903f0e2015-04-04 18:50:31 +0200160 /* now evaluate the tcp-request layer4 rules. We only need a session
161 * and no stream for these rules.
162 */
163 if ((l->options & LI_O_TCP_RULES) && !tcp_exec_req_rules(sess)) {
164 /* let's do a no-linger now to close with a single RST. */
165 setsockopt(cfd, SOL_SOCKET, SO_LINGER, (struct linger *) &nolinger, sizeof(struct linger));
166 ret = 0; /* successful termination */
167 goto out_free_sess;
168 }
169
170 /* monitor-net and health mode are processed immediately after TCP
171 * connection rules. This way it's possible to block them, but they
172 * never use the lower data layers, they send directly over the socket,
173 * as they were designed for. We first flush the socket receive buffer
174 * in order to avoid emission of an RST by the system. We ignore any
175 * error.
176 */
177 if (unlikely((p->mode == PR_MODE_HEALTH) ||
178 ((l->options & LI_O_CHK_MONNET) &&
179 addr->ss_family == AF_INET &&
180 (((struct sockaddr_in *)addr)->sin_addr.s_addr & p->mon_mask.s_addr) == p->mon_net.s_addr))) {
181 /* we have 4 possibilities here :
182 * - HTTP mode, from monitoring address => send "HTTP/1.0 200 OK"
183 * - HEALTH mode with HTTP check => send "HTTP/1.0 200 OK"
184 * - HEALTH mode without HTTP check => just send "OK"
185 * - TCP mode from monitoring address => just close
186 */
187 if (l->proto->drain)
188 l->proto->drain(cfd);
189 if (p->mode == PR_MODE_HTTP ||
190 (p->mode == PR_MODE_HEALTH && (p->options2 & PR_O2_CHK_ANY) == PR_O2_HTTP_CHK))
191 send(cfd, "HTTP/1.0 200 OK\r\n\r\n", 19, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_MORE);
192 else if (p->mode == PR_MODE_HEALTH)
193 send(cfd, "OK\n", 3, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_MORE);
194 ret = 0;
195 goto out_free_sess;
196 }
197
Willy Tarreauf9d1bc62015-04-05 17:56:47 +0200198 /* Adjust some socket options */
199 if (l->addr.ss_family == AF_INET || l->addr.ss_family == AF_INET6) {
200 setsockopt(cfd, IPPROTO_TCP, TCP_NODELAY, (char *) &one, sizeof(one));
201
202 if (p->options & PR_O_TCP_CLI_KA)
203 setsockopt(cfd, SOL_SOCKET, SO_KEEPALIVE, (char *) &one, sizeof(one));
204
205 if (p->options & PR_O_TCP_NOLING)
206 fdtab[cfd].linger_risk = 1;
207
208#if defined(TCP_MAXSEG)
209 if (l->maxseg < 0) {
210 /* we just want to reduce the current MSS by that value */
211 int mss;
212 socklen_t mss_len = sizeof(mss);
213 if (getsockopt(cfd, IPPROTO_TCP, TCP_MAXSEG, &mss, &mss_len) == 0) {
214 mss += l->maxseg; /* remember, it's < 0 */
215 setsockopt(cfd, IPPROTO_TCP, TCP_MAXSEG, &mss, sizeof(mss));
216 }
217 }
218#endif
219 }
220
221 if (global.tune.client_sndbuf)
222 setsockopt(cfd, SOL_SOCKET, SO_SNDBUF, &global.tune.client_sndbuf, sizeof(global.tune.client_sndbuf));
223
224 if (global.tune.client_rcvbuf)
225 setsockopt(cfd, SOL_SOCKET, SO_RCVBUF, &global.tune.client_rcvbuf, sizeof(global.tune.client_rcvbuf));
226
Willy Tarreau9903f0e2015-04-04 18:50:31 +0200227 if (unlikely((t = task_new()) == NULL))
228 goto out_free_sess;
229
230 t->context = sess;
231 t->nice = l->nice;
232
233 /* OK, now either we have a pending handshake to execute with and
234 * then we must return to the I/O layer, or we can proceed with the
235 * end of the stream initialization. In case of handshake, we also
236 * set the I/O timeout to the frontend's client timeout.
237 *
238 * At this point we set the relation between sess/task/conn this way :
239 *
240 * orig -- sess <-- context
241 * | |
242 * v |
243 * conn -- owner ---> task
244 */
245 if (cli_conn->flags & CO_FL_HANDSHAKE) {
246 conn_attach(cli_conn, t, &sess_conn_cb);
247 t->process = session_expire_embryonic;
248 t->expire = tick_add_ifset(now_ms, p->timeout.client);
249 task_queue(t);
250 cli_conn->flags |= CO_FL_INIT_DATA | CO_FL_WAKE_DATA;
251 return 1;
252 }
253
Willy Tarreau18b95a42015-04-05 01:04:01 +0200254 /* OK let's complete stream initialization since there is no handshake */
255 cli_conn->flags |= CO_FL_CONNECTED;
Willy Tarreau042cd752015-04-08 18:10:49 +0200256
Willy Tarreau678be622015-04-08 18:18:15 +0200257 /* we want the connection handler to notify the stream interface about updates. */
258 cli_conn->flags |= CO_FL_WAKE_DATA;
259
260 /* if logs require transport layer information, note it on the connection */
261 if (sess->fe->to_log & LW_XPRT)
262 cli_conn->flags |= CO_FL_XPRT_TRACKED;
263
Willy Tarreau042cd752015-04-08 18:10:49 +0200264 session_count_new(sess);
Willy Tarreau73b65ac2015-04-08 18:26:29 +0200265 strm = stream_new(sess, t, &cli_conn->obj_type);
Willy Tarreaud1769b82015-04-06 00:25:48 +0200266 if (!strm)
267 goto out_free_task;
Willy Tarreau9903f0e2015-04-04 18:50:31 +0200268
Christopher Fauletd7c91962015-04-30 11:48:27 +0200269 strm->target = sess->listener->default_target;
270 strm->req.analysers |= sess->listener->analysers;
271
Willy Tarreaud1769b82015-04-06 00:25:48 +0200272 return 1;
273
274 out_free_task:
Willy Tarreau9903f0e2015-04-04 18:50:31 +0200275 task_free(t);
276 out_free_sess:
277 p->feconn--;
278 session_free(sess);
279 out_free_conn:
280 cli_conn->flags &= ~CO_FL_XPRT_TRACKED;
281 conn_xprt_close(cli_conn);
282 conn_free(cli_conn);
283 out_close:
284 if (ret < 0 && l->xprt == &raw_sock && p->mode == PR_MODE_HTTP) {
285 /* critical error, no more memory, try to emit a 500 response */
286 struct chunk *err_msg = &p->errmsg[HTTP_ERR_500];
287 if (!err_msg->str)
288 err_msg = &http_err_chunks[HTTP_ERR_500];
289 send(cfd, err_msg->str, err_msg->len, MSG_DONTWAIT|MSG_NOSIGNAL);
290 }
291
292 if (fdtab[cfd].owner)
293 fd_delete(cfd);
294 else
295 close(cfd);
296 return ret;
297}
298
299
300/* prepare the trash with a log prefix for session <sess>. It only works with
301 * embryonic sessions based on a real connection. This function requires that
302 * at sess->origin points to the incoming connection.
303 */
304static void session_prepare_log_prefix(struct session *sess)
305{
306 struct tm tm;
307 char pn[INET6_ADDRSTRLEN];
308 int ret;
309 char *end;
310 struct connection *cli_conn = __objt_conn(sess->origin);
311
312 ret = addr_to_str(&cli_conn->addr.from, pn, sizeof(pn));
313 if (ret <= 0)
314 chunk_printf(&trash, "unknown [");
315 else if (ret == AF_UNIX)
316 chunk_printf(&trash, "%s:%d [", pn, sess->listener->luid);
317 else
318 chunk_printf(&trash, "%s:%d [", pn, get_host_port(&cli_conn->addr.from));
319
320 get_localtime(sess->accept_date.tv_sec, &tm);
321 end = date2str_log(trash.str + trash.len, &tm, &(sess->accept_date), trash.size - trash.len);
322 trash.len = end - trash.str;
323 if (sess->listener->name)
324 chunk_appendf(&trash, "] %s/%s", sess->fe->id, sess->listener->name);
325 else
326 chunk_appendf(&trash, "] %s/%d", sess->fe->id, sess->listener->luid);
327}
328
329/* This function kills an existing embryonic session. It stops the connection's
330 * transport layer, releases assigned resources, resumes the listener if it was
331 * disabled and finally kills the file descriptor. This function requires that
332 * sess->origin points to the incoming connection.
333 */
334static void session_kill_embryonic(struct session *sess)
335{
336 int level = LOG_INFO;
337 struct connection *conn = __objt_conn(sess->origin);
338 struct task *task = conn->owner;
339 unsigned int log = sess->fe->to_log;
340 const char *err_msg;
341
342 if (sess->fe->options2 & PR_O2_LOGERRORS)
343 level = LOG_ERR;
344
345 if (log && (sess->fe->options & PR_O_NULLNOLOG)) {
346 /* with "option dontlognull", we don't log connections with no transfer */
347 if (!conn->err_code ||
348 conn->err_code == CO_ER_PRX_EMPTY || conn->err_code == CO_ER_PRX_ABORT ||
349 conn->err_code == CO_ER_SSL_EMPTY || conn->err_code == CO_ER_SSL_ABORT)
350 log = 0;
351 }
352
353 if (log) {
354 if (!conn->err_code && (task->state & TASK_WOKEN_TIMER)) {
355 if (conn->flags & CO_FL_ACCEPT_PROXY)
356 conn->err_code = CO_ER_PRX_TIMEOUT;
357 else if (conn->flags & CO_FL_SSL_WAIT_HS)
358 conn->err_code = CO_ER_SSL_TIMEOUT;
359 }
360
361 session_prepare_log_prefix(sess);
362 err_msg = conn_err_code_str(conn);
363 if (err_msg)
364 send_log(sess->fe, level, "%s: %s\n", trash.str, err_msg);
365 else
366 send_log(sess->fe, level, "%s: unknown connection error (code=%d flags=%08x)\n",
367 trash.str, conn->err_code, conn->flags);
368 }
369
370 /* kill the connection now */
371 conn_force_close(conn);
372 conn_free(conn);
373
374 sess->fe->feconn--;
375
376 if (!(sess->listener->options & LI_O_UNLIMITED))
377 actconn--;
378 jobs--;
379 sess->listener->nbconn--;
380 if (sess->listener->state == LI_FULL)
381 resume_listener(sess->listener);
382
383 /* Dequeues all of the listeners waiting for a resource */
384 if (!LIST_ISEMPTY(&global_listener_queue))
385 dequeue_all_listeners(&global_listener_queue);
386
387 if (!LIST_ISEMPTY(&sess->fe->listener_queue) &&
388 (!sess->fe->fe_sps_lim || freq_ctr_remain(&sess->fe->fe_sess_per_sec, sess->fe->fe_sps_lim, 0) > 0))
389 dequeue_all_listeners(&sess->fe->listener_queue);
390
391 task_delete(task);
392 task_free(task);
393 session_free(sess);
394}
395
396/* Manages the embryonic session timeout. It is only called when the timeout
397 * strikes and performs the required cleanup.
398 */
399static struct task *session_expire_embryonic(struct task *t)
400{
401 struct session *sess = t->context;
402
403 if (!(t->state & TASK_WOKEN_TIMER))
404 return t;
405
406 session_kill_embryonic(sess);
407 return NULL;
408}
409
410/* Finish initializing a session from a connection, or kills it if the
411 * connection shows and error. Returns <0 if the connection was killed.
412 */
413static int conn_complete_session(struct connection *conn)
414{
415 struct task *task = conn->owner;
416 struct session *sess = task->context;
Willy Tarreaud1769b82015-04-06 00:25:48 +0200417 struct stream *strm;
Willy Tarreau9903f0e2015-04-04 18:50:31 +0200418
Willy Tarreaud1769b82015-04-06 00:25:48 +0200419 if (conn->flags & CO_FL_ERROR)
420 goto fail;
421
Willy Tarreau678be622015-04-08 18:18:15 +0200422 /* we want the connection handler to notify the stream interface about updates. */
423 conn->flags |= CO_FL_WAKE_DATA;
424
425 /* if logs require transport layer information, note it on the connection */
426 if (sess->fe->to_log & LW_XPRT)
427 conn->flags |= CO_FL_XPRT_TRACKED;
428
Willy Tarreau042cd752015-04-08 18:10:49 +0200429 session_count_new(sess);
Willy Tarreaud1769b82015-04-06 00:25:48 +0200430 task->process = sess->listener->handler;
Willy Tarreau73b65ac2015-04-08 18:26:29 +0200431 strm = stream_new(sess, task, &conn->obj_type);
Willy Tarreaud1769b82015-04-06 00:25:48 +0200432 if (!strm)
433 goto fail;
434
Christopher Fauletd7c91962015-04-30 11:48:27 +0200435 strm->target = sess->listener->default_target;
436 strm->req.analysers |= sess->listener->analysers;
Willy Tarreaud1769b82015-04-06 00:25:48 +0200437 conn->flags &= ~CO_FL_INIT_DATA;
Willy Tarreau678be622015-04-08 18:18:15 +0200438
Willy Tarreaud1769b82015-04-06 00:25:48 +0200439 return 0;
Willy Tarreau9903f0e2015-04-04 18:50:31 +0200440
Willy Tarreaud1769b82015-04-06 00:25:48 +0200441 fail:
Willy Tarreau9903f0e2015-04-04 18:50:31 +0200442 session_kill_embryonic(sess);
443 return -1;
444}
445
446/* Update a session status. The connection is killed in case of
447 * error, and <0 will be returned. Otherwise it does nothing.
448 */
449static int conn_update_session(struct connection *conn)
450{
451 struct task *task = conn->owner;
452 struct session *sess = task->context;
453
454 if (conn->flags & CO_FL_ERROR) {
455 session_kill_embryonic(sess);
456 return -1;
457 }
458 return 0;
459}
460
Willy Tarreaub1ec8c42015-04-03 13:53:24 +0200461/*
462 * Local variables:
463 * c-indent-level: 8
464 * c-basic-offset: 8
465 * End:
466 */