blob: 17fba5fcabe3e85a473ac6b5a465a147e3df9e1a [file] [log] [blame]
Baptiste Assmann325137d2015-04-13 23:40:55 +02001/*
2 * Name server resolution
3 *
Willy Tarreau714f3452021-05-09 06:47:26 +02004 * Copyright 2020 HAProxy Technologies
Baptiste Assmann325137d2015-04-13 23:40:55 +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 <errno.h>
14#include <fcntl.h>
15#include <stdio.h>
16#include <stdlib.h>
17#include <string.h>
18#include <unistd.h>
19
20#include <sys/types.h>
21
Willy Tarreau122eba92020-06-04 10:15:32 +020022#include <haproxy/action.h>
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020023#include <haproxy/api.h>
Willy Tarreau6be78492020-06-05 00:00:29 +020024#include <haproxy/cfgparse.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020025#include <haproxy/channel.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020026#include <haproxy/check.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020027#include <haproxy/cli.h>
Willy Tarreau7c18b542020-06-11 09:23:02 +020028#include <haproxy/dgram.h>
Willy Tarreaueb92deb2020-06-04 10:53:16 +020029#include <haproxy/dns.h>
Willy Tarreau8d366972020-05-27 16:10:29 +020030#include <haproxy/errors.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020031#include <haproxy/fd.h>
Willy Tarreauaeed4a82020-06-04 22:01:04 +020032#include <haproxy/log.h>
Emeric Brund26a6232021-01-04 13:32:20 +010033#include <haproxy/ring.h>
Emeric Brunfd647d52021-02-12 20:03:38 +010034#include <haproxy/stream.h>
35#include <haproxy/stream_interface.h>
Willy Tarreau9f9e9fc2021-05-08 13:09:46 +020036#include <haproxy/tools.h>
Baptiste Assmann325137d2015-04-13 23:40:55 +020037
Emeric Brund26a6232021-01-04 13:32:20 +010038static THREAD_LOCAL char *dns_msg_trash;
Baptiste Assmann325137d2015-04-13 23:40:55 +020039
Emeric Brunfd647d52021-02-12 20:03:38 +010040DECLARE_STATIC_POOL(dns_session_pool, "dns_session", sizeof(struct dns_session));
41DECLARE_STATIC_POOL(dns_query_pool, "dns_query", sizeof(struct dns_query));
42DECLARE_STATIC_POOL(dns_msg_buf, "dns_msg_buf", DNS_TCP_MSG_RING_MAX_SIZE);
43
Christopher Faulet67957bd2017-09-27 11:00:59 +020044/* Opens an UDP socket on the namesaver's IP/Port, if required. Returns 0 on
Christopher Faulet1e711be2021-03-04 16:58:35 +010045 * success, -1 otherwise. ns->dgram must be defined.
Baptiste Assmann325137d2015-04-13 23:40:55 +020046 */
Emeric Brund26a6232021-01-04 13:32:20 +010047static int dns_connect_nameserver(struct dns_nameserver *ns)
Baptiste Assmann325137d2015-04-13 23:40:55 +020048{
Christopher Faulet1e711be2021-03-04 16:58:35 +010049 struct dgram_conn *dgram = &ns->dgram->conn;
50 int fd;
Baptiste Assmann325137d2015-04-13 23:40:55 +020051
Christopher Faulet1e711be2021-03-04 16:58:35 +010052 /* Already connected */
53 if (dgram->t.sock.fd != -1)
Emeric Brun526b7922021-02-15 14:28:27 +010054 return 0;
Christopher Faulet1e711be2021-03-04 16:58:35 +010055
56 /* Create an UDP socket and connect it on the nameserver's IP/Port */
57 if ((fd = socket(dgram->addr.to.ss_family, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
58 send_log(NULL, LOG_WARNING,
59 "DNS : section '%s': can't create socket for nameserver '%s'.\n",
60 ns->counters->pid, ns->id);
61 return -1;
62 }
63 if (connect(fd, (struct sockaddr*)&dgram->addr.to, get_addr_len(&dgram->addr.to)) == -1) {
64 send_log(NULL, LOG_WARNING,
65 "DNS : section '%s': can't connect socket for nameserver '%s'.\n",
66 ns->counters->id, ns->id);
67 close(fd);
68 return -1;
Emeric Brunc9437992021-02-12 19:42:55 +010069 }
Emeric Brun526b7922021-02-15 14:28:27 +010070
Christopher Faulet1e711be2021-03-04 16:58:35 +010071 /* Make the socket non blocking */
72 fcntl(fd, F_SETFL, O_NONBLOCK);
73
74 /* Add the fd in the fd list and update its parameters */
75 dgram->t.sock.fd = fd;
76 fd_insert(fd, dgram, dgram_fd_handler, MAX_THREADS_MASK);
77 fd_want_recv(fd);
78 return 0;
Baptiste Assmann325137d2015-04-13 23:40:55 +020079}
80
Emeric Brund26a6232021-01-04 13:32:20 +010081/* Sends a message to a name server
82 * It returns message length on success
83 * or -1 in error case
84 * 0 is returned in case of output ring buffer is full
85 */
86int dns_send_nameserver(struct dns_nameserver *ns, void *buf, size_t len)
87{
88 int ret = -1;
89
90 if (ns->dgram) {
91 struct dgram_conn *dgram = &ns->dgram->conn;
92 int fd = dgram->t.sock.fd;
93
94 if (dgram->t.sock.fd == -1) {
95 if (dns_connect_nameserver(ns) == -1)
96 return -1;
97 fd = dgram->t.sock.fd;
98 }
99
100 ret = send(fd, buf, len, 0);
101 if (ret < 0) {
102 if (errno == EAGAIN) {
103 struct ist myist;
104
Tim Duesterhus92c696e2021-02-28 16:11:36 +0100105 myist = ist2(buf, len);
Emeric Brund26a6232021-01-04 13:32:20 +0100106 ret = ring_write(ns->dgram->ring_req, DNS_TCP_MSG_MAX_SIZE, NULL, 0, &myist, 1);
107 if (!ret) {
108 ns->counters->snd_error++;
109 return -1;
110 }
111 fd_cant_send(fd);
112 return ret;
113 }
114 ns->counters->snd_error++;
115 fd_delete(fd);
Emeric Brund26a6232021-01-04 13:32:20 +0100116 dgram->t.sock.fd = -1;
117 return -1;
118 }
119 ns->counters->sent++;
120 }
Emeric Brunfd647d52021-02-12 20:03:38 +0100121 else if (ns->stream) {
122 struct ist myist;
123
Tim Duesterhus92c696e2021-02-28 16:11:36 +0100124 myist = ist2(buf, len);
Emeric Brunfd647d52021-02-12 20:03:38 +0100125 ret = ring_write(ns->stream->ring_req, DNS_TCP_MSG_MAX_SIZE, NULL, 0, &myist, 1);
126 if (!ret) {
127 ns->counters->snd_error++;
128 return -1;
129 }
130 task_wakeup(ns->stream->task_req, TASK_WOKEN_MSG);
131 return ret;
132 }
Emeric Brund26a6232021-01-04 13:32:20 +0100133
134 return ret;
135}
136
Emeric Brunfd647d52021-02-12 20:03:38 +0100137void dns_session_free(struct dns_session *);
138
Emeric Brund26a6232021-01-04 13:32:20 +0100139/* Receives a dns message
140 * Returns message length
141 * 0 is returned if no more message available
142 * -1 in error case
143 */
144ssize_t dns_recv_nameserver(struct dns_nameserver *ns, void *data, size_t size)
145{
146 ssize_t ret = -1;
147
148 if (ns->dgram) {
149 struct dgram_conn *dgram = &ns->dgram->conn;
150 int fd = dgram->t.sock.fd;
151
152 if (fd == -1)
153 return -1;
154
155 if ((ret = recv(fd, data, size, 0)) < 0) {
156 if (errno == EAGAIN) {
157 fd_cant_recv(fd);
158 return 0;
159 }
160 fd_delete(fd);
Emeric Brund26a6232021-01-04 13:32:20 +0100161 dgram->t.sock.fd = -1;
162 return -1;
163 }
164 }
Emeric Brunfd647d52021-02-12 20:03:38 +0100165 else if (ns->stream) {
166 struct dns_stream_server *dss = ns->stream;
167 struct dns_session *ds;
168
169 HA_SPIN_LOCK(DNS_LOCK, &dss->lock);
170
171 if (!LIST_ISEMPTY(&dss->wait_sess)) {
172 ds = LIST_NEXT(&dss->wait_sess, struct dns_session *, waiter);
Emeric Brunfd647d52021-02-12 20:03:38 +0100173 ret = ds->rx_msg.len < size ? ds->rx_msg.len : size;
174 memcpy(data, ds->rx_msg.area, ret);
175
176 ds->rx_msg.len = 0;
177
Emeric Brunfd647d52021-02-12 20:03:38 +0100178 LIST_DEL_INIT(&ds->waiter);
179
180 if (ds->appctx) {
Ilya Shipitsin0de36ad2021-02-20 00:23:36 +0500181 /* awake appctx because it may have other
Emeric Brunfd647d52021-02-12 20:03:38 +0100182 * message to receive
183 */
184 appctx_wakeup(ds->appctx);
185
186 /* dns_session could already be into free_sess list
187 * so we firstly remove it */
188 LIST_DEL_INIT(&ds->list);
189
190 /* decrease nb_queries to free a slot for a new query on that sess */
191 ds->nb_queries--;
192 if (ds->nb_queries) {
193 /* it remains pipelined unanswered request
194 * into this session but we just decrease
195 * the counter so the session
196 * can not be full of pipelined requests
197 * so we can add if to free_sess list
198 * to receive a new request
199 */
Willy Tarreau2b718102021-04-21 07:32:39 +0200200 LIST_INSERT(&ds->dss->free_sess, &ds->list);
Emeric Brunfd647d52021-02-12 20:03:38 +0100201 }
202 else {
203 /* there is no more pipelined requests
204 * into this session, so we move it
205 * to idle_sess list */
Willy Tarreau2b718102021-04-21 07:32:39 +0200206 LIST_INSERT(&ds->dss->idle_sess, &ds->list);
Emeric Brunfd647d52021-02-12 20:03:38 +0100207
208 /* update the counter of idle sessions */
209 ds->dss->idle_conns++;
210
211 /* Note: this is useless there to update
212 * the max_active_conns since we increase
213 * the idle count */
214 }
215 }
216 else {
217 /* there is no more appctx for this session
218 * it means it is ready to die
219 */
220 dns_session_free(ds);
221 }
222
223
224 }
225
226 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
227 }
Emeric Brund26a6232021-01-04 13:32:20 +0100228
229 return ret;
230}
231
232static void dns_resolve_recv(struct dgram_conn *dgram)
233{
234 struct dns_nameserver *ns;
235 int fd;
236
237 fd = dgram->t.sock.fd;
238
239 /* check if ready for reading */
240 if (!fd_recv_ready(fd))
241 return;
242
243 /* no need to go further if we can't retrieve the nameserver */
244 if ((ns = dgram->owner) == NULL) {
Willy Tarreauf5090652021-04-06 17:23:40 +0200245 _HA_ATOMIC_AND(&fdtab[fd].state, ~(FD_POLL_HUP|FD_POLL_ERR));
Emeric Brund26a6232021-01-04 13:32:20 +0100246 fd_stop_recv(fd);
247 return;
248 }
249
250 ns->process_responses(ns);
251}
252
253/* Called when a dns network socket is ready to send data */
254static void dns_resolve_send(struct dgram_conn *dgram)
255{
256 int fd;
257 struct dns_nameserver *ns;
258 struct ring *ring;
259 struct buffer *buf;
260 uint64_t msg_len;
261 size_t len, cnt, ofs;
262
263 fd = dgram->t.sock.fd;
264
265 /* check if ready for sending */
266 if (!fd_send_ready(fd))
267 return;
268
269 /* no need to go further if we can't retrieve the nameserver */
270 if ((ns = dgram->owner) == NULL) {
Willy Tarreauf5090652021-04-06 17:23:40 +0200271 _HA_ATOMIC_AND(&fdtab[fd].state, ~(FD_POLL_HUP|FD_POLL_ERR));
Emeric Brund26a6232021-01-04 13:32:20 +0100272 fd_stop_send(fd);
273 return;
274 }
275
276 ring = ns->dgram->ring_req;
277 buf = &ring->buf;
278
279 HA_RWLOCK_RDLOCK(DNS_LOCK, &ring->lock);
280 ofs = ns->dgram->ofs_req;
281
282 /* explanation for the initialization below: it would be better to do
283 * this in the parsing function but this would occasionally result in
284 * dropped events because we'd take a reference on the oldest message
285 * and keep it while being scheduled. Thus instead let's take it the
286 * first time we enter here so that we have a chance to pass many
287 * existing messages before grabbing a reference to a location. This
288 * value cannot be produced after initialization.
289 */
290 if (unlikely(ofs == ~0)) {
291 ofs = 0;
Willy Tarreau4781b152021-04-06 13:53:36 +0200292 HA_ATOMIC_INC(b_peek(buf, ofs));
Emeric Brund26a6232021-01-04 13:32:20 +0100293 ofs += ring->ofs;
294 }
295
296 /* we were already there, adjust the offset to be relative to
297 * the buffer's head and remove us from the counter.
298 */
299 ofs -= ring->ofs;
300 BUG_ON(ofs >= buf->size);
Willy Tarreau4781b152021-04-06 13:53:36 +0200301 HA_ATOMIC_DEC(b_peek(buf, ofs));
Emeric Brund26a6232021-01-04 13:32:20 +0100302
303 while (ofs + 1 < b_data(buf)) {
304 int ret;
305
306 cnt = 1;
307 len = b_peek_varint(buf, ofs + cnt, &msg_len);
308 if (!len)
309 break;
310 cnt += len;
311 BUG_ON(msg_len + ofs + cnt + 1 > b_data(buf));
312 if (unlikely(msg_len > DNS_TCP_MSG_MAX_SIZE)) {
313 /* too large a message to ever fit, let's skip it */
314 ofs += cnt + msg_len;
315 continue;
316 }
317
318 len = b_getblk(buf, dns_msg_trash, msg_len, ofs + cnt);
319
320 ret = send(fd, dns_msg_trash, len, 0);
321 if (ret < 0) {
322 if (errno == EAGAIN) {
323 fd_cant_send(fd);
324 goto out;
325 }
326 ns->counters->snd_error++;
327 fd_delete(fd);
Emeric Brund26a6232021-01-04 13:32:20 +0100328 fd = dgram->t.sock.fd = -1;
329 goto out;
330 }
331 ns->counters->sent++;
332
333 ofs += cnt + len;
334 }
335
336 /* we don't want/need to be waked up any more for sending
337 * because all ring content is sent */
338 fd_stop_send(fd);
339
340out:
341
Willy Tarreau4781b152021-04-06 13:53:36 +0200342 HA_ATOMIC_INC(b_peek(buf, ofs));
Emeric Brund26a6232021-01-04 13:32:20 +0100343 ofs += ring->ofs;
344 ns->dgram->ofs_req = ofs;
345 HA_RWLOCK_RDUNLOCK(DNS_LOCK, &ring->lock);
346
347}
348
Emeric Brunc9437992021-02-12 19:42:55 +0100349/* proto_udp callback functions for a DNS resolution */
350struct dgram_data_cb dns_dgram_cb = {
351 .recv = dns_resolve_recv,
352 .send = dns_resolve_send,
353};
Baptiste Assmann325137d2015-04-13 23:40:55 +0200354
Emeric Brunc9437992021-02-12 19:42:55 +0100355int dns_dgram_init(struct dns_nameserver *ns, struct sockaddr_storage *sk)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200356{
Emeric Brunc9437992021-02-12 19:42:55 +0100357 struct dns_dgram_server *dgram;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200358
Emeric Brunc9437992021-02-12 19:42:55 +0100359 if ((dgram = calloc(1, sizeof(*dgram))) == NULL)
Christopher Faulet67957bd2017-09-27 11:00:59 +0200360 return -1;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200361
Emeric Brunc9437992021-02-12 19:42:55 +0100362 /* Leave dgram partially initialized, no FD attached for
363 * now. */
364 dgram->conn.owner = ns;
365 dgram->conn.data = &dns_dgram_cb;
366 dgram->conn.t.sock.fd = -1;
367 dgram->conn.addr.to = *sk;
368 ns->dgram = dgram;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200369
Emeric Brunc9437992021-02-12 19:42:55 +0100370 dgram->ofs_req = ~0; /* init ring offset */
371 dgram->ring_req = ring_new(2*DNS_TCP_MSG_RING_MAX_SIZE);
372 if (!dgram->ring_req) {
373 ha_alert("memory allocation error initializing the ring for nameserver.\n");
374 goto out;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200375 }
376
Emeric Brunc9437992021-02-12 19:42:55 +0100377 /* attach the task as reader */
378 if (!ring_attach(dgram->ring_req)) {
379 /* mark server attached to the ring */
380 ha_alert("nameserver sets too many watchers > 255 on ring. This is a bug and should not happen.\n");
381 goto out;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200382 }
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200383 return 0;
Emeric Brunc9437992021-02-12 19:42:55 +0100384out:
385 if (dgram->ring_req)
386 ring_free(dgram->ring_req);
Christopher Fauletd6c6b5f2020-09-08 10:27:24 +0200387
Emeric Brunc9437992021-02-12 19:42:55 +0100388 free(dgram);
Olivier Houchard2ec2db92018-01-08 16:28:57 +0100389
Emeric Brunfd647d52021-02-12 20:03:38 +0100390 return -1;
391}
392
393/*
394 * IO Handler to handle message push to dns tcp server
395 */
396static void dns_session_io_handler(struct appctx *appctx)
397{
398 struct stream_interface *si = appctx->owner;
399 struct dns_session *ds = appctx->ctx.sft.ptr;
400 struct ring *ring = &ds->ring;
401 struct buffer *buf = &ring->buf;
402 uint64_t msg_len;
403 int available_room;
404 size_t len, cnt, ofs;
405 int ret = 0;
406
407 /* if stopping was requested, close immediately */
408 if (unlikely(stopping))
409 goto close;
410
411 /* we want to be sure to not miss that we have been awaked for a shutdown */
412 __ha_barrier_load();
413
414 /* that means the connection was requested to shutdown
415 * for instance idle expire */
416 if (ds->shutdown)
417 goto close;
418
419 /* an error was detected */
420 if (unlikely(si_ic(si)->flags & (CF_WRITE_ERROR|CF_SHUTW)))
421 goto close;
422
423 /* con closed by server side, we will skip data write and drain data from channel */
424 if ((si_oc(si)->flags & CF_SHUTW)) {
425 goto read;
426 }
427
428 /* if the connection is not established, inform the stream that we want
429 * to be notified whenever the connection completes.
430 */
431 if (si_opposite(si)->state < SI_ST_EST) {
432 si_cant_get(si);
433 si_rx_conn_blk(si);
434 si_rx_endp_more(si);
435 return;
436 }
437
438
439 ofs = ds->ofs;
440
441 HA_RWLOCK_WRLOCK(DNS_LOCK, &ring->lock);
442 LIST_DEL_INIT(&appctx->wait_entry);
443 HA_RWLOCK_WRUNLOCK(DNS_LOCK, &ring->lock);
444
445 HA_RWLOCK_RDLOCK(DNS_LOCK, &ring->lock);
446
447 /* explanation for the initialization below: it would be better to do
448 * this in the parsing function but this would occasionally result in
449 * dropped events because we'd take a reference on the oldest message
450 * and keep it while being scheduled. Thus instead let's take it the
451 * first time we enter here so that we have a chance to pass many
452 * existing messages before grabbing a reference to a location. This
453 * value cannot be produced after initialization.
454 */
455 if (unlikely(ofs == ~0)) {
456 ofs = 0;
457
Willy Tarreau4781b152021-04-06 13:53:36 +0200458 HA_ATOMIC_INC(b_peek(buf, ofs));
Emeric Brunfd647d52021-02-12 20:03:38 +0100459 ofs += ring->ofs;
460 }
461
462 /* in this loop, ofs always points to the counter byte that precedes
463 * the message so that we can take our reference there if we have to
464 * stop before the end (ret=0).
465 */
466 if (si_opposite(si)->state == SI_ST_EST) {
467 /* we were already there, adjust the offset to be relative to
468 * the buffer's head and remove us from the counter.
469 */
470 ofs -= ring->ofs;
471 BUG_ON(ofs >= buf->size);
Willy Tarreau4781b152021-04-06 13:53:36 +0200472 HA_ATOMIC_DEC(b_peek(buf, ofs));
Emeric Brunfd647d52021-02-12 20:03:38 +0100473
474 ret = 1;
475 while (ofs + 1 < b_data(buf)) {
476 struct dns_query *query;
477 uint16_t original_qid;
478 uint16_t new_qid;
479
480 cnt = 1;
481 len = b_peek_varint(buf, ofs + cnt, &msg_len);
482 if (!len)
483 break;
484 cnt += len;
485 BUG_ON(msg_len + ofs + cnt + 1 > b_data(buf));
486
487 /* retrieve available room on output channel */
488 available_room = channel_recv_max(si_ic(si));
489
490 /* tx_msg_offset null means we are at the start of a new message */
491 if (!ds->tx_msg_offset) {
492 uint16_t slen;
493
494 /* check if there is enough room to put message len and query id */
495 if (available_room < sizeof(slen) + sizeof(new_qid)) {
496 si_rx_room_blk(si);
497 ret = 0;
498 break;
499 }
500
501 /* put msg len into then channel */
502 slen = (uint16_t)msg_len;
503 slen = htons(slen);
504 ci_putblk(si_ic(si), (char *)&slen, sizeof(slen));
505 available_room -= sizeof(slen);
506
507 /* backup original query id */
508 len = b_getblk(buf, (char *)&original_qid, sizeof(original_qid), ofs + cnt);
Emeric Brun538bb042021-02-15 13:58:06 +0100509 if (!len) {
510 /* should never happen since messages are atomically
511 * written into ring
512 */
513 ret = 0;
514 break;
515 }
Emeric Brunfd647d52021-02-12 20:03:38 +0100516
517 /* generates new query id */
518 new_qid = ++ds->query_counter;
519 new_qid = htons(new_qid);
520
521 /* put new query id into the channel */
522 ci_putblk(si_ic(si), (char *)&new_qid, sizeof(new_qid));
523 available_room -= sizeof(new_qid);
524
525 /* keep query id mapping */
526
527 query = pool_alloc(dns_query_pool);
528 if (query) {
529 query->qid.key = new_qid;
530 query->original_qid = original_qid;
531 query->expire = tick_add(now_ms, 5000);
532 LIST_INIT(&query->list);
533 if (LIST_ISEMPTY(&ds->queries)) {
534 /* enable task to handle expire */
535 ds->task_exp->expire = query->expire;
536 /* ensure this will be executed by the same
537 * thread than ds_session_release
538 * to ensure session_release is free
539 * to destroy the task */
540 task_queue(ds->task_exp);
541 }
Willy Tarreau2b718102021-04-21 07:32:39 +0200542 LIST_APPEND(&ds->queries, &query->list);
Emeric Brunfd647d52021-02-12 20:03:38 +0100543 eb32_insert(&ds->query_ids, &query->qid);
544 ds->onfly_queries++;
545 }
546
547 /* update the tx_offset to handle output in 16k streams */
548 ds->tx_msg_offset = sizeof(original_qid);
549
550 }
551
552 /* check if it remains available room on output chan */
553 if (unlikely(!available_room)) {
554 si_rx_room_blk(si);
555 ret = 0;
556 break;
557 }
558
559 chunk_reset(&trash);
560 if ((msg_len - ds->tx_msg_offset) > available_room) {
561 /* remaining msg data is too large to be written in output channel at one time */
562
563 len = b_getblk(buf, trash.area, available_room, ofs + cnt + ds->tx_msg_offset);
564
565 /* update offset to complete mesg forwarding later */
566 ds->tx_msg_offset += len;
567 }
568 else {
569 /* remaining msg data can be written in output channel at one time */
570 len = b_getblk(buf, trash.area, msg_len - ds->tx_msg_offset, ofs + cnt + ds->tx_msg_offset);
571
572 /* reset tx_msg_offset to mark forward fully processed */
573 ds->tx_msg_offset = 0;
574 }
575 trash.data += len;
576
Emeric Brun743afee2021-02-15 14:12:06 +0100577 if (ci_putchk(si_ic(si), &trash) == -1) {
578 /* should never happen since we
579 * check available_room is large
Ilya Shipitsin0de36ad2021-02-20 00:23:36 +0500580 * enough here.
Emeric Brun743afee2021-02-15 14:12:06 +0100581 */
582 si_rx_room_blk(si);
583 ret = 0;
584 break;
585 }
Emeric Brunfd647d52021-02-12 20:03:38 +0100586
587 if (ds->tx_msg_offset) {
588 /* msg was not fully processed, we must be awake to drain pending data */
589
590 si_rx_room_blk(si);
591 ret = 0;
592 break;
593 }
594 /* switch to next message */
595 ofs += cnt + msg_len;
596 }
597
Willy Tarreau4781b152021-04-06 13:53:36 +0200598 HA_ATOMIC_INC(b_peek(buf, ofs));
Emeric Brunfd647d52021-02-12 20:03:38 +0100599 ofs += ring->ofs;
600 ds->ofs = ofs;
601 }
602 HA_RWLOCK_RDUNLOCK(DNS_LOCK, &ring->lock);
603
604 if (ret) {
605 /* let's be woken up once new request to write arrived */
606 HA_RWLOCK_WRLOCK(DNS_LOCK, &ring->lock);
Willy Tarreau2b718102021-04-21 07:32:39 +0200607 LIST_APPEND(&ring->waiters, &appctx->wait_entry);
Emeric Brunfd647d52021-02-12 20:03:38 +0100608 HA_RWLOCK_WRUNLOCK(DNS_LOCK, &ring->lock);
609 si_rx_endp_done(si);
610 }
611
612read:
613
Ilya Shipitsin0de36ad2021-02-20 00:23:36 +0500614 /* if session is not a waiter it means there is no committed
Emeric Brunfd647d52021-02-12 20:03:38 +0100615 * message into rx_buf and we are free to use it
616 * Note: we need a load barrier here to not miss the
617 * delete from the list
618 */
Emeric Brun9a6ac572021-10-20 10:49:53 +0200619
620 /* lock the dns_stream_server containing lists heads */
621 HA_SPIN_LOCK(DNS_LOCK, &ds->dss->lock);
622
Willy Tarreau2b718102021-04-21 07:32:39 +0200623 if (!LIST_INLIST(&ds->waiter)) {
Emeric Brunfd647d52021-02-12 20:03:38 +0100624 while (1) {
625 uint16_t query_id;
626 struct eb32_node *eb;
627 struct dns_query *query;
628
629 if (!ds->rx_msg.len) {
630 /* next message len is not fully available into the channel */
631 if (co_data(si_oc(si)) < 2)
632 break;
633
634 /* retrieve message len */
635 co_getblk(si_oc(si), (char *)&msg_len, 2, 0);
636
637 /* mark as consumed */
638 co_skip(si_oc(si), 2);
639
640 /* store message len */
641 ds->rx_msg.len = ntohs(msg_len);
642 }
643
644 if (!co_data(si_oc(si))) {
645 /* we need more data but nothing is available */
646 break;
647 }
648
649 if (co_data(si_oc(si)) + ds->rx_msg.offset < ds->rx_msg.len) {
650 /* message only partially available */
651
652 /* read available data */
653 co_getblk(si_oc(si), ds->rx_msg.area + ds->rx_msg.offset, co_data(si_oc(si)), 0);
654
655 /* update message offset */
656 ds->rx_msg.offset += co_data(si_oc(si));
657
658 /* consume all pending data from the channel */
659 co_skip(si_oc(si), co_data(si_oc(si)));
660
661 /* we need to wait for more data */
662 break;
663 }
664
Ilya Shipitsin0de36ad2021-02-20 00:23:36 +0500665 /* enough data is available into the channel to read the message until the end */
Emeric Brunfd647d52021-02-12 20:03:38 +0100666
667 /* read from the channel until the end of the message */
668 co_getblk(si_oc(si), ds->rx_msg.area + ds->rx_msg.offset, ds->rx_msg.len - ds->rx_msg.offset, 0);
669
670 /* consume all data until the end of the message from the channel */
671 co_skip(si_oc(si), ds->rx_msg.len - ds->rx_msg.offset);
672
673 /* reset reader offset to 0 for next message reand */
674 ds->rx_msg.offset = 0;
675
676 /* try remap query id to original */
677 memcpy(&query_id, ds->rx_msg.area, sizeof(query_id));
678 eb = eb32_lookup(&ds->query_ids, query_id);
679 if (!eb) {
680 /* query id not found means we have an unknown corresponding
681 * request, perhaps server's bug or or the query reached
682 * timeout
683 */
684 ds->rx_msg.len = 0;
685 continue;
686 }
687
688 /* re-map the original query id set by the requester */
689 query = eb32_entry(eb, struct dns_query, qid);
690 memcpy(ds->rx_msg.area, &query->original_qid, sizeof(query->original_qid));
691
692 /* remove query ids mapping from pending queries list/tree */
693 eb32_delete(&query->qid);
Willy Tarreau2b718102021-04-21 07:32:39 +0200694 LIST_DELETE(&query->list);
Emeric Brunfd647d52021-02-12 20:03:38 +0100695 pool_free(dns_query_pool, query);
696 ds->onfly_queries--;
697
Emeric Brunfd647d52021-02-12 20:03:38 +0100698 /* the dns_session is also added in queue of the
699 * wait_sess list where the task processing
700 * response will pop available responses
701 */
Willy Tarreau2b718102021-04-21 07:32:39 +0200702 LIST_APPEND(&ds->dss->wait_sess, &ds->waiter);
Emeric Brunfd647d52021-02-12 20:03:38 +0100703
Emeric Brunfd647d52021-02-12 20:03:38 +0100704 /* awake the task processing the responses */
705 task_wakeup(ds->dss->task_rsp, TASK_WOKEN_INIT);
706
707 break;
708 }
709
Willy Tarreau2b718102021-04-21 07:32:39 +0200710 if (!LIST_INLIST(&ds->waiter)) {
Emeric Brunfd647d52021-02-12 20:03:38 +0100711 /* there is no more pending data to read and the con was closed by the server side */
712 if (!co_data(si_oc(si)) && (si_oc(si)->flags & CF_SHUTW)) {
Emeric Brun9a6ac572021-10-20 10:49:53 +0200713 HA_SPIN_UNLOCK(DNS_LOCK, &ds->dss->lock);
Emeric Brunfd647d52021-02-12 20:03:38 +0100714 goto close;
715 }
716 }
717
718 }
719
Emeric Brun9a6ac572021-10-20 10:49:53 +0200720 HA_SPIN_UNLOCK(DNS_LOCK, &ds->dss->lock);
Emeric Brunfd647d52021-02-12 20:03:38 +0100721 return;
722close:
723 si_shutw(si);
724 si_shutr(si);
725 si_ic(si)->flags |= CF_READ_NULL;
726}
727
728void dns_queries_flush(struct dns_session *ds)
729{
730 struct dns_query *query, *queryb;
731
732 list_for_each_entry_safe(query, queryb, &ds->queries, list) {
733 eb32_delete(&query->qid);
Willy Tarreau2b718102021-04-21 07:32:39 +0200734 LIST_DELETE(&query->list);
Emeric Brunfd647d52021-02-12 20:03:38 +0100735 pool_free(dns_query_pool, query);
736 }
737}
738
739void dns_session_free(struct dns_session *ds)
740{
741 if (ds->rx_msg.area)
742 pool_free(dns_msg_buf, ds->rx_msg.area);
743 if (ds->tx_ring_area)
744 pool_free(dns_msg_buf, ds->tx_ring_area);
745 if (ds->task_exp)
746 task_destroy(ds->task_exp);
747
748 dns_queries_flush(ds);
749
Emeric Brunb18a95b2021-10-19 15:40:10 +0200750 /* Ensure to remove this session from external lists
751 * Note: we are under the lock of dns_stream_server
752 * which own the heads of those lists.
753 */
754 LIST_DEL_INIT(&ds->waiter);
755 LIST_DEL_INIT(&ds->list);
756
Emeric Brunfd647d52021-02-12 20:03:38 +0100757 ds->dss->cur_conns--;
758 /* Note: this is useless to update
759 * max_active_conns here because
760 * we decrease the value
761 */
762 pool_free(dns_session_pool, ds);
763}
764
765static struct appctx *dns_session_create(struct dns_session *ds);
766
767/*
768 * Function to release a DNS tcp session
769 */
770static void dns_session_release(struct appctx *appctx)
771{
772 struct dns_session *ds = appctx->ctx.sft.ptr;
Willy Tarreaue3e648c2021-02-24 17:38:46 +0100773 struct dns_stream_server *dss __maybe_unused;
Emeric Brunfd647d52021-02-12 20:03:38 +0100774
775 if (!ds)
776 return;
777
778 dss = ds->dss;
779
780 HA_SPIN_LOCK(DNS_LOCK, &dss->lock);
781 LIST_DEL_INIT(&ds->list);
782
783 if (stopping) {
784 dns_session_free(ds);
785 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
786 return;
787 }
788
789 if (!ds->nb_queries) {
790 /* this is an idle session */
791 /* Note: this is useless to update max_active_sess
792 * here because we decrease idle_conns but
793 * dns_session_free decrease curconns
794 */
795
796 ds->dss->idle_conns--;
797 dns_session_free(ds);
798 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
799 return;
800 }
801
802 if (ds->onfly_queries == ds->nb_queries) {
803 /* the session can be released because
804 * it means that all queries AND
805 * responses are in fly */
806 dns_session_free(ds);
807 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
808 return;
809 }
810
811 /* We do not call ring_appctx_detach here
812 * because we want to keep readers counters
813 * to retry a con with a different appctx*/
814 HA_RWLOCK_WRLOCK(DNS_LOCK, &ds->ring.lock);
815 LIST_DEL_INIT(&appctx->wait_entry);
816 HA_RWLOCK_WRUNLOCK(DNS_LOCK, &ds->ring.lock);
817
818 /* if there is no pending complete response
819 * message, ensure to reset
820 * message offsets if the session
821 * was closed with an incomplete pending response
822 */
Willy Tarreau2b718102021-04-21 07:32:39 +0200823 if (!LIST_INLIST(&ds->waiter))
Emeric Brunfd647d52021-02-12 20:03:38 +0100824 ds->rx_msg.len = ds->rx_msg.offset = 0;
825
826 /* we flush pending sent queries because we never
827 * have responses
828 */
829 ds->nb_queries -= ds->onfly_queries;
830 dns_queries_flush(ds);
831
832 /* reset offset to be sure to start from message start */
833 ds->tx_msg_offset = 0;
834
835 /* here the ofs and the attached counter
836 * are kept unchanged
837 */
838
839 /* Create a new appctx, We hope we can
840 * create from the release callback! */
841 ds->appctx = dns_session_create(ds);
842 if (!ds->appctx) {
843 dns_session_free(ds);
844 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
845 return;
846 }
847
848 if (ds->nb_queries < DNS_STREAM_MAX_PIPELINED_REQ)
Willy Tarreau2b718102021-04-21 07:32:39 +0200849 LIST_INSERT(&ds->dss->free_sess, &ds->list);
Emeric Brunfd647d52021-02-12 20:03:38 +0100850
851 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
852}
853
854/* DNS tcp session applet */
855static struct applet dns_session_applet = {
856 .obj_type = OBJ_TYPE_APPLET,
857 .name = "<STRMDNS>", /* used for logging */
858 .fct = dns_session_io_handler,
859 .release = dns_session_release,
860};
861
862/*
863 * Function used to create an appctx for a DNS session
864 */
865static struct appctx *dns_session_create(struct dns_session *ds)
866{
867 struct appctx *appctx;
868 struct session *sess;
869 struct stream *s;
870 struct applet *applet = &dns_session_applet;
871
872 appctx = appctx_new(applet, tid_bit);
873 if (!appctx)
874 goto out_close;
875
876 appctx->ctx.sft.ptr = (void *)ds;
877
878 sess = session_new(ds->dss->srv->proxy, NULL, &appctx->obj_type);
879 if (!sess) {
880 ha_alert("out of memory in peer_session_create().\n");
881 goto out_free_appctx;
882 }
883
884 if ((s = stream_new(sess, &appctx->obj_type, &BUF_NULL)) == NULL) {
885 ha_alert("Failed to initialize stream in peer_session_create().\n");
886 goto out_free_sess;
887 }
888
889
890 s->target = &ds->dss->srv->obj_type;
891 if (!sockaddr_alloc(&s->target_addr, &ds->dss->srv->addr, sizeof(ds->dss->srv->addr)))
892 goto out_free_strm;
893 s->flags = SF_ASSIGNED|SF_ADDR_SET;
894 s->si[1].flags |= SI_FL_NOLINGER;
895
896 s->do_log = NULL;
897 s->uniq_id = 0;
898
899 s->res.flags |= CF_READ_DONTWAIT;
900 /* for rto and rex to eternity to not expire on idle recv:
901 * We are using a syslog server.
902 */
903 s->res.rto = TICK_ETERNITY;
904 s->res.rex = TICK_ETERNITY;
905 ds->appctx = appctx;
906 task_wakeup(s->task, TASK_WOKEN_INIT);
907 return appctx;
908
909 /* Error unrolling */
910 out_free_strm:
Willy Tarreau2b718102021-04-21 07:32:39 +0200911 LIST_DELETE(&s->list);
Emeric Brunfd647d52021-02-12 20:03:38 +0100912 pool_free(pool_head_stream, s);
913 out_free_sess:
914 session_free(sess);
915 out_free_appctx:
916 appctx_free(appctx);
917 out_close:
918 return NULL;
919}
920
921/* Task processing expiration of unresponded queries, this one is supposed
922 * to be stuck on the same thread than the appctx handler
923 */
Willy Tarreau144f84a2021-03-02 16:09:26 +0100924static struct task *dns_process_query_exp(struct task *t, void *context, unsigned int state)
Emeric Brunfd647d52021-02-12 20:03:38 +0100925{
926 struct dns_session *ds = (struct dns_session *)context;
927 struct dns_query *query, *queryb;
928
929 t->expire = TICK_ETERNITY;
930
931 list_for_each_entry_safe(query, queryb, &ds->queries, list) {
932 if (tick_is_expired(query->expire, now_ms)) {
933 eb32_delete(&query->qid);
Willy Tarreau2b718102021-04-21 07:32:39 +0200934 LIST_DELETE(&query->list);
Emeric Brunfd647d52021-02-12 20:03:38 +0100935 pool_free(dns_query_pool, query);
936 ds->onfly_queries--;
937 }
938 else {
939 t->expire = query->expire;
940 break;
941 }
942 }
943
944 return t;
945}
946
947/* Task processing expiration of idle sessions */
Willy Tarreau144f84a2021-03-02 16:09:26 +0100948static struct task *dns_process_idle_exp(struct task *t, void *context, unsigned int state)
Emeric Brunfd647d52021-02-12 20:03:38 +0100949{
950 struct dns_stream_server *dss = (struct dns_stream_server *)context;
951 struct dns_session *ds, *dsb;
952 int target = 0;
953 int cur_active_conns;
954
955 HA_SPIN_LOCK(DNS_LOCK, &dss->lock);
956
957
958 cur_active_conns = dss->cur_conns - dss->idle_conns;
959 if (cur_active_conns > dss->max_active_conns)
960 dss->max_active_conns = cur_active_conns;
961
962 target = (dss->max_active_conns - cur_active_conns) / 2;
963 list_for_each_entry_safe(ds, dsb, &dss->idle_sess, list) {
964 if (!target)
965 break;
966
967 /* remove conn to pending list to ensure it won't be reused */
968 LIST_DEL_INIT(&ds->list);
969
970 /* force session shutdown */
971 ds->shutdown = 1;
972
Ilya Shipitsin0de36ad2021-02-20 00:23:36 +0500973 /* to be sure that the appctx won't miss shutdown */
Emeric Brunfd647d52021-02-12 20:03:38 +0100974 __ha_barrier_store();
975
976 /* wake appctx to perform the shutdown */
977 appctx_wakeup(ds->appctx);
978 }
979
980 /* reset max to current active conns */
981 dss->max_active_conns = cur_active_conns;
982
983 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
984
985 t->expire = tick_add(now_ms, 5000);
986
987 return t;
988}
989
990struct dns_session *dns_session_new(struct dns_stream_server *dss)
991{
992 struct dns_session *ds;
993
994 if (dss->maxconn && (dss->maxconn <= dss->cur_conns))
995 return NULL;
996
997 ds = pool_alloc(dns_session_pool);
998 if (!ds)
999 return NULL;
1000
1001 ds->ofs = ~0;
1002 ds->dss = dss;
1003 LIST_INIT(&ds->list);
1004 LIST_INIT(&ds->queries);
1005 LIST_INIT(&ds->waiter);
1006 ds->rx_msg.offset = ds->rx_msg.len = 0;
1007 ds->rx_msg.area = NULL;
1008 ds->tx_ring_area = NULL;
1009 ds->task_exp = NULL;
1010 ds->appctx = NULL;
1011 ds->shutdown = 0;
1012 ds->nb_queries = 0;
1013 ds->query_ids = EB_ROOT_UNIQUE;
1014 ds->rx_msg.area = pool_alloc(dns_msg_buf);
1015 if (!ds->rx_msg.area)
1016 goto error;
1017
1018 ds->tx_ring_area = pool_alloc(dns_msg_buf);
1019 if (!ds->tx_ring_area)
1020 goto error;
1021
1022 ring_init(&ds->ring, ds->tx_ring_area, DNS_TCP_MSG_RING_MAX_SIZE);
Christopher Faulet1a1b6742021-03-04 16:53:27 +01001023 /* never fail because it is the first watcher attached to the ring */
1024 DISGUISE(ring_attach(&ds->ring));
Emeric Brunfd647d52021-02-12 20:03:38 +01001025
1026 if ((ds->task_exp = task_new(tid_bit)) == NULL)
1027 goto error;
1028
1029 ds->task_exp->process = dns_process_query_exp;
1030 ds->task_exp->context = ds;
1031
1032 ds->appctx = dns_session_create(ds);
1033 if (!ds->appctx)
1034 goto error;
1035
1036 dss->cur_conns++;
1037
1038 return ds;
1039
1040error:
1041 if (ds->task_exp)
1042 task_destroy(ds->task_exp);
1043 if (ds->rx_msg.area)
1044 pool_free(dns_msg_buf, ds->rx_msg.area);
1045 if (ds->tx_ring_area)
1046 pool_free(dns_msg_buf, ds->tx_ring_area);
1047
1048 pool_free(dns_session_pool, ds);
1049
1050 return NULL;
1051}
1052
1053/*
1054 * Task used to consume pending messages from nameserver ring
1055 * and forward them to dns_session ring.
1056 * Note: If no slot found a new dns_session is allocated
1057 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01001058static struct task *dns_process_req(struct task *t, void *context, unsigned int state)
Emeric Brunfd647d52021-02-12 20:03:38 +01001059{
1060 struct dns_nameserver *ns = (struct dns_nameserver *)context;
1061 struct dns_stream_server *dss = ns->stream;
1062 struct ring *ring = dss->ring_req;
1063 struct buffer *buf = &ring->buf;
1064 uint64_t msg_len;
1065 size_t len, cnt, ofs;
1066 struct dns_session *ds, *ads;
1067 HA_SPIN_LOCK(DNS_LOCK, &dss->lock);
1068
1069 ofs = dss->ofs_req;
1070
1071 HA_RWLOCK_RDLOCK(DNS_LOCK, &ring->lock);
1072
1073 /* explanation for the initialization below: it would be better to do
1074 * this in the parsing function but this would occasionally result in
1075 * dropped events because we'd take a reference on the oldest message
1076 * and keep it while being scheduled. Thus instead let's take it the
1077 * first time we enter here so that we have a chance to pass many
1078 * existing messages before grabbing a reference to a location. This
1079 * value cannot be produced after initialization.
1080 */
1081 if (unlikely(ofs == ~0)) {
1082 ofs = 0;
Willy Tarreau4781b152021-04-06 13:53:36 +02001083 HA_ATOMIC_INC(b_peek(buf, ofs));
Emeric Brunfd647d52021-02-12 20:03:38 +01001084 ofs += ring->ofs;
1085 }
1086
1087 /* we were already there, adjust the offset to be relative to
1088 * the buffer's head and remove us from the counter.
1089 */
1090 ofs -= ring->ofs;
1091 BUG_ON(ofs >= buf->size);
Willy Tarreau4781b152021-04-06 13:53:36 +02001092 HA_ATOMIC_DEC(b_peek(buf, ofs));
Emeric Brunfd647d52021-02-12 20:03:38 +01001093
1094 while (ofs + 1 < b_data(buf)) {
1095 struct ist myist;
1096
1097 cnt = 1;
1098 len = b_peek_varint(buf, ofs + cnt, &msg_len);
1099 if (!len)
1100 break;
1101 cnt += len;
1102 BUG_ON(msg_len + ofs + cnt + 1 > b_data(buf));
1103 if (unlikely(msg_len > DNS_TCP_MSG_MAX_SIZE)) {
1104 /* too large a message to ever fit, let's skip it */
1105 ofs += cnt + msg_len;
1106 continue;
1107 }
1108
1109 len = b_getblk(buf, dns_msg_trash, msg_len, ofs + cnt);
1110
Tim Duesterhus92c696e2021-02-28 16:11:36 +01001111 myist = ist2(dns_msg_trash, len);
Emeric Brunfd647d52021-02-12 20:03:38 +01001112
1113 ads = NULL;
Ilya Shipitsin0de36ad2021-02-20 00:23:36 +05001114 /* try to push request into active sess with free slot */
Emeric Brunfd647d52021-02-12 20:03:38 +01001115 if (!LIST_ISEMPTY(&dss->free_sess)) {
1116 ds = LIST_NEXT(&dss->free_sess, struct dns_session *, list);
1117
1118 if (ring_write(&ds->ring, DNS_TCP_MSG_MAX_SIZE, NULL, 0, &myist, 1) > 0) {
1119 ds->nb_queries++;
1120 if (ds->nb_queries >= DNS_STREAM_MAX_PIPELINED_REQ)
1121 LIST_DEL_INIT(&ds->list);
1122 ads = ds;
1123 }
1124 else {
1125 /* it means we were unable to put a request in this slot,
1126 * it may be close to be full so we put it at the end
1127 * of free conn list */
1128 LIST_DEL_INIT(&ds->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02001129 LIST_APPEND(&dss->free_sess, &ds->list);
Emeric Brunfd647d52021-02-12 20:03:38 +01001130 }
1131 }
1132
1133 if (!ads) {
Ilya Shipitsin0de36ad2021-02-20 00:23:36 +05001134 /* try to push request into idle, this one should have enough free space */
Emeric Brunfd647d52021-02-12 20:03:38 +01001135 if (!LIST_ISEMPTY(&dss->idle_sess)) {
1136 ds = LIST_NEXT(&dss->idle_sess, struct dns_session *, list);
1137
1138 /* ring is empty so this ring_write should never fail */
1139 ring_write(&ds->ring, DNS_TCP_MSG_MAX_SIZE, NULL, 0, &myist, 1);
1140 ds->nb_queries++;
1141 LIST_DEL_INIT(&ds->list);
1142
1143 ds->dss->idle_conns--;
1144
1145 /* we may have to update the max_active_conns */
1146 if (ds->dss->max_active_conns < ds->dss->cur_conns - ds->dss->idle_conns)
1147 ds->dss->max_active_conns = ds->dss->cur_conns - ds->dss->idle_conns;
1148
1149 /* since we may unable to find a free list to handle
1150 * this request, this request may be large and fill
1151 * the ring buffer so we prefer to put at the end of free
1152 * list. */
Willy Tarreau2b718102021-04-21 07:32:39 +02001153 LIST_APPEND(&dss->free_sess, &ds->list);
Emeric Brunfd647d52021-02-12 20:03:38 +01001154 ads = ds;
1155 }
1156 }
1157
Ilya Shipitsin0de36ad2021-02-20 00:23:36 +05001158 /* we didn't find a session available with large enough room */
Emeric Brunfd647d52021-02-12 20:03:38 +01001159 if (!ads) {
1160 /* allocate a new session */
1161 ads = dns_session_new(dss);
1162 if (ads) {
1163 /* ring is empty so this ring_write should never fail */
1164 ring_write(&ads->ring, DNS_TCP_MSG_MAX_SIZE, NULL, 0, &myist, 1);
1165 ads->nb_queries++;
Willy Tarreau2b718102021-04-21 07:32:39 +02001166 LIST_INSERT(&dss->free_sess, &ads->list);
Emeric Brunfd647d52021-02-12 20:03:38 +01001167 }
1168 else
1169 ns->counters->snd_error++;
1170 }
1171
1172 if (ads)
1173 ns->counters->sent++;
1174
1175 ofs += cnt + len;
1176 }
1177
Willy Tarreau4781b152021-04-06 13:53:36 +02001178 HA_ATOMIC_INC(b_peek(buf, ofs));
Emeric Brunfd647d52021-02-12 20:03:38 +01001179 ofs += ring->ofs;
1180 dss->ofs_req = ofs;
1181 HA_RWLOCK_RDUNLOCK(DNS_LOCK, &ring->lock);
1182
1183
1184 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
1185 return t;
1186}
1187
1188/*
1189 * Task used to consume response
1190 * Note: upper layer callback is called
1191 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01001192static struct task *dns_process_rsp(struct task *t, void *context, unsigned int state)
Emeric Brunfd647d52021-02-12 20:03:38 +01001193{
1194 struct dns_nameserver *ns = (struct dns_nameserver *)context;
1195
1196 ns->process_responses(ns);
1197
1198 return t;
1199}
1200
1201/* Function used to initialize an TCP nameserver */
1202int dns_stream_init(struct dns_nameserver *ns, struct server *srv)
1203{
1204 struct dns_stream_server *dss = NULL;
1205
1206 dss = calloc(1, sizeof(*dss));
1207 if (!dss) {
1208 ha_alert("memory allocation error initializing dns tcp server '%s'.\n", srv->id);
1209 goto out;
1210 }
1211
1212 dss->srv = srv;
1213 dss->maxconn = srv->maxconn;
1214
1215 dss->ofs_req = ~0; /* init ring offset */
1216 dss->ring_req = ring_new(2*DNS_TCP_MSG_RING_MAX_SIZE);
1217 if (!dss->ring_req) {
1218 ha_alert("memory allocation error initializing the ring for dns tcp server '%s'.\n", srv->id);
1219 goto out;
1220 }
1221 /* Create the task associated to the resolver target handling conns */
1222 if ((dss->task_req = task_new(MAX_THREADS_MASK)) == NULL) {
1223 ha_alert("memory allocation error initializing the ring for dns tcp server '%s'.\n", srv->id);
1224 goto out;
1225 }
1226
1227 /* Update task's parameters */
1228 dss->task_req->process = dns_process_req;
1229 dss->task_req->context = ns;
1230
1231 /* attach the task as reader */
1232 if (!ring_attach(dss->ring_req)) {
1233 /* mark server attached to the ring */
1234 ha_alert("server '%s': too many watchers for ring. this should never happen.\n", srv->id);
1235 goto out;
1236 }
1237
1238 /* Create the task associated to the resolver target handling conns */
1239 if ((dss->task_rsp = task_new(MAX_THREADS_MASK)) == NULL) {
1240 ha_alert("memory allocation error initializing the ring for dns tcp server '%s'.\n", srv->id);
1241 goto out;
1242 }
1243
1244 /* Update task's parameters */
1245 dss->task_rsp->process = dns_process_rsp;
1246 dss->task_rsp->context = ns;
1247
1248 /* Create the task associated to the resolver target handling conns */
1249 if ((dss->task_idle = task_new(MAX_THREADS_MASK)) == NULL) {
1250 ha_alert("memory allocation error initializing the ring for dns tcp server '%s'.\n", srv->id);
1251 goto out;
1252 }
1253
1254 /* Update task's parameters */
1255 dss->task_idle->process = dns_process_idle_exp;
1256 dss->task_idle->context = dss;
1257 dss->task_idle->expire = tick_add(now_ms, 5000);
1258
Ilya Shipitsin0de36ad2021-02-20 00:23:36 +05001259 /* let start the task to free idle conns immediately */
Emeric Brunfd647d52021-02-12 20:03:38 +01001260 task_queue(dss->task_idle);
1261
1262 LIST_INIT(&dss->free_sess);
1263 LIST_INIT(&dss->idle_sess);
1264 LIST_INIT(&dss->wait_sess);
1265 HA_SPIN_INIT(&dss->lock);
1266 ns->stream = dss;
1267 return 0;
1268out:
1269 if (dss && dss->task_rsp)
1270 task_destroy(dss->task_rsp);
1271 if (dss && dss->task_req)
1272 task_destroy(dss->task_req);
1273 if (dss && dss->ring_req)
1274 ring_free(dss->ring_req);
1275
1276 free(dss);
Emeric Brunc9437992021-02-12 19:42:55 +01001277 return -1;
Christopher Faulet67957bd2017-09-27 11:00:59 +02001278}
1279
Emeric Brunc9437992021-02-12 19:42:55 +01001280int init_dns_buffers()
Baptiste Assmann325137d2015-04-13 23:40:55 +02001281{
Emeric Brunc9437992021-02-12 19:42:55 +01001282 dns_msg_trash = malloc(DNS_TCP_MSG_MAX_SIZE);
1283 if (!dns_msg_trash)
1284 return 0;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001285
Emeric Brunc9437992021-02-12 19:42:55 +01001286 return 1;
1287}
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001288
Emeric Brunc9437992021-02-12 19:42:55 +01001289void deinit_dns_buffers()
1290{
Willy Tarreau61cfdf42021-02-20 10:46:51 +01001291 ha_free(&dns_msg_trash);
Emeric Brunc9437992021-02-12 19:42:55 +01001292}
Emeric Brund26a6232021-01-04 13:32:20 +01001293
1294REGISTER_PER_THREAD_ALLOC(init_dns_buffers);
1295REGISTER_PER_THREAD_FREE(deinit_dns_buffers);