worker.c 52.8 KB
Newer Older
1
/*  Copyright (C) 2014-2017 CZ.NIC, z.s.p.o. <knot-dns@labs.nic.cz>
Marek Vavruša's avatar
Marek Vavruša committed
2 3 4 5 6 7 8 9 10 11 12 13

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
14
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
Marek Vavruša's avatar
Marek Vavruša committed
15 16
 */

17
#include <uv.h>
18
#include <lua.h>
19
#include <libknot/packet/pkt.h>
20
#include <libknot/descriptor.h>
21 22
#include <contrib/ucw/lib.h>
#include <contrib/ucw/mempool.h>
23
#include <contrib/wire.h>
Marek Vavruša's avatar
Marek Vavruša committed
24 25 26
#if defined(__GLIBC__) && defined(_GNU_SOURCE)
#include <malloc.h>
#endif
27
#include <assert.h>
28 29
#include <sys/types.h>
#include <unistd.h>
30
#include <gnutls/gnutls.h>
31
#include "lib/utils.h"
32
#include "lib/layer.h"
33
#include "daemon/worker.h"
34
#include "daemon/bindings.h"
35
#include "daemon/engine.h"
36
#include "daemon/io.h"
37
#include "daemon/tls.h"
38
#include "daemon/zimport.h"
39
#include "daemon/session.h"
40

41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

/* Magic defaults for the worker. */
#ifndef MP_FREELIST_SIZE
# ifdef __clang_analyzer__
#  define MP_FREELIST_SIZE 0
# else
#  define MP_FREELIST_SIZE 64 /**< Maximum length of the worker mempool freelist */
# endif
#endif
#ifndef QUERY_RATE_THRESHOLD
#define QUERY_RATE_THRESHOLD (2 * MP_FREELIST_SIZE) /**< Nr of parallel queries considered as high rate */
#endif
#ifndef MAX_PIPELINED
#define MAX_PIPELINED 100
#endif

57 58
#define VERBOSE_MSG(qry, fmt...) QRVERBOSE(qry, "wrkr", fmt)

59 60 61 62 63 64 65 66 67 68 69 70 71
/** Client request state. */
struct request_ctx
{
	struct kr_request req;
	struct {
		union inaddr addr;
		union inaddr dst_addr;
		/* uv_handle_t *handle; */

		/** NULL if the request didn't come over network. */
		struct session *session;
	} source;
	struct worker_ctx *worker;
72
	struct qr_task *task;
73 74 75 76 77 78 79 80
};

/** Query resolution task. */
struct qr_task
{
	struct request_ctx *ctx;
	knot_pkt_t *pktbuf;
	qr_tasklist_t waiting;
81
	struct session *pending[MAX_PENDING];
82 83 84 85 86 87 88 89 90
	uint16_t pending_count;
	uint16_t addrlist_count;
	uint16_t addrlist_turn;
	uint16_t timeouts;
	uint16_t iter_count;
	struct sockaddr *addrlist;
	uint32_t refs;
	bool finished : 1;
	bool leading  : 1;
91
	uint64_t creation_time;
92 93
};

94

95 96 97 98
/* Convenience macros */
#define qr_task_ref(task) \
	do { ++(task)->refs; } while(0)
#define qr_task_unref(task) \
99
	do { if (task && --(task)->refs == 0) { qr_task_free(task); } } while (0)
100 101 102 103 104

/** @internal get key for tcp session
 *  @note kr_straddr() return pointer to static string
 */
#define tcpsess_key(addr) kr_straddr(addr)
105 106

/* Forward decls */
107
static void qr_task_free(struct qr_task *task);
108 109 110
static int qr_task_step(struct qr_task *task,
			const struct sockaddr *packet_source,
			knot_pkt_t *packet);
111
static int qr_task_send(struct qr_task *task, struct session *session,
112 113 114 115
			struct sockaddr *addr, knot_pkt_t *pkt);
static int qr_task_finalize(struct qr_task *task, int state);
static void qr_task_complete(struct qr_task *task);
static struct session* worker_find_tcp_connected(struct worker_ctx *worker,
116
						 const struct sockaddr *addr);
117 118 119 120 121 122
static int worker_add_tcp_waiting(struct worker_ctx *worker,
				  const struct sockaddr *addr,
				  struct session *session);
static int worker_del_tcp_waiting(struct worker_ctx *worker,
				  const struct sockaddr *addr);
static struct session* worker_find_tcp_waiting(struct worker_ctx *worker,
123
					       const struct sockaddr *addr);
124
static void on_tcp_connect_timeout(uv_timer_t *timer);
125 126 127 128 129 130 131

/** @internal Get singleton worker. */
static inline struct worker_ctx *get_worker(void)
{
	return uv_default_loop()->data;
}

132 133
/*! @internal Create a UDP/TCP handle for an outgoing AF_INET* connection.
 *  socktype is SOCK_* */
134
static uv_handle_t *ioreq_spawn(struct worker_ctx *worker, int socktype, sa_family_t family)
135
{
136 137 138
	bool precond = (socktype == SOCK_DGRAM || socktype == SOCK_STREAM)
			&& (family == AF_INET  || family == AF_INET6);
	if (!precond) {
139 140
		/* assert(false); see #245 */
		kr_log_verbose("[work] ioreq_spawn: pre-condition failed\n");
141 142 143
		return NULL;
	}

144
	/* Create connection for iterative query */
145 146
	uv_handle_t *handle = malloc(socktype == SOCK_DGRAM
					? sizeof(uv_udp_t) : sizeof(uv_tcp_t));
147 148 149
	if (!handle) {
		return NULL;
	}
150 151 152 153 154 155
	int ret = io_create(worker->loop, handle, socktype, family);
	if (ret) {
		if (ret == UV_EMFILE) {
			worker->too_many_open = true;
			worker->rconcurrent_highwatermark = worker->stats.rconcurrent;
		}
156
		free(handle);
157 158
		return NULL;
	}
159 160 161 162

	/* Bind to outgoing address, according to IP v4/v6. */
	union inaddr *addr;
	if (family == AF_INET) {
163
		addr = (union inaddr *)&worker->out_addr4;
164
	} else {
165
		addr = (union inaddr *)&worker->out_addr6;
166 167 168 169
	}
	if (addr->ip.sa_family != AF_UNSPEC) {
		assert(addr->ip.sa_family == family);
		if (socktype == SOCK_DGRAM) {
170 171 172 173 174
			uv_udp_t *udp = (uv_udp_t *)handle;
			ret = uv_udp_bind(udp, &addr->ip, 0);
		} else if (socktype == SOCK_STREAM){
			uv_tcp_t *tcp = (uv_tcp_t *)handle;
			ret = uv_tcp_bind(tcp, &addr->ip, 0);
175 176 177
		}
	}

178
	if (ret != 0) {
179
		io_deinit(handle);
180
		free(handle);
181 182
		return NULL;
	}
183 184 185 186

	/* Set current handle as a subrequest type. */
	struct session *session = handle->data;
	session_flags(session)->outgoing = true;
187
	/* Connect or issue query datagram */
188
	return handle;
189 190
}

191
static void ioreq_kill_pending(struct qr_task *task)
192
{
193
	for (uint16_t i = 0; i < task->pending_count; ++i) {
194
		session_kill_ioreq(task->pending[i], task);
195 196 197 198
	}
	task->pending_count = 0;
}

199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
/** @cond This memory layout is internal to mempool.c, use only for debugging. */
#if defined(__SANITIZE_ADDRESS__)
struct mempool_chunk {
  struct mempool_chunk *next;
  size_t size;
};
static void mp_poison(struct mempool *mp, bool poison)
{
	if (!poison) { /* @note mempool is part of the first chunk, unpoison it first */
		kr_asan_unpoison(mp, sizeof(*mp));
	}
	struct mempool_chunk *chunk = mp->state.last[0];
	void *chunk_off = (void *)chunk - chunk->size;
	if (poison) {
		kr_asan_poison(chunk_off, chunk->size);
	} else {
		kr_asan_unpoison(chunk_off, chunk->size);
	}
}
#else
#define mp_poison(mp, enable)
#endif
/** @endcond */

223
/** Get a mempool.  (Recycle if possible.)  */
224
static inline struct mempool *pool_borrow(struct worker_ctx *worker)
225 226
{
	struct mempool *mp = NULL;
227 228 229 230
	if (worker->pool_mp.len > 0) {
		mp = array_tail(worker->pool_mp);
		array_pop(worker->pool_mp);
		mp_poison(mp, 0);
231 232 233 234 235 236
	} else { /* No mempool on the freelist, create new one */
		mp = mp_new (4 * CPU_PAGE_SIZE);
	}
	return mp;
}

237
/** Return a mempool.  (Cache them up to some count.) */
238 239
static inline void pool_release(struct worker_ctx *worker, struct mempool *mp)
{
240
	if (worker->pool_mp.len < MP_FREELIST_SIZE) {
241
		mp_flush(mp);
242
		array_push(worker->pool_mp, mp);
243
		mp_poison(mp, 1);
244 245 246 247 248
	} else {
		mp_delete(mp);
	}
}

249 250 251 252 253 254 255 256 257 258 259 260
/** Create a key for an outgoing subrequest: qname, qclass, qtype.
 * @param key Destination buffer for key size, MUST be SUBREQ_KEY_LEN or larger.
 * @return key length if successful or an error
 */
static const size_t SUBREQ_KEY_LEN = KR_RRKEY_LEN;
static int subreq_key(char *dst, knot_pkt_t *pkt)
{
	assert(pkt);
	return kr_rrkey(dst, knot_pkt_qclass(pkt), knot_pkt_qname(pkt),
			knot_pkt_qtype(pkt), knot_pkt_qtype(pkt));
}

261 262 263 264 265 266 267
/** Create and initialize a request_ctx (on a fresh mempool).
 *
 * handle and addr point to the source of the request, and they are NULL
 * in case the request didn't come from network.
 */
static struct request_ctx *request_create(struct worker_ctx *worker,
					  uv_handle_t *handle,
268 269
					  const struct sockaddr *addr,
					  uint32_t uid)
270
{
271
	knot_mm_t pool = {
272
		.ctx = pool_borrow(worker),
273
		.alloc = (knot_mm_alloc_t) mp_alloc
274
	};
275

276 277 278 279
	/* Create request context */
	struct request_ctx *ctx = mm_alloc(&pool, sizeof(*ctx));
	if (!ctx) {
		pool_release(worker, pool.ctx);
280 281
		return NULL;
	}
282

283 284 285 286
	memset(ctx, 0, sizeof(*ctx));

	/* TODO Relocate pool to struct request */
	ctx->worker = worker;
287 288
	struct session *s = handle ? handle->data : NULL;
	if (s) {
289
		assert(session_flags(s)->outgoing == false);
290
	}
291
	ctx->source.session = s;
292 293 294

	struct kr_request *req = &ctx->req;
	req->pool = pool;
295
	req->vars_ref = LUA_NOREF;
296
	req->uid = uid;
297

298
	/* Remember query source addr */
299 300 301
	if (!addr || (addr->sa_family != AF_INET && addr->sa_family != AF_INET6)) {
		ctx->source.addr.ip.sa_family = AF_UNSPEC;
	} else {
302 303 304
		size_t addr_len = sizeof(struct sockaddr_in);
		if (addr->sa_family == AF_INET6)
			addr_len = sizeof(struct sockaddr_in6);
305 306
		memcpy(&ctx->source.addr.ip, addr, addr_len);
		ctx->req.qsource.addr = &ctx->source.addr.ip;
307
	}
308 309 310 311 312

	worker->stats.rconcurrent += 1;

	if (!handle) {
		return ctx;
313
	}
314

315
	/* Remember the destination address. */
316 317 318 319 320 321
	int addr_len = sizeof(ctx->source.dst_addr);
	struct sockaddr *dst_addr = &ctx->source.dst_addr.ip;
	ctx->source.dst_addr.ip.sa_family = AF_UNSPEC;
	if (handle->type == UV_UDP) {
		if (uv_udp_getsockname((uv_udp_t *)handle, dst_addr, &addr_len) == 0) {
			req->qsource.dst_addr = dst_addr;
322
		}
323 324 325 326
		req->qsource.tcp = false;
	} else if (handle->type == UV_TCP) {
		if (uv_tcp_getsockname((uv_tcp_t *)handle, dst_addr, &addr_len) == 0) {
			req->qsource.dst_addr = dst_addr;
327
		}
328
		req->qsource.tcp = true;
329
	}
330 331

	return ctx;
332 333
}

334 335
/** More initialization, related to the particular incoming query/packet. */
static int request_start(struct request_ctx *ctx, knot_pkt_t *query)
336
{
337 338 339 340 341
	assert(query && ctx);
	size_t answer_max = KNOT_WIRE_MIN_PKTSIZE;
	struct kr_request *req = &ctx->req;

	/* source.session can be empty if request was generated by kresd itself */
342 343
	struct session *s = ctx->source.session;
	if (!s || session_get_handle(s)->type == UV_TCP) {
344 345 346 347
		answer_max = KNOT_WIRE_MAX_PKTSIZE;
	} else if (knot_pkt_has_edns(query)) { /* EDNS */
		answer_max = MAX(knot_edns_get_payload(query->opt_rr),
				 KNOT_WIRE_MIN_PKTSIZE);
348
	}
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
	req->qsource.size = query->size;

	req->answer = knot_pkt_new(NULL, answer_max, &req->pool);
	if (!req->answer) {
		return kr_error(ENOMEM);
	}

	/* Remember query source TSIG key */
	if (query->tsig_rr) {
		req->qsource.key = knot_rrset_copy(query->tsig_rr, &req->pool);
	}

	/* Remember query source EDNS data */
	if (query->opt_rr) {
		req->qsource.opt = knot_rrset_copy(query->opt_rr, &req->pool);
	}
	/* Start resolution */
	struct worker_ctx *worker = ctx->worker;
	struct engine *engine = worker->engine;
	kr_resolve_begin(req, &engine->resolver, req->answer);
	worker->stats.queries += 1;
	/* Throttle outbound queries only when high pressure */
	if (worker->stats.concurrent < QUERY_RATE_THRESHOLD) {
		req->options.NO_THROTTLE = true;
	}
	return kr_ok();
}

static void request_free(struct request_ctx *ctx)
{
	struct worker_ctx *worker = ctx->worker;
380 381 382 383 384 385 386 387 388 389 390 391 392 393
	/* Dereference any Lua vars table if exists */
	if (ctx->req.vars_ref != LUA_NOREF) {
		lua_State *L = worker->engine->L;
		/* Get worker variables table */
		lua_rawgeti(L, LUA_REGISTRYINDEX, worker->vars_table_ref);
		/* Get next free element (position 0) and store it under current reference (forming a list) */
		lua_rawgeti(L, -1, 0);
		lua_rawseti(L, -2, ctx->req.vars_ref);
		/* Set current reference as the next free element */
		lua_pushinteger(L, ctx->req.vars_ref);
		lua_rawseti(L, -2, 0);
		lua_pop(L, 1);
		ctx->req.vars_ref = LUA_NOREF;
	}
394
	/* Return mempool to ring or free it if it's full */
395
	pool_release(worker, ctx->req.pool.ctx);
396
	/* @note The 'task' is invalidated from now on. */
Marek Vavruša's avatar
Marek Vavruša committed
397
	/* Decommit memory every once in a while */
398
	static int mp_delete_count = 0;
399 400 401
	if (++mp_delete_count == 100000) {
		lua_gc(worker->engine->L, LUA_GCCOLLECT, 0);
#if defined(__GLIBC__) && defined(_GNU_SOURCE)
Marek Vavruša's avatar
Marek Vavruša committed
402
		malloc_trim(0);
403
#endif
Marek Vavruša's avatar
Marek Vavruša committed
404
		mp_delete_count = 0;
405
	}
406
	worker->stats.rconcurrent -= 1;
407
}
408

409 410 411 412 413 414 415 416
static struct qr_task *qr_task_create(struct request_ctx *ctx)
{
	/* How much can client handle? */
	struct engine *engine = ctx->worker->engine;
	size_t pktbuf_max = KR_EDNS_PAYLOAD;
	if (engine->resolver.opt_rr) {
		pktbuf_max = MAX(knot_edns_get_payload(engine->resolver.opt_rr),
				 pktbuf_max);
417 418
	}

419 420 421 422
	/* Create resolution task */
	struct qr_task *task = mm_alloc(&ctx->req.pool, sizeof(*task));
	if (!task) {
		return NULL;
423
	}
424
	memset(task, 0, sizeof(*task)); /* avoid accidentally unintialized fields */
425

426 427 428 429 430
	/* Create packet buffers for answer and subrequests */
	knot_pkt_t *pktbuf = knot_pkt_new(NULL, pktbuf_max, &ctx->req.pool);
	if (!pktbuf) {
		mm_free(&ctx->req.pool, task);
		return NULL;
431
	}
432
	pktbuf->size = 0;
433

434 435 436 437
	task->ctx = ctx;
	task->pktbuf = pktbuf;
	array_init(task->waiting);
	task->refs = 0;
438 439 440 441
	assert(ctx->task == NULL);
	ctx->task = task;
	/* Make the primary reference to task. */
	qr_task_ref(task);
442
	task->creation_time = kr_now();
443 444
	ctx->worker->stats.concurrent += 1;
	return task;
445 446
}

447 448 449 450 451 452 453 454 455
/* This is called when the task refcount is zero, free memory. */
static void qr_task_free(struct qr_task *task)
{
	struct request_ctx *ctx = task->ctx;

	assert(ctx);

	struct worker_ctx *worker = ctx->worker;

456
	if (ctx->task == NULL) {
457 458 459 460 461 462 463
		request_free(ctx);
	}

	/* Update stats */
	worker->stats.concurrent -= 1;
}

464 465 466
/*@ Register new qr_task within session. */
static int qr_task_register(struct qr_task *task, struct session *session)
{
467
	assert(!session_flags(session)->outgoing && session_get_handle(session)->type == UV_TCP);
468 469 470 471 472 473 474 475 476 477 478

	session_tasklist_add(session, task);

	struct request_ctx *ctx = task->ctx;
	assert(ctx && (ctx->source.session == NULL || ctx->source.session == session));
	ctx->source.session = session;
	/* Soft-limit on parallel queries, there is no "slow down" RCODE
	 * that we could use to signalize to client, but we can stop reading,
	 * an in effect shrink TCP window size. To get more precise throttling,
	 * we would need to copy remainder of the unread buffer and reassemble
	 * when resuming reading. This is NYI.  */
479 480 481 482
	if (session_tasklist_get_len(session) >= task->ctx->worker->tcp_pipeline_max &&
	    !session_flags(session)->throttled && !session_flags(session)->closing) {
		session_stop_read(session);
		session_flags(session)->throttled = true;
483 484 485 486 487
	}

	return 0;
}

488
static void qr_task_complete(struct qr_task *task)
489
{
490
	struct request_ctx *ctx = task->ctx;
491

492
	/* Kill pending I/O requests */
493
	ioreq_kill_pending(task);
494 495
	assert(task->waiting.len == 0);
	assert(task->leading == false);
496

497 498
	struct session *s = ctx->source.session;
	if (s) {
499
		assert(!session_flags(s)->outgoing && session_waitinglist_is_empty(s));
500
		ctx->source.session = NULL;
501
		session_tasklist_del(s, task);
Grigorii Demidov's avatar
Grigorii Demidov committed
502
	}
503

504
	/* Release primary reference to task. */
505 506 507 508
	if (ctx->task == task) {
		ctx->task = NULL;
		qr_task_unref(task);
	}
509 510
}

511
/* This is called when we send subrequest / answer */
512
static int qr_task_on_send(struct qr_task *task, uv_handle_t *handle, int status)
513
{
514

515 516 517 518 519
	if (task->finished) {
		assert(task->leading == false);
		qr_task_complete(task);
	}

520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
	if (!handle || handle->type != UV_TCP) {
		return status;
	}

	struct session* s = handle->data;
	assert(s);
	if (status != 0) {
		session_tasklist_del(s, task);
	}

	if (session_flags(s)->outgoing || session_flags(s)->closing) {
		return status;
	}

	struct worker_ctx *worker = task->ctx->worker;
	if (session_flags(s)->throttled &&
	    session_tasklist_get_len(s) < worker->tcp_pipeline_max/2) {
	   /* Start reading again if the session is throttled and
	    * the number of outgoing requests is below watermark. */
		session_start_read(s);
		session_flags(s)->throttled = false;
541
	}
542

543
	return status;
544 545
}

546 547 548
static void on_send(uv_udp_send_t *req, int status)
{
	struct qr_task *task = req->data;
549 550
	uv_handle_t *h = (uv_handle_t *)req->handle;
	qr_task_on_send(task, h, status);
551
	qr_task_unref(task);
552
	free(req);
553
}
554 555

static void on_write(uv_write_t *req, int status)
556 557
{
	struct qr_task *task = req->data;
558 559
	uv_handle_t *h = (uv_handle_t *)req->handle;
	qr_task_on_send(task, h, status);
560
	qr_task_unref(task);
561
	free(req);
562 563
}

564
static int qr_task_send(struct qr_task *task, struct session *session,
565
			struct sockaddr *addr, knot_pkt_t *pkt)
566
{
567 568
	if (!session) {
		return qr_task_on_send(task, NULL, kr_error(EIO));
569
	}
570

571
	int ret = 0;
572 573
	struct request_ctx *ctx = task->ctx;
	struct kr_request *req = &ctx->req;
574

575 576
	uv_handle_t *handle = session_get_handle(session);
	assert(handle && handle->data == session);
577 578 579
	const bool is_stream = handle->type == UV_TCP;
	if (!is_stream && handle->type != UV_UDP) abort();

580 581 582 583 584 585 586 587
	if (addr == NULL) {
		addr = session_get_peer(session);
	}

	if (pkt == NULL) {
		pkt = worker_task_get_pktbuf(task);
	}

588
	if (session_flags(session)->outgoing && handle->type == UV_TCP) {
589 590
		size_t try_limit = session_tasklist_get_len(session) + 1;
		uint16_t msg_id = knot_wire_get_id(pkt->wire);
591
		size_t try_count = 0;
592 593 594 595 596 597
		while (session_tasklist_find_msgid(session, msg_id) &&
		       try_count <= try_limit) {
			++msg_id;
			++try_count;
		}
		if (try_count > try_limit) {
598
			return kr_error(ENOENT);
599 600 601 602
		}
		worker_task_pkt_set_msgid(task, msg_id);
	}

603
	if (knot_wire_get_qr(pkt->wire) == 0) {
604 605 606 607 608 609 610 611 612 613 614 615
		/*
		 * Query must be finalised using destination address before
		 * sending.
		 *
		 * Libuv does not offer a convenient way how to obtain a source
		 * IP address from a UDP handle that has been initialised using
		 * uv_udp_init(). The uv_udp_getsockname() fails because of the
		 * lazy socket initialisation.
		 *
		 * @note -- A solution might be opening a separate socket and
		 * trying to obtain the IP address from it.
		 */
616
		ret = kr_resolve_checkout(req, NULL, addr,
617
		                          is_stream ? SOCK_STREAM : SOCK_DGRAM,
618
		                          pkt);
619
		if (ret != 0) {
620
			return ret;
621
		}
622
	}
623

624 625 626 627 628
	uv_handle_t *ioreq = malloc(is_stream ? sizeof(uv_write_t) : sizeof(uv_udp_send_t));
	if (!ioreq) {
		return qr_task_on_send(task, handle, kr_error(ENOMEM));
	}

629 630 631
	/* Pending ioreq on current task */
	qr_task_ref(task);

632
	struct worker_ctx *worker = ctx->worker;
633
	/* Send using given protocol */
634 635
	assert(!session_flags(session)->closing);
	if (session_flags(session)->has_tls) {
636 637
		uv_write_t *write_req = (uv_write_t *)ioreq;
		write_req->data = task;
638
		ret = tls_write(write_req, handle, pkt, &on_write);
639
	} else if (handle->type == UV_UDP) {
640
		uv_udp_send_t *send_req = (uv_udp_send_t *)ioreq;
641
		uv_buf_t buf = { (char *)pkt->wire, pkt->size };
642 643 644 645
		send_req->data = task;
		ret = uv_udp_send(send_req, (uv_udp_t *)handle, &buf, 1, addr, &on_send);
	} else if (handle->type == UV_TCP) {
		uv_write_t *write_req = (uv_write_t *)ioreq;
646 647 648 649 650
		uint16_t pkt_size = htons(pkt->size);
		uv_buf_t buf[2] = {
			{ (char *)&pkt_size, sizeof(pkt_size) },
			{ (char *)pkt->wire, pkt->size }
		};
651
		write_req->data = task;
652
		ret = uv_write(write_req, (uv_stream_t *)handle, buf, 2, &on_write);
653 654
	} else {
		assert(false);
655
	}
656

657
	if (ret == 0) {
658
		session_touch(session);
659 660 661
		if (session_flags(session)->outgoing) {
			session_tasklist_add(session, task);
		}
662 663
		if (worker->too_many_open &&
		    worker->stats.rconcurrent <
664
			worker->rconcurrent_highwatermark - 10) {
665 666
			worker->too_many_open = false;
		}
667
	} else {
668
		free(ioreq);
669
		qr_task_unref(task);
670 671 672
		if (ret == UV_EMFILE) {
			worker->too_many_open = true;
			worker->rconcurrent_highwatermark = worker->stats.rconcurrent;
673
			ret = kr_error(UV_EMFILE);
674
		}
675
	}
676

677
	/* Update statistics */
678 679
	if (session_flags(session)->outgoing && addr) {
		if (session_flags(session)->has_tls)
680 681
			worker->stats.tls += 1;
		else if (handle->type == UV_UDP)
682
			worker->stats.udp += 1;
683
		else
684
			worker->stats.tcp += 1;
685

686
		if (addr->sa_family == AF_INET6)
687
			worker->stats.ipv6 += 1;
688
		else if (addr->sa_family == AF_INET)
689
			worker->stats.ipv4 += 1;
690
	}
691
	return ret;
692 693
}

694 695
static int session_tls_hs_cb(struct session *session, int status)
{
696
	assert(session_flags(session)->outgoing);
697 698 699 700 701
	uv_handle_t *handle = session_get_handle(session);
	uv_loop_t *loop = handle->loop;
	struct worker_ctx *worker = loop->data;
	struct sockaddr *peer = session_get_peer(session);
	int deletion_res = worker_del_tcp_waiting(worker, peer);
702
	int ret = kr_ok();
703

704
	if (status) {
705
		kr_nsrep_update_rtt(NULL, peer, KR_NS_DEAD,
706 707
				    worker->engine->resolver.cache_rtt,
				    KR_NS_UPDATE_NORESET);
708 709 710 711
		return ret;
	}

	/* handshake was completed successfully */
712
	struct tls_client_ctx_t *tls_client_ctx = session_tls_get_client_ctx(session);
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
	struct tls_client_paramlist_entry *tls_params = tls_client_ctx->params;
	gnutls_session_t tls_session = tls_client_ctx->c.tls_session;
	if (gnutls_session_is_resumed(tls_session) != 0) {
		kr_log_verbose("[tls_client] TLS session has resumed\n");
	} else {
		kr_log_verbose("[tls_client] TLS session has not resumed\n");
		/* session wasn't resumed, delete old session data ... */
		if (tls_params->session_data.data != NULL) {
			gnutls_free(tls_params->session_data.data);
			tls_params->session_data.data = NULL;
			tls_params->session_data.size = 0;
		}
		/* ... and get the new session data */
		gnutls_datum_t tls_session_data = { NULL, 0 };
		ret = gnutls_session_get_data2(tls_session, &tls_session_data);
		if (ret == 0) {
			tls_params->session_data = tls_session_data;
		}
731
	}
732

733
	ret = worker_add_tcp_connected(worker, peer, session);
734
	if (deletion_res == kr_ok() && ret == kr_ok()) {
735 736 737 738 739 740 741 742
		while (!session_waitinglist_is_empty(session)) {
			struct qr_task *t = session_waitinglist_get(session);
			ret = qr_task_send(t, session, NULL, NULL);
			if (ret != 0) {
				break;
			}
			session_waitinglist_pop(session, true);
		}
743 744 745 746 747 748 749 750 751
	} else {
		ret = kr_error(EINVAL);
	}

	if (ret != kr_ok()) {
		/* Something went wrong.
		 * Session isn't in the list of waiting sessions,
		 * or addition to the list of connected sessions failed,
		 * or write to upstream failed. */
752
		worker_del_tcp_connected(worker, peer);
753
		session_waitinglist_finalize(session, KR_STATE_FAIL);
754
		assert(session_tasklist_is_empty(session));
755
		session_close(session);
756
	} else {
757
		session_timer_stop(session);
758
		session_timer_start(session, tcp_timeout_trigger,
759
				    MAX_TCP_INACTIVITY, MAX_TCP_INACTIVITY);
760 761 762 763
	}
	return kr_ok();
}

764

765 766 767
static struct kr_query *task_get_last_pending_query(struct qr_task *task)
{
	if (!task || task->ctx->req.rplan.pending.len == 0) {
768 769 770 771 772 773
		return NULL;
	}

	return array_tail(task->ctx->req.rplan.pending);
}

774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
static int send_waiting(struct session *session)
{
	int ret = 0;
	while (!session_waitinglist_is_empty(session)) {
		struct qr_task *t = session_waitinglist_get(session);
		ret = qr_task_send(t, session, NULL, NULL);
		if (ret != 0) {
			session_waitinglist_finalize(session, KR_STATE_FAIL);
			session_tasklist_finalize(session, KR_STATE_FAIL);
			session_close(session);
			break;
		}
		session_waitinglist_pop(session, true);
	}
	return ret;
}
790

791
static void on_connect(uv_connect_t *req, int status)
792
{
793
	struct worker_ctx *worker = get_worker();
794
	uv_stream_t *handle = req->handle;
795
	struct session *session = handle->data;
796
	struct sockaddr *peer = session_get_peer(session);
797
	free(req);
798

799
	assert(session_flags(session)->outgoing);
800 801

	if (status == UV_ECANCELED) {
802
		worker_del_tcp_waiting(worker, peer);
803
		assert(session_is_empty(session) && session_flags(session)->closing);
804 805 806
		return;
	}

807
	if (session_flags(session)->closing) {
808 809
		worker_del_tcp_waiting(worker, peer);
		assert(session_is_empty(session));
810 811 812 813
		return;
	}

	if (status != 0) {
814 815
		worker_del_tcp_waiting(worker, peer);
		assert(session_tasklist_is_empty(session));
816
		session_waitinglist_retry(session, false);
817 818 819 820
		session_close(session);
		return;
	}

821
	if (!session_flags(session)->has_tls) {
822 823
		/* if there is a TLS, session still waiting for handshake,
		 * otherwise remove it from waiting list */
824
		if (worker_del_tcp_waiting(worker, peer) != 0) {
825 826
			/* session isn't in list of waiting queries, *
			 * something gone wrong */
827 828
			session_waitinglist_finalize(session, KR_STATE_FAIL);
			assert(session_tasklist_is_empty(session));
829 830 831 832 833
			session_close(session);
			return;
		}
	}

834
	struct qr_task *task = session_waitinglist_get(session);
835
	struct kr_query *qry = task_get_last_pending_query(task);
836
	WITH_VERBOSE (qry) {
837 838 839 840
		struct sockaddr *peer = session_get_peer(session);
		char peer_str[INET6_ADDRSTRLEN];
		inet_ntop(peer->sa_family, kr_inaddr(peer), peer_str, sizeof(peer_str));
		VERBOSE_MSG(qry, "=> connected to '%s'\n", peer_str);
841 842
	}

843
	session_flags(session)->connected = true;
844
	session_start_read(session);
845 846

	int ret = kr_ok();
847
	if (session_flags(session)->has_tls) {
848 849
		struct tls_client_ctx_t *tls_ctx = session_tls_get_client_ctx(session);
		ret = tls_client_connect_start(tls_ctx, session, session_tls_hs_cb);
850
		if (ret == kr_error(EAGAIN)) {
851 852
			session_timer_stop(session);
			session_timer_start(session, tcp_timeout_trigger,
853
					    MAX_TCP_INACTIVITY, MAX_TCP_INACTIVITY);
854 855
			return;
		}
856 857
	} else {
		worker_add_tcp_connected(worker, peer, session);
858
	}
859 860 861 862 863

	ret = send_waiting(session);
	if (ret != 0) {
		worker_del_tcp_connected(worker, peer);
		return;
864
	}
865

866 867
	session_timer_stop(session);
	session_timer_start(session, tcp_timeout_trigger,
868
			    MAX_TCP_INACTIVITY, MAX_TCP_INACTIVITY);
869 870
}

871
static void on_tcp_connect_timeout(uv_timer_t *timer)
872
{
873 874 875
	struct session *session = timer->data;

	uv_timer_stop(timer);
876
	struct worker_ctx *worker = get_worker();
877

878
	assert (session_tasklist_is_empty(session));
879

880 881
	struct sockaddr *peer = session_get_peer(session);
	worker_del_tcp_waiting(worker, peer);
882

883
	struct qr_task *task = session_waitinglist_get(session);
884
	struct kr_query *qry = task_get_last_pending_query(task);
885
	WITH_VERBOSE (qry) {
886 887 888
		char peer_str[INET6_ADDRSTRLEN];
		inet_ntop(peer->sa_family, kr_inaddr(peer), peer_str, sizeof(peer_str));
		VERBOSE_MSG(qry, "=> connection to '%s' failed\n", peer_str);
889
	}
890

891
	kr_nsrep_update_rtt(NULL, peer, KR_NS_DEAD,
892 893
			    worker->engine->resolver.cache_rtt,
			    KR_NS_UPDATE_NORESET);
894

895 896 897
	worker->stats.timeout += session_waitinglist_get_len(session);
	session_waitinglist_retry(session, true);
	assert (session_tasklist_is_empty(session));
898
	session_close(session);
899 900 901
}

/* This is called when I/O timeouts */
902
static void on_udp_timeout(uv_timer_t *timer)
903
{
904
	struct session *session = timer->data;
905 906 907
	assert(session_get_handle(session)->data == session);
	assert(session_tasklist_get_len(session) == 1);
	assert(session_waitinglist_is_empty(session));
908 909

	uv_timer_stop(timer);
910 911

	/* Penalize all tried nameservers with a timeout. */
912
	struct qr_task *task = session_tasklist_get_first(session);
913
	struct worker_ctx *worker = task->ctx->worker;
914
	if (task->leading && task->pending_count > 0) {
915
		struct kr_query *qry = array_tail(task->ctx->req.rplan.pending);
916 917 918
		struct sockaddr_in6 *addrlist = (struct sockaddr_in6 *)task->addrlist;
		for (uint16_t i = 0; i < MIN(task->pending_count, task->addrlist_count); ++i) {
			struct sockaddr *choice = (struct sockaddr *)(&addrlist[i]);
919
			WITH_VERBOSE(qry) {
920 921
				char addr_str[INET6_ADDRSTRLEN];
				inet_ntop(choice->sa_family, kr_inaddr(choice), addr_str, sizeof(addr_str));
922
				VERBOSE_MSG(qry, "=> server: '%s' flagged as 'bad'\n", addr_str);
923
			}
924
			kr_nsrep_update_rtt(&qry->ns, choice, KR_NS_DEAD,
925 926
					    worker->engine->resolver.cache_rtt,
					    KR_NS_UPDATE_NORESET);
927 928 929 930 931
		}
	}
	task->timeouts += 1;
	worker->stats.timeout += 1;
	qr_task_step(task, NULL, NULL);
932 933
}

934
static uv_handle_t *retransmit(struct qr_task *task)
935
{
936
	uv_handle_t *ret = NULL;
937
	if (task && task->addrlist && task->addrlist_count > 0) {
938
		struct sockaddr_in6 *choice = &((struct sockaddr_in6 *)task->addrlist)[task->addrlist_turn];
Grigorii Demidov's avatar
Grigorii Demidov committed
939 940 941
		if (!choice) {
			return ret;
		}
942 943 944 945
		if (task->pending_count >= MAX_PENDING) {
			return ret;
		}
		ret = ioreq_spawn(task->ctx->worker, SOCK_DGRAM, choice->sin6_family);
946 947 948 949 950
		if (!ret) {
			return ret;
		}
		struct sockaddr *addr = (struct sockaddr *)choice;
		struct session *session = ret->data;
951
		struct sockaddr *peer = session_get_peer(session);
952
		assert (peer->sa_family == AF_UNSPEC && session_flags(session)->outgoing);
953
		memcpy(peer, addr, kr_sockaddr_len(addr));
954 955 956 957 958
		if (qr_task_send(task, session, (struct sockaddr *)choice,
				 task->pktbuf) != 0) {
			session_close(session);
			ret = NULL;
		} else {
959
			task->pending[task->pending_count] = session;
960
			task->pending_count += 1;
961 962
			task->addrlist_turn = (task->addrlist_turn + 1) %
					      task->addrlist_count; /* Round robin */
963
			session_start_read(session); /* Start reading answer */
964 965
		}
	}
966
	return ret;
967 968 969 970
}

static void on_retransmit(uv_timer_t *req)
{
971
	struct session *session = req->data;
972
	assert(session_tasklist_get_len(session) == 1);
973 974

	uv_timer_stop(req);
975
	struct qr_task *task = session_tasklist_get_first(session);
976
	if (retransmit(task) == NULL) {
977 978
		/* Not possible to spawn request, start timeout timer with remaining deadline. */
		uint64_t timeout = KR_CONN_RTT_MAX - task->pending_count * KR_CONN_RETRY;
979
		uv_timer_start(req, on_udp_timeout, timeout, 0);
980 981
	} else {
		uv_timer_start(req, on_retransmit, KR_CONN_RETRY, 0);
982
	}
983 984
}

985
static void subreq_finalize(struct qr_task *task, const struct sockaddr *packet_source, knot_pkt_t *pkt)
986
{
987 988 989
	if (!task || task->finished) {
		return;
	}
990
	/* Close pending timer */
991
	ioreq_kill_pending(task);
992
	/* Clear from outgoing table. */
993 994
	if (!task->leading)
		return;
995 996 997 998 999
	char key[SUBREQ_KEY_LEN];
	const int klen = subreq_key(key, task->pktbuf);
	if (klen > 0) {
		void *val_deleted;
		int ret = trie_del(task->ctx->worker->subreq_out, key, klen, &val_deleted);
1000
		assert(ret == KNOT_EOK && val_deleted == task); (void)ret;
1001 1002
	}
	/* Notify waiting tasks. */
1003
	struct kr_query *leader_qry = array_tail(task->ctx->req.rplan.pending);
1004 1005
	for (size_t i = task->waiting.len; i > 0; i--) {
		struct qr_task *follower = task->waiting.at[i - 1];
1006
		/* Reuse MSGID and 0x20 secret */
1007 1008
		if (follower->ctx->req.rplan.pending.len > 0) {
			struct kr_query *qry = array_tail(follower->ctx->req.rplan.pending);
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
			qry->id = leader_qry->id;
			qry->secret = leader_qry->secret;
			leader_qry->secret = 0; /* Next will be already decoded */
		}
		qr_task_step(follower, packet_source, pkt);
		qr_task_unref(follower);
	}
	task->waiting.len = 0;
	task->leading = false;
}

static void subreq_lead(struct qr_task *task)
{
	assert(task);
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
	char key[SUBREQ_KEY_LEN];
	const int klen = subreq_key(key, task->pktbuf);
	if (klen < 0)
		return;
	struct qr_task **tvp = (struct qr_task **)
		trie_get_ins(task->ctx->worker->subreq_out, key, klen);
	if (unlikely(!tvp))
		return; /*ENOMEM*/
	if (unlikely(*tvp != NULL)) {
		assert(false);
		return;
1034
	}
1035 1036
	*tvp = task;
	task->leading = true;
1037 1038 1039 1040 1041
}

static bool subreq_enqueue(struct qr_task *task)
{
	assert(task);
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
	char key[SUBREQ_KEY_LEN];
	const int klen = subreq_key(key, task->pktbuf);
	if (klen < 0)
		return false;
	struct qr_task **leader = (struct qr_task **)
		trie_get_try(task->ctx->worker->subreq_out, key, klen);
	if (!leader /*ENOMEM*/ || !*leader)
		return false;
	/* Enqueue itself to leader for this subrequest. */
	int ret = array_push_mm((*leader)->waiting, task,
				kr_memreserve, &(*leader)->ctx->req.pool);
	if (unlikely(ret < 0)) /*ENOMEM*/
		return false;
	qr_task_ref(task);
	return true;
1057 1058 1059 1060 1061
}

static int qr_task_finalize(struct qr_task *task, int state)
{
	assert(task && task->leading == false);
1062 1063 1064
	if (task->finished) {
		return 0;
	}
1065 1066
	struct request_ctx *ctx = task->ctx;
	kr_resolve_finish(&ctx->req, state);
1067

1068
	task->finished = true;
1069 1070 1071 1072 1073
	if (ctx->source.session == NULL) {
		(void) qr_task_on_send(task, NULL, kr_error(EIO));
		return state == KR_STATE_DONE ? 0 : kr_error(EIO);
	}

1074 1075 1076
	/* Reference task as the callback handler can close it */
	qr_task_ref(task);

1077
	/* Send back answer */
1078
	struct session *source_session = ctx->source.session;
1079
	assert(!session_flags(source_session)->closing);
1080
	assert(ctx->source.addr.ip.sa_family != AF_UNSPEC);
1081
	int res = qr_task_send(task, source_session,
1082 1083 1084
			       (struct sockaddr *)&ctx->source.addr,
			        ctx->req.answer);
	if (res != kr_ok()) {
1085
		(void) qr_task_on_send(task, NULL, kr_error(EIO));
1086
		/* Since source session is erroneous detach all tasks. */
1087
		while (!session_tasklist_is_empty(source_session)) {
1088
			struct qr_task *t = session_tasklist_del_first(source_session, false);
1089 1090 1091 1092 1093 1094
			struct request_ctx *c = t->ctx;
			assert(c->source.session == source_session);
			c->source.session = NULL;
			/* Don't finalize them as there can be other tasks
			 * waiting for answer to this particular task.
			 * (ie. task->leading is true) */
1095
			worker_task_unref(t);
1096 1097
		}
		session_close(source_session);
1098
	}
1099

1100 1101
	qr_task_unref(task);

1102
	return state == KR_STATE_DONE ? 0 : kr_error(EIO);
1103
}
1104

1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
static int udp_task_step(struct qr_task *task,
			 const struct sockaddr *packet_source, knot_pkt_t *packet)
{
	struct request_ctx *ctx = task->ctx;
	struct kr_request *req = &ctx->req;

	/* If there is already outgoing query, enqueue to it. */
	if (subreq_enqueue(task)) {
		return kr_ok(); /* Will be notified when outgoing query finishes. */
	}
	/* Start transmitting */
	uv_handle_t *handle = retransmit(task);
	if (handle == NULL) {
		subreq_finalize(task, packet_source, packet);
		return qr_task_finalize(task, KR_STATE_FAIL);
	}
	/* Check current query NSLIST */
	struct kr_query *qry = array_tail(req->rplan.pending);
	assert(qry != NULL);
	/* Retransmit at default interval, or more frequently if the mean
	 * RTT of the server is better. If the server is glued, use default rate. */
	size_t timeout = qry->ns.score;
	if (timeout > KR_NS_GLUED) {
		/* We don't have information about variance in RTT, expect +10ms */
		timeout = MIN(qry->ns.score + 10, KR_CONN_RETRY);
	} else {
		timeout = KR_CONN_RETRY;
	}
	/* Announce and start subrequest.
	 * @note Only UDP can lead I/O as it doesn't touch 'task->pktbuf' for reassembly.
	 */
	subreq_lead(task);
	struct session *session = handle->data;
	assert(session_get_handle(session) == handle && (handle->type == UV_UDP));
	int ret = session_timer_start(session, on_retransmit, timeout, 0);
	/* Start next step with timeout, fatal if can't start a timer. */
	if (ret != 0) {
		subreq_finalize(task, packet_source, packet);
		return qr_task_finalize(task, KR_STATE_FAIL);
	}
	return kr_ok();
}

static int tcp_task_waiting_connection(struct session *session, struct qr_task *task)
{
	assert(session_flags(session)->outgoing);
	if (session_flags(session)->closing) {
		/* Something went wrong. Better answer with KR_STATE_FAIL.
		 * TODO: normally should not happen,
		 * consider possibility to transform this into
		 * assert(!session_flags(session)->closing). */
		return kr_error(EINVAL);
	}
	/* Add task to the end of list of waiting tasks.
	 * It will be notified in on_connect() or qr_task_on_send(). */
	int ret = session_waitinglist_push(session, task);
	if (ret < 0) {
		return kr_error(EINVAL);
	}
	return kr_ok();
}

static int tcp_task_existing_connection(struct session *session, struct qr_task *task)
{
	assert(session_flags(session)->outgoing);
	struct request_ctx *ctx = task->ctx;
	struct worker_ctx *worker = ctx->worker;

	if (session_flags(session)->closing) {
		/* Something went wrong. Better answer with KR_STATE_FAIL.
		 * TODO: normally should not happen,
		 * consider possibility to transform this into
		 * assert(!session_flags(session)->closing). */
		return kr_error(EINVAL);
	}

	/* If there are any unsent queries, send it first. */
	int ret = send_waiting(session);
	if (ret != 0) {
		return kr_error(EINVAL);
	}

	/* No unsent queries at that point. */
	if (session_tasklist_get_len(session) >= worker->tcp_pipeline_max) {
		/* Too many outstanding queries, answer with SERFVAIL, */
		return kr_error(EINVAL);
	}

	/* Send query to upstream. */
	ret = qr_task_send(task, session, NULL, NULL);
	if (ret != 0) {
		/* Error, finalize task with SERVFAIL and
		 * close connection to upstream. */
		session_tasklist_finalize(session, KR_STATE_FAIL);
		session_close(session);
		return kr_error(EINVAL);
	}

	return kr_ok();
}

static int tcp_task_make_connection(struct session *session, struct qr_task *task,
				    const struct sockaddr *addr /* , knot_pkt_t *packet */)
{
	struct request_ctx *ctx = task->ctx;
	struct worker_ctx *worker = ctx->worker;

	uv_connect_t *conn = malloc(sizeof(uv_connect_t));
	if (!conn) {
		return kr_error(EINVAL);
	}
	uv_handle_t *client = ioreq_spawn(worker, SOCK_STREAM,
						  addr->sa_family);
	if (!client) {
		free(conn);
		return kr_error(EINVAL);
	}
	session = client->data;

	/* Add address to the waiting list.
	 * Now it "is waiting to be connected to." */
	int ret = worker_add_tcp_waiting(ctx->worker, addr, session);
	if (ret < 0) {
		free(conn);
		return kr_error(EINVAL);
	}

	/* Check if there must be TLS */
	struct engine *engine = ctx->worker->engine;
	struct network *net = &engine->net;
	const char *key = tcpsess_key(addr);
	struct tls_client_paramlist_entry *entry = map_get(&net->tls_client_params, key);
	if (entry) {
		/* Address is configured to be used with TLS.
		 * We need to allocate auxiliary data structure. */
		assert(session_tls_get_client_ctx(session) == NULL);
		struct tls_client_ctx_t *tls_ctx = tls_client_ctx_new(entry, worker);
		if (!tls_ctx) {
			worker_del_tcp_waiting(ctx->worker, addr);
			free(conn);
			return kr_error(EINVAL);
		}
		tls_client_ctx_set_session(tls_ctx, session);
		session_tls_set_client_ctx(session, tls_ctx);
		session_flags(session)->has_tls = true;
	}

	conn->data = session;
	/*  Store peer address for the session. */
	struct sockaddr *peer = session_get_peer(session);
	memcpy(peer, addr, kr_sockaddr_len(addr));

	/*  Start watchdog to catch eventual connection timeout. */
	ret = session_timer_start(session, on_tcp_connect_timeout,
				  KR_CONN_RTT_MAX, 0);
	if (ret != 0) {
		worker_del_tcp_waiting(ctx->worker, addr);
		free(conn);
		return kr_error(EINVAL);
	}

	struct kr_query *qry = task_get_last_pending_query(task);
	WITH_VERBOSE (qry) {
		const char *peer_str = kr_straddr(peer);
		VERBOSE_MSG(qry, "=> connecting to: '%s'\n", peer_str ? peer_str : "");
	}

	/*  Start connection process to upstream. */
	if (uv_tcp_connect(conn, (uv_tcp_t *)client, addr , on_connect) != 0) {
		session_timer_stop(session);
		worker_del_tcp_waiting(ctx->worker, addr);
		free(conn);
		return kr_error(EAGAIN);
	}

	/* Add task to the end of list of waiting tasks.
	 * Will be notified either in on_connect() or in qr_task_on_send(). */
	ret = session_waitinglist_push(session, task);
	if (<