blob: 9251bec3a27a4836080144dfae3b806d63755387 [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>
Baptiste Assmann325137d2015-04-13 23:40:55 +020014#include <stdio.h>
15#include <stdlib.h>
16#include <string.h>
17#include <unistd.h>
18
19#include <sys/types.h>
20
Willy Tarreau122eba92020-06-04 10:15:32 +020021#include <haproxy/action.h>
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020022#include <haproxy/api.h>
Christopher Faulet6b0a0fb2022-04-04 11:29:28 +020023#include <haproxy/applet.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>
Christopher Faulet908628c2022-03-25 16:43:49 +010028#include <haproxy/conn_stream.h>
29#include <haproxy/cs_utils.h>
Willy Tarreau7c18b542020-06-11 09:23:02 +020030#include <haproxy/dgram.h>
Willy Tarreaueb92deb2020-06-04 10:53:16 +020031#include <haproxy/dns.h>
Willy Tarreau8d366972020-05-27 16:10:29 +020032#include <haproxy/errors.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020033#include <haproxy/fd.h>
Willy Tarreauaeed4a82020-06-04 22:01:04 +020034#include <haproxy/log.h>
Emeric Brund26a6232021-01-04 13:32:20 +010035#include <haproxy/ring.h>
Emeric Brunfd647d52021-02-12 20:03:38 +010036#include <haproxy/stream.h>
Willy Tarreau9f9e9fc2021-05-08 13:09:46 +020037#include <haproxy/tools.h>
Baptiste Assmann325137d2015-04-13 23:40:55 +020038
Emeric Brund26a6232021-01-04 13:32:20 +010039static THREAD_LOCAL char *dns_msg_trash;
Baptiste Assmann325137d2015-04-13 23:40:55 +020040
Emeric Brunfd647d52021-02-12 20:03:38 +010041DECLARE_STATIC_POOL(dns_session_pool, "dns_session", sizeof(struct dns_session));
42DECLARE_STATIC_POOL(dns_query_pool, "dns_query", sizeof(struct dns_query));
43DECLARE_STATIC_POOL(dns_msg_buf, "dns_msg_buf", DNS_TCP_MSG_RING_MAX_SIZE);
44
Christopher Faulet67957bd2017-09-27 11:00:59 +020045/* Opens an UDP socket on the namesaver's IP/Port, if required. Returns 0 on
Christopher Faulet1e711be2021-03-04 16:58:35 +010046 * success, -1 otherwise. ns->dgram must be defined.
Baptiste Assmann325137d2015-04-13 23:40:55 +020047 */
Emeric Brund26a6232021-01-04 13:32:20 +010048static int dns_connect_nameserver(struct dns_nameserver *ns)
Baptiste Assmann325137d2015-04-13 23:40:55 +020049{
Christopher Faulet1e711be2021-03-04 16:58:35 +010050 struct dgram_conn *dgram = &ns->dgram->conn;
51 int fd;
Baptiste Assmann325137d2015-04-13 23:40:55 +020052
Christopher Faulet1e711be2021-03-04 16:58:35 +010053 /* Already connected */
54 if (dgram->t.sock.fd != -1)
Emeric Brun526b7922021-02-15 14:28:27 +010055 return 0;
Christopher Faulet1e711be2021-03-04 16:58:35 +010056
57 /* Create an UDP socket and connect it on the nameserver's IP/Port */
58 if ((fd = socket(dgram->addr.to.ss_family, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
59 send_log(NULL, LOG_WARNING,
60 "DNS : section '%s': can't create socket for nameserver '%s'.\n",
61 ns->counters->pid, ns->id);
62 return -1;
63 }
64 if (connect(fd, (struct sockaddr*)&dgram->addr.to, get_addr_len(&dgram->addr.to)) == -1) {
65 send_log(NULL, LOG_WARNING,
66 "DNS : section '%s': can't connect socket for nameserver '%s'.\n",
67 ns->counters->id, ns->id);
68 close(fd);
69 return -1;
Emeric Brunc9437992021-02-12 19:42:55 +010070 }
Emeric Brun526b7922021-02-15 14:28:27 +010071
Christopher Faulet1e711be2021-03-04 16:58:35 +010072 /* Make the socket non blocking */
Willy Tarreau38247432022-04-26 10:24:14 +020073 fd_set_nonblock(fd);
Christopher Faulet1e711be2021-03-04 16:58:35 +010074
75 /* Add the fd in the fd list and update its parameters */
76 dgram->t.sock.fd = fd;
77 fd_insert(fd, dgram, dgram_fd_handler, MAX_THREADS_MASK);
78 fd_want_recv(fd);
79 return 0;
Baptiste Assmann325137d2015-04-13 23:40:55 +020080}
81
Emeric Brund26a6232021-01-04 13:32:20 +010082/* Sends a message to a name server
83 * It returns message length on success
84 * or -1 in error case
85 * 0 is returned in case of output ring buffer is full
86 */
87int dns_send_nameserver(struct dns_nameserver *ns, void *buf, size_t len)
88{
89 int ret = -1;
90
91 if (ns->dgram) {
92 struct dgram_conn *dgram = &ns->dgram->conn;
93 int fd = dgram->t.sock.fd;
94
95 if (dgram->t.sock.fd == -1) {
96 if (dns_connect_nameserver(ns) == -1)
97 return -1;
98 fd = dgram->t.sock.fd;
99 }
100
101 ret = send(fd, buf, len, 0);
102 if (ret < 0) {
Willy Tarreauacef5e22022-04-25 20:32:15 +0200103 if (errno == EAGAIN || errno == EWOULDBLOCK) {
Emeric Brund26a6232021-01-04 13:32:20 +0100104 struct ist myist;
105
Tim Duesterhus92c696e2021-02-28 16:11:36 +0100106 myist = ist2(buf, len);
Emeric Brund26a6232021-01-04 13:32:20 +0100107 ret = ring_write(ns->dgram->ring_req, DNS_TCP_MSG_MAX_SIZE, NULL, 0, &myist, 1);
108 if (!ret) {
109 ns->counters->snd_error++;
110 return -1;
111 }
112 fd_cant_send(fd);
113 return ret;
114 }
115 ns->counters->snd_error++;
116 fd_delete(fd);
Emeric Brund26a6232021-01-04 13:32:20 +0100117 dgram->t.sock.fd = -1;
118 return -1;
119 }
120 ns->counters->sent++;
121 }
Emeric Brunfd647d52021-02-12 20:03:38 +0100122 else if (ns->stream) {
123 struct ist myist;
124
Tim Duesterhus92c696e2021-02-28 16:11:36 +0100125 myist = ist2(buf, len);
Emeric Brunfd647d52021-02-12 20:03:38 +0100126 ret = ring_write(ns->stream->ring_req, DNS_TCP_MSG_MAX_SIZE, NULL, 0, &myist, 1);
127 if (!ret) {
128 ns->counters->snd_error++;
129 return -1;
130 }
131 task_wakeup(ns->stream->task_req, TASK_WOKEN_MSG);
132 return ret;
133 }
Emeric Brund26a6232021-01-04 13:32:20 +0100134
135 return ret;
136}
137
Emeric Brunfd647d52021-02-12 20:03:38 +0100138void dns_session_free(struct dns_session *);
139
Emeric Brund26a6232021-01-04 13:32:20 +0100140/* Receives a dns message
141 * Returns message length
142 * 0 is returned if no more message available
143 * -1 in error case
144 */
145ssize_t dns_recv_nameserver(struct dns_nameserver *ns, void *data, size_t size)
146{
147 ssize_t ret = -1;
148
149 if (ns->dgram) {
150 struct dgram_conn *dgram = &ns->dgram->conn;
151 int fd = dgram->t.sock.fd;
152
153 if (fd == -1)
154 return -1;
155
156 if ((ret = recv(fd, data, size, 0)) < 0) {
Willy Tarreauacef5e22022-04-25 20:32:15 +0200157 if (errno == EAGAIN || errno == EWOULDBLOCK) {
Emeric Brund26a6232021-01-04 13:32:20 +0100158 fd_cant_recv(fd);
159 return 0;
160 }
161 fd_delete(fd);
Emeric Brund26a6232021-01-04 13:32:20 +0100162 dgram->t.sock.fd = -1;
163 return -1;
164 }
165 }
Emeric Brunfd647d52021-02-12 20:03:38 +0100166 else if (ns->stream) {
167 struct dns_stream_server *dss = ns->stream;
168 struct dns_session *ds;
169
170 HA_SPIN_LOCK(DNS_LOCK, &dss->lock);
171
172 if (!LIST_ISEMPTY(&dss->wait_sess)) {
173 ds = LIST_NEXT(&dss->wait_sess, struct dns_session *, waiter);
Emeric Brunfd647d52021-02-12 20:03:38 +0100174 ret = ds->rx_msg.len < size ? ds->rx_msg.len : size;
175 memcpy(data, ds->rx_msg.area, ret);
176
177 ds->rx_msg.len = 0;
178
Willy Tarreaudde1b442021-10-21 14:33:38 +0200179 /* This barrier is here to ensure that all data is
180 * stored if the appctx detect the elem is out of the
181 * list.
182 */
183 __ha_barrier_store();
184
Emeric Brunfd647d52021-02-12 20:03:38 +0100185 LIST_DEL_INIT(&ds->waiter);
186
187 if (ds->appctx) {
Willy Tarreaudde1b442021-10-21 14:33:38 +0200188 /* This second barrier is here to ensure that
189 * the waked up appctx won't miss that the elem
190 * is removed from the list.
191 */
192 __ha_barrier_store();
193
Ilya Shipitsin0de36ad2021-02-20 00:23:36 +0500194 /* awake appctx because it may have other
Emeric Brunfd647d52021-02-12 20:03:38 +0100195 * message to receive
196 */
197 appctx_wakeup(ds->appctx);
198
199 /* dns_session could already be into free_sess list
200 * so we firstly remove it */
201 LIST_DEL_INIT(&ds->list);
202
203 /* decrease nb_queries to free a slot for a new query on that sess */
204 ds->nb_queries--;
205 if (ds->nb_queries) {
206 /* it remains pipelined unanswered request
207 * into this session but we just decrease
208 * the counter so the session
209 * can not be full of pipelined requests
210 * so we can add if to free_sess list
211 * to receive a new request
212 */
Willy Tarreau2b718102021-04-21 07:32:39 +0200213 LIST_INSERT(&ds->dss->free_sess, &ds->list);
Emeric Brunfd647d52021-02-12 20:03:38 +0100214 }
215 else {
216 /* there is no more pipelined requests
217 * into this session, so we move it
218 * to idle_sess list */
Willy Tarreau2b718102021-04-21 07:32:39 +0200219 LIST_INSERT(&ds->dss->idle_sess, &ds->list);
Emeric Brunfd647d52021-02-12 20:03:38 +0100220
221 /* update the counter of idle sessions */
222 ds->dss->idle_conns++;
223
224 /* Note: this is useless there to update
225 * the max_active_conns since we increase
226 * the idle count */
227 }
228 }
229 else {
230 /* there is no more appctx for this session
231 * it means it is ready to die
232 */
233 dns_session_free(ds);
234 }
235
236
237 }
238
239 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
240 }
Emeric Brund26a6232021-01-04 13:32:20 +0100241
242 return ret;
243}
244
245static void dns_resolve_recv(struct dgram_conn *dgram)
246{
247 struct dns_nameserver *ns;
248 int fd;
249
250 fd = dgram->t.sock.fd;
251
252 /* check if ready for reading */
253 if (!fd_recv_ready(fd))
254 return;
255
256 /* no need to go further if we can't retrieve the nameserver */
257 if ((ns = dgram->owner) == NULL) {
Willy Tarreauf5090652021-04-06 17:23:40 +0200258 _HA_ATOMIC_AND(&fdtab[fd].state, ~(FD_POLL_HUP|FD_POLL_ERR));
Emeric Brund26a6232021-01-04 13:32:20 +0100259 fd_stop_recv(fd);
260 return;
261 }
262
263 ns->process_responses(ns);
264}
265
266/* Called when a dns network socket is ready to send data */
267static void dns_resolve_send(struct dgram_conn *dgram)
268{
269 int fd;
270 struct dns_nameserver *ns;
271 struct ring *ring;
272 struct buffer *buf;
273 uint64_t msg_len;
274 size_t len, cnt, ofs;
275
276 fd = dgram->t.sock.fd;
277
278 /* check if ready for sending */
279 if (!fd_send_ready(fd))
280 return;
281
282 /* no need to go further if we can't retrieve the nameserver */
283 if ((ns = dgram->owner) == NULL) {
Willy Tarreauf5090652021-04-06 17:23:40 +0200284 _HA_ATOMIC_AND(&fdtab[fd].state, ~(FD_POLL_HUP|FD_POLL_ERR));
Emeric Brund26a6232021-01-04 13:32:20 +0100285 fd_stop_send(fd);
286 return;
287 }
288
289 ring = ns->dgram->ring_req;
290 buf = &ring->buf;
291
292 HA_RWLOCK_RDLOCK(DNS_LOCK, &ring->lock);
293 ofs = ns->dgram->ofs_req;
294
295 /* explanation for the initialization below: it would be better to do
296 * this in the parsing function but this would occasionally result in
297 * dropped events because we'd take a reference on the oldest message
298 * and keep it while being scheduled. Thus instead let's take it the
299 * first time we enter here so that we have a chance to pass many
300 * existing messages before grabbing a reference to a location. This
301 * value cannot be produced after initialization.
302 */
303 if (unlikely(ofs == ~0)) {
304 ofs = 0;
Willy Tarreau4781b152021-04-06 13:53:36 +0200305 HA_ATOMIC_INC(b_peek(buf, ofs));
Emeric Brund26a6232021-01-04 13:32:20 +0100306 ofs += ring->ofs;
307 }
308
309 /* we were already there, adjust the offset to be relative to
310 * the buffer's head and remove us from the counter.
311 */
312 ofs -= ring->ofs;
313 BUG_ON(ofs >= buf->size);
Willy Tarreau4781b152021-04-06 13:53:36 +0200314 HA_ATOMIC_DEC(b_peek(buf, ofs));
Emeric Brund26a6232021-01-04 13:32:20 +0100315
316 while (ofs + 1 < b_data(buf)) {
317 int ret;
318
319 cnt = 1;
320 len = b_peek_varint(buf, ofs + cnt, &msg_len);
321 if (!len)
322 break;
323 cnt += len;
324 BUG_ON(msg_len + ofs + cnt + 1 > b_data(buf));
325 if (unlikely(msg_len > DNS_TCP_MSG_MAX_SIZE)) {
326 /* too large a message to ever fit, let's skip it */
327 ofs += cnt + msg_len;
328 continue;
329 }
330
331 len = b_getblk(buf, dns_msg_trash, msg_len, ofs + cnt);
332
333 ret = send(fd, dns_msg_trash, len, 0);
334 if (ret < 0) {
Willy Tarreauacef5e22022-04-25 20:32:15 +0200335 if (errno == EAGAIN || errno == EWOULDBLOCK) {
Emeric Brund26a6232021-01-04 13:32:20 +0100336 fd_cant_send(fd);
337 goto out;
338 }
339 ns->counters->snd_error++;
340 fd_delete(fd);
Emeric Brund26a6232021-01-04 13:32:20 +0100341 fd = dgram->t.sock.fd = -1;
342 goto out;
343 }
344 ns->counters->sent++;
345
346 ofs += cnt + len;
347 }
348
349 /* we don't want/need to be waked up any more for sending
350 * because all ring content is sent */
351 fd_stop_send(fd);
352
353out:
354
Willy Tarreau4781b152021-04-06 13:53:36 +0200355 HA_ATOMIC_INC(b_peek(buf, ofs));
Emeric Brund26a6232021-01-04 13:32:20 +0100356 ofs += ring->ofs;
357 ns->dgram->ofs_req = ofs;
358 HA_RWLOCK_RDUNLOCK(DNS_LOCK, &ring->lock);
359
360}
361
Emeric Brunc9437992021-02-12 19:42:55 +0100362/* proto_udp callback functions for a DNS resolution */
363struct dgram_data_cb dns_dgram_cb = {
364 .recv = dns_resolve_recv,
365 .send = dns_resolve_send,
366};
Baptiste Assmann325137d2015-04-13 23:40:55 +0200367
Emeric Brunc9437992021-02-12 19:42:55 +0100368int dns_dgram_init(struct dns_nameserver *ns, struct sockaddr_storage *sk)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200369{
Emeric Brunc9437992021-02-12 19:42:55 +0100370 struct dns_dgram_server *dgram;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200371
Emeric Brunc9437992021-02-12 19:42:55 +0100372 if ((dgram = calloc(1, sizeof(*dgram))) == NULL)
Christopher Faulet67957bd2017-09-27 11:00:59 +0200373 return -1;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200374
Emeric Brunc9437992021-02-12 19:42:55 +0100375 /* Leave dgram partially initialized, no FD attached for
376 * now. */
377 dgram->conn.owner = ns;
378 dgram->conn.data = &dns_dgram_cb;
379 dgram->conn.t.sock.fd = -1;
380 dgram->conn.addr.to = *sk;
381 ns->dgram = dgram;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200382
Emeric Brunc9437992021-02-12 19:42:55 +0100383 dgram->ofs_req = ~0; /* init ring offset */
384 dgram->ring_req = ring_new(2*DNS_TCP_MSG_RING_MAX_SIZE);
385 if (!dgram->ring_req) {
386 ha_alert("memory allocation error initializing the ring for nameserver.\n");
387 goto out;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200388 }
389
Emeric Brunc9437992021-02-12 19:42:55 +0100390 /* attach the task as reader */
391 if (!ring_attach(dgram->ring_req)) {
392 /* mark server attached to the ring */
393 ha_alert("nameserver sets too many watchers > 255 on ring. This is a bug and should not happen.\n");
394 goto out;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200395 }
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200396 return 0;
Emeric Brunc9437992021-02-12 19:42:55 +0100397out:
398 if (dgram->ring_req)
399 ring_free(dgram->ring_req);
Christopher Fauletd6c6b5f2020-09-08 10:27:24 +0200400
Emeric Brunc9437992021-02-12 19:42:55 +0100401 free(dgram);
Olivier Houchard2ec2db92018-01-08 16:28:57 +0100402
Emeric Brunfd647d52021-02-12 20:03:38 +0100403 return -1;
404}
405
406/*
407 * IO Handler to handle message push to dns tcp server
Willy Tarreau0d626a52022-05-04 20:41:19 +0200408 * It takes its context from appctx->svcctx.
Emeric Brunfd647d52021-02-12 20:03:38 +0100409 */
410static void dns_session_io_handler(struct appctx *appctx)
411{
Christopher Faulet908628c2022-03-25 16:43:49 +0100412 struct conn_stream *cs = appctx->owner;
Willy Tarreau0d626a52022-05-04 20:41:19 +0200413 struct dns_session *ds = appctx->svcctx;
Emeric Brunfd647d52021-02-12 20:03:38 +0100414 struct ring *ring = &ds->ring;
415 struct buffer *buf = &ring->buf;
416 uint64_t msg_len;
417 int available_room;
418 size_t len, cnt, ofs;
419 int ret = 0;
420
421 /* if stopping was requested, close immediately */
422 if (unlikely(stopping))
423 goto close;
424
425 /* we want to be sure to not miss that we have been awaked for a shutdown */
426 __ha_barrier_load();
427
428 /* that means the connection was requested to shutdown
429 * for instance idle expire */
430 if (ds->shutdown)
431 goto close;
432
433 /* an error was detected */
Christopher Faulet908628c2022-03-25 16:43:49 +0100434 if (unlikely(cs_ic(cs)->flags & (CF_WRITE_ERROR|CF_SHUTW)))
Emeric Brunfd647d52021-02-12 20:03:38 +0100435 goto close;
436
437 /* con closed by server side, we will skip data write and drain data from channel */
Christopher Faulet908628c2022-03-25 16:43:49 +0100438 if ((cs_oc(cs)->flags & CF_SHUTW)) {
Emeric Brunfd647d52021-02-12 20:03:38 +0100439 goto read;
440 }
441
442 /* if the connection is not established, inform the stream that we want
443 * to be notified whenever the connection completes.
444 */
Christopher Faulet62e75742022-03-31 09:16:34 +0200445 if (cs_opposite(cs)->state < CS_ST_EST) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +0200446 cs_cant_get(cs);
447 cs_rx_conn_blk(cs);
448 cs_rx_endp_more(cs);
Emeric Brunfd647d52021-02-12 20:03:38 +0100449 return;
450 }
451
452
453 ofs = ds->ofs;
454
455 HA_RWLOCK_WRLOCK(DNS_LOCK, &ring->lock);
456 LIST_DEL_INIT(&appctx->wait_entry);
457 HA_RWLOCK_WRUNLOCK(DNS_LOCK, &ring->lock);
458
459 HA_RWLOCK_RDLOCK(DNS_LOCK, &ring->lock);
460
461 /* explanation for the initialization below: it would be better to do
462 * this in the parsing function but this would occasionally result in
463 * dropped events because we'd take a reference on the oldest message
464 * and keep it while being scheduled. Thus instead let's take it the
465 * first time we enter here so that we have a chance to pass many
466 * existing messages before grabbing a reference to a location. This
467 * value cannot be produced after initialization.
468 */
469 if (unlikely(ofs == ~0)) {
470 ofs = 0;
471
Willy Tarreau4781b152021-04-06 13:53:36 +0200472 HA_ATOMIC_INC(b_peek(buf, ofs));
Emeric Brunfd647d52021-02-12 20:03:38 +0100473 ofs += ring->ofs;
474 }
475
476 /* in this loop, ofs always points to the counter byte that precedes
477 * the message so that we can take our reference there if we have to
478 * stop before the end (ret=0).
479 */
Christopher Faulet62e75742022-03-31 09:16:34 +0200480 if (cs_opposite(cs)->state == CS_ST_EST) {
Emeric Brunfd647d52021-02-12 20:03:38 +0100481 /* we were already there, adjust the offset to be relative to
482 * the buffer's head and remove us from the counter.
483 */
484 ofs -= ring->ofs;
485 BUG_ON(ofs >= buf->size);
Willy Tarreau4781b152021-04-06 13:53:36 +0200486 HA_ATOMIC_DEC(b_peek(buf, ofs));
Emeric Brunfd647d52021-02-12 20:03:38 +0100487
488 ret = 1;
489 while (ofs + 1 < b_data(buf)) {
490 struct dns_query *query;
491 uint16_t original_qid;
492 uint16_t new_qid;
493
494 cnt = 1;
495 len = b_peek_varint(buf, ofs + cnt, &msg_len);
496 if (!len)
497 break;
498 cnt += len;
499 BUG_ON(msg_len + ofs + cnt + 1 > b_data(buf));
500
501 /* retrieve available room on output channel */
Christopher Faulet908628c2022-03-25 16:43:49 +0100502 available_room = channel_recv_max(cs_ic(cs));
Emeric Brunfd647d52021-02-12 20:03:38 +0100503
504 /* tx_msg_offset null means we are at the start of a new message */
505 if (!ds->tx_msg_offset) {
506 uint16_t slen;
507
508 /* check if there is enough room to put message len and query id */
509 if (available_room < sizeof(slen) + sizeof(new_qid)) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +0200510 cs_rx_room_blk(cs);
Emeric Brunfd647d52021-02-12 20:03:38 +0100511 ret = 0;
512 break;
513 }
514
515 /* put msg len into then channel */
516 slen = (uint16_t)msg_len;
517 slen = htons(slen);
Christopher Faulet908628c2022-03-25 16:43:49 +0100518 ci_putblk(cs_ic(cs), (char *)&slen, sizeof(slen));
Emeric Brunfd647d52021-02-12 20:03:38 +0100519 available_room -= sizeof(slen);
520
521 /* backup original query id */
522 len = b_getblk(buf, (char *)&original_qid, sizeof(original_qid), ofs + cnt);
Emeric Brun538bb042021-02-15 13:58:06 +0100523 if (!len) {
524 /* should never happen since messages are atomically
525 * written into ring
526 */
527 ret = 0;
528 break;
529 }
Emeric Brunfd647d52021-02-12 20:03:38 +0100530
531 /* generates new query id */
532 new_qid = ++ds->query_counter;
533 new_qid = htons(new_qid);
534
535 /* put new query id into the channel */
Christopher Faulet908628c2022-03-25 16:43:49 +0100536 ci_putblk(cs_ic(cs), (char *)&new_qid, sizeof(new_qid));
Emeric Brunfd647d52021-02-12 20:03:38 +0100537 available_room -= sizeof(new_qid);
538
539 /* keep query id mapping */
540
541 query = pool_alloc(dns_query_pool);
542 if (query) {
543 query->qid.key = new_qid;
544 query->original_qid = original_qid;
545 query->expire = tick_add(now_ms, 5000);
546 LIST_INIT(&query->list);
547 if (LIST_ISEMPTY(&ds->queries)) {
548 /* enable task to handle expire */
549 ds->task_exp->expire = query->expire;
550 /* ensure this will be executed by the same
551 * thread than ds_session_release
552 * to ensure session_release is free
553 * to destroy the task */
554 task_queue(ds->task_exp);
555 }
Willy Tarreau2b718102021-04-21 07:32:39 +0200556 LIST_APPEND(&ds->queries, &query->list);
Emeric Brunfd647d52021-02-12 20:03:38 +0100557 eb32_insert(&ds->query_ids, &query->qid);
558 ds->onfly_queries++;
559 }
560
561 /* update the tx_offset to handle output in 16k streams */
562 ds->tx_msg_offset = sizeof(original_qid);
563
564 }
565
566 /* check if it remains available room on output chan */
567 if (unlikely(!available_room)) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +0200568 cs_rx_room_blk(cs);
Emeric Brunfd647d52021-02-12 20:03:38 +0100569 ret = 0;
570 break;
571 }
572
573 chunk_reset(&trash);
574 if ((msg_len - ds->tx_msg_offset) > available_room) {
575 /* remaining msg data is too large to be written in output channel at one time */
576
577 len = b_getblk(buf, trash.area, available_room, ofs + cnt + ds->tx_msg_offset);
578
579 /* update offset to complete mesg forwarding later */
580 ds->tx_msg_offset += len;
581 }
582 else {
583 /* remaining msg data can be written in output channel at one time */
584 len = b_getblk(buf, trash.area, msg_len - ds->tx_msg_offset, ofs + cnt + ds->tx_msg_offset);
585
586 /* reset tx_msg_offset to mark forward fully processed */
587 ds->tx_msg_offset = 0;
588 }
589 trash.data += len;
590
Christopher Faulet908628c2022-03-25 16:43:49 +0100591 if (ci_putchk(cs_ic(cs), &trash) == -1) {
Emeric Brun743afee2021-02-15 14:12:06 +0100592 /* should never happen since we
593 * check available_room is large
Ilya Shipitsin0de36ad2021-02-20 00:23:36 +0500594 * enough here.
Emeric Brun743afee2021-02-15 14:12:06 +0100595 */
Christopher Fauleta0bdec32022-04-04 07:51:21 +0200596 cs_rx_room_blk(cs);
Emeric Brun743afee2021-02-15 14:12:06 +0100597 ret = 0;
598 break;
599 }
Emeric Brunfd647d52021-02-12 20:03:38 +0100600
601 if (ds->tx_msg_offset) {
602 /* msg was not fully processed, we must be awake to drain pending data */
603
Christopher Fauleta0bdec32022-04-04 07:51:21 +0200604 cs_rx_room_blk(cs);
Emeric Brunfd647d52021-02-12 20:03:38 +0100605 ret = 0;
606 break;
607 }
608 /* switch to next message */
609 ofs += cnt + msg_len;
610 }
611
Willy Tarreau4781b152021-04-06 13:53:36 +0200612 HA_ATOMIC_INC(b_peek(buf, ofs));
Emeric Brunfd647d52021-02-12 20:03:38 +0100613 ofs += ring->ofs;
614 ds->ofs = ofs;
615 }
616 HA_RWLOCK_RDUNLOCK(DNS_LOCK, &ring->lock);
617
618 if (ret) {
619 /* let's be woken up once new request to write arrived */
620 HA_RWLOCK_WRLOCK(DNS_LOCK, &ring->lock);
Willy Tarreau62e467c2021-10-20 11:02:13 +0200621 BUG_ON(LIST_INLIST(&appctx->wait_entry));
Willy Tarreau2b718102021-04-21 07:32:39 +0200622 LIST_APPEND(&ring->waiters, &appctx->wait_entry);
Emeric Brunfd647d52021-02-12 20:03:38 +0100623 HA_RWLOCK_WRUNLOCK(DNS_LOCK, &ring->lock);
Christopher Fauleta0bdec32022-04-04 07:51:21 +0200624 cs_rx_endp_done(cs);
Emeric Brunfd647d52021-02-12 20:03:38 +0100625 }
626
627read:
628
Ilya Shipitsin0de36ad2021-02-20 00:23:36 +0500629 /* if session is not a waiter it means there is no committed
Emeric Brunfd647d52021-02-12 20:03:38 +0100630 * message into rx_buf and we are free to use it
631 * Note: we need a load barrier here to not miss the
632 * delete from the list
633 */
Emeric Brun70455902021-10-20 10:49:53 +0200634
Willy Tarreaudde1b442021-10-21 14:33:38 +0200635 __ha_barrier_load();
636 if (!LIST_INLIST_ATOMIC(&ds->waiter)) {
Emeric Brunfd647d52021-02-12 20:03:38 +0100637 while (1) {
638 uint16_t query_id;
639 struct eb32_node *eb;
640 struct dns_query *query;
641
642 if (!ds->rx_msg.len) {
643 /* next message len is not fully available into the channel */
Christopher Faulet908628c2022-03-25 16:43:49 +0100644 if (co_data(cs_oc(cs)) < 2)
Emeric Brunfd647d52021-02-12 20:03:38 +0100645 break;
646
647 /* retrieve message len */
Christopher Faulet908628c2022-03-25 16:43:49 +0100648 co_getblk(cs_oc(cs), (char *)&msg_len, 2, 0);
Emeric Brunfd647d52021-02-12 20:03:38 +0100649
650 /* mark as consumed */
Christopher Faulet908628c2022-03-25 16:43:49 +0100651 co_skip(cs_oc(cs), 2);
Emeric Brunfd647d52021-02-12 20:03:38 +0100652
653 /* store message len */
654 ds->rx_msg.len = ntohs(msg_len);
655 }
656
Christopher Faulet908628c2022-03-25 16:43:49 +0100657 if (!co_data(cs_oc(cs))) {
Emeric Brunfd647d52021-02-12 20:03:38 +0100658 /* we need more data but nothing is available */
659 break;
660 }
661
Christopher Faulet908628c2022-03-25 16:43:49 +0100662 if (co_data(cs_oc(cs)) + ds->rx_msg.offset < ds->rx_msg.len) {
Emeric Brunfd647d52021-02-12 20:03:38 +0100663 /* message only partially available */
664
665 /* read available data */
Christopher Faulet908628c2022-03-25 16:43:49 +0100666 co_getblk(cs_oc(cs), ds->rx_msg.area + ds->rx_msg.offset, co_data(cs_oc(cs)), 0);
Emeric Brunfd647d52021-02-12 20:03:38 +0100667
668 /* update message offset */
Christopher Faulet908628c2022-03-25 16:43:49 +0100669 ds->rx_msg.offset += co_data(cs_oc(cs));
Emeric Brunfd647d52021-02-12 20:03:38 +0100670
671 /* consume all pending data from the channel */
Christopher Faulet908628c2022-03-25 16:43:49 +0100672 co_skip(cs_oc(cs), co_data(cs_oc(cs)));
Emeric Brunfd647d52021-02-12 20:03:38 +0100673
674 /* we need to wait for more data */
675 break;
676 }
677
Ilya Shipitsin0de36ad2021-02-20 00:23:36 +0500678 /* enough data is available into the channel to read the message until the end */
Emeric Brunfd647d52021-02-12 20:03:38 +0100679
680 /* read from the channel until the end of the message */
Christopher Faulet908628c2022-03-25 16:43:49 +0100681 co_getblk(cs_oc(cs), ds->rx_msg.area + ds->rx_msg.offset, ds->rx_msg.len - ds->rx_msg.offset, 0);
Emeric Brunfd647d52021-02-12 20:03:38 +0100682
683 /* consume all data until the end of the message from the channel */
Christopher Faulet908628c2022-03-25 16:43:49 +0100684 co_skip(cs_oc(cs), ds->rx_msg.len - ds->rx_msg.offset);
Emeric Brunfd647d52021-02-12 20:03:38 +0100685
686 /* reset reader offset to 0 for next message reand */
687 ds->rx_msg.offset = 0;
688
689 /* try remap query id to original */
690 memcpy(&query_id, ds->rx_msg.area, sizeof(query_id));
691 eb = eb32_lookup(&ds->query_ids, query_id);
692 if (!eb) {
693 /* query id not found means we have an unknown corresponding
694 * request, perhaps server's bug or or the query reached
695 * timeout
696 */
697 ds->rx_msg.len = 0;
698 continue;
699 }
700
701 /* re-map the original query id set by the requester */
702 query = eb32_entry(eb, struct dns_query, qid);
703 memcpy(ds->rx_msg.area, &query->original_qid, sizeof(query->original_qid));
704
705 /* remove query ids mapping from pending queries list/tree */
706 eb32_delete(&query->qid);
Willy Tarreau2b718102021-04-21 07:32:39 +0200707 LIST_DELETE(&query->list);
Emeric Brunfd647d52021-02-12 20:03:38 +0100708 pool_free(dns_query_pool, query);
709 ds->onfly_queries--;
710
Emeric Brunfd647d52021-02-12 20:03:38 +0100711 /* the dns_session is also added in queue of the
712 * wait_sess list where the task processing
713 * response will pop available responses
714 */
Willy Tarreaudde1b442021-10-21 14:33:38 +0200715 HA_SPIN_LOCK(DNS_LOCK, &ds->dss->lock);
716
Willy Tarreau62e467c2021-10-20 11:02:13 +0200717 BUG_ON(LIST_INLIST(&ds->waiter));
Willy Tarreau2b718102021-04-21 07:32:39 +0200718 LIST_APPEND(&ds->dss->wait_sess, &ds->waiter);
Emeric Brunfd647d52021-02-12 20:03:38 +0100719
Willy Tarreaudde1b442021-10-21 14:33:38 +0200720 HA_SPIN_UNLOCK(DNS_LOCK, &ds->dss->lock);
721
Emeric Brunfd647d52021-02-12 20:03:38 +0100722 /* awake the task processing the responses */
723 task_wakeup(ds->dss->task_rsp, TASK_WOKEN_INIT);
724
725 break;
726 }
727
Willy Tarreau2b718102021-04-21 07:32:39 +0200728 if (!LIST_INLIST(&ds->waiter)) {
Emeric Brunfd647d52021-02-12 20:03:38 +0100729 /* there is no more pending data to read and the con was closed by the server side */
Christopher Faulet908628c2022-03-25 16:43:49 +0100730 if (!co_data(cs_oc(cs)) && (cs_oc(cs)->flags & CF_SHUTW)) {
Emeric Brunfd647d52021-02-12 20:03:38 +0100731 goto close;
732 }
733 }
734
735 }
736
Emeric Brunfd647d52021-02-12 20:03:38 +0100737 return;
738close:
Christopher Fauletda098e62022-03-31 17:44:45 +0200739 cs_shutw(cs);
740 cs_shutr(cs);
Christopher Faulet908628c2022-03-25 16:43:49 +0100741 cs_ic(cs)->flags |= CF_READ_NULL;
Emeric Brunfd647d52021-02-12 20:03:38 +0100742}
743
744void dns_queries_flush(struct dns_session *ds)
745{
746 struct dns_query *query, *queryb;
747
748 list_for_each_entry_safe(query, queryb, &ds->queries, list) {
749 eb32_delete(&query->qid);
Willy Tarreau2b718102021-04-21 07:32:39 +0200750 LIST_DELETE(&query->list);
Emeric Brunfd647d52021-02-12 20:03:38 +0100751 pool_free(dns_query_pool, query);
752 }
753}
754
755void dns_session_free(struct dns_session *ds)
756{
757 if (ds->rx_msg.area)
758 pool_free(dns_msg_buf, ds->rx_msg.area);
759 if (ds->tx_ring_area)
760 pool_free(dns_msg_buf, ds->tx_ring_area);
761 if (ds->task_exp)
762 task_destroy(ds->task_exp);
763
764 dns_queries_flush(ds);
765
Emeric Brund20dc212021-10-19 15:40:10 +0200766 /* Ensure to remove this session from external lists
767 * Note: we are under the lock of dns_stream_server
768 * which own the heads of those lists.
769 */
770 LIST_DEL_INIT(&ds->waiter);
771 LIST_DEL_INIT(&ds->list);
772
Emeric Brunfd647d52021-02-12 20:03:38 +0100773 ds->dss->cur_conns--;
774 /* Note: this is useless to update
775 * max_active_conns here because
776 * we decrease the value
777 */
Willy Tarreau62e467c2021-10-20 11:02:13 +0200778
779 BUG_ON(!LIST_ISEMPTY(&ds->list));
780 BUG_ON(!LIST_ISEMPTY(&ds->waiter));
781 BUG_ON(!LIST_ISEMPTY(&ds->queries));
782 BUG_ON(!LIST_ISEMPTY(&ds->ring.waiters));
783 BUG_ON(!eb_is_empty(&ds->query_ids));
Emeric Brunfd647d52021-02-12 20:03:38 +0100784 pool_free(dns_session_pool, ds);
785}
786
787static struct appctx *dns_session_create(struct dns_session *ds);
788
789/*
790 * Function to release a DNS tcp session
791 */
792static void dns_session_release(struct appctx *appctx)
793{
Willy Tarreau0d626a52022-05-04 20:41:19 +0200794 struct dns_session *ds = appctx->svcctx;
Willy Tarreaue3e648c2021-02-24 17:38:46 +0100795 struct dns_stream_server *dss __maybe_unused;
Emeric Brunfd647d52021-02-12 20:03:38 +0100796
797 if (!ds)
798 return;
799
Willy Tarreaub56a8782021-10-20 14:38:43 +0200800 /* We do not call ring_appctx_detach here
801 * because we want to keep readers counters
802 * to retry a conn with a different appctx.
803 */
804 HA_RWLOCK_WRLOCK(DNS_LOCK, &ds->ring.lock);
805 LIST_DEL_INIT(&appctx->wait_entry);
806 HA_RWLOCK_WRUNLOCK(DNS_LOCK, &ds->ring.lock);
807
Emeric Brunfd647d52021-02-12 20:03:38 +0100808 dss = ds->dss;
809
810 HA_SPIN_LOCK(DNS_LOCK, &dss->lock);
811 LIST_DEL_INIT(&ds->list);
812
813 if (stopping) {
814 dns_session_free(ds);
815 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
816 return;
817 }
818
819 if (!ds->nb_queries) {
820 /* this is an idle session */
821 /* Note: this is useless to update max_active_sess
822 * here because we decrease idle_conns but
823 * dns_session_free decrease curconns
824 */
825
826 ds->dss->idle_conns--;
827 dns_session_free(ds);
828 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
829 return;
830 }
831
832 if (ds->onfly_queries == ds->nb_queries) {
833 /* the session can be released because
834 * it means that all queries AND
835 * responses are in fly */
836 dns_session_free(ds);
837 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
838 return;
839 }
840
Emeric Brunfd647d52021-02-12 20:03:38 +0100841 /* if there is no pending complete response
842 * message, ensure to reset
843 * message offsets if the session
844 * was closed with an incomplete pending response
845 */
Willy Tarreau2b718102021-04-21 07:32:39 +0200846 if (!LIST_INLIST(&ds->waiter))
Emeric Brunfd647d52021-02-12 20:03:38 +0100847 ds->rx_msg.len = ds->rx_msg.offset = 0;
848
849 /* we flush pending sent queries because we never
850 * have responses
851 */
852 ds->nb_queries -= ds->onfly_queries;
853 dns_queries_flush(ds);
854
855 /* reset offset to be sure to start from message start */
856 ds->tx_msg_offset = 0;
857
858 /* here the ofs and the attached counter
859 * are kept unchanged
860 */
861
862 /* Create a new appctx, We hope we can
863 * create from the release callback! */
864 ds->appctx = dns_session_create(ds);
865 if (!ds->appctx) {
866 dns_session_free(ds);
867 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
868 return;
869 }
870
871 if (ds->nb_queries < DNS_STREAM_MAX_PIPELINED_REQ)
Willy Tarreau2b718102021-04-21 07:32:39 +0200872 LIST_INSERT(&ds->dss->free_sess, &ds->list);
Emeric Brunfd647d52021-02-12 20:03:38 +0100873
874 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
875}
876
877/* DNS tcp session applet */
878static struct applet dns_session_applet = {
879 .obj_type = OBJ_TYPE_APPLET,
880 .name = "<STRMDNS>", /* used for logging */
881 .fct = dns_session_io_handler,
882 .release = dns_session_release,
883};
884
885/*
886 * Function used to create an appctx for a DNS session
Willy Tarreau0d626a52022-05-04 20:41:19 +0200887 * It sets its context into appctx->svcctx.
Emeric Brunfd647d52021-02-12 20:03:38 +0100888 */
889static struct appctx *dns_session_create(struct dns_session *ds)
890{
891 struct appctx *appctx;
892 struct session *sess;
Christopher Faulet13a35e52021-12-20 15:34:16 +0100893 struct conn_stream *cs;
Emeric Brunfd647d52021-02-12 20:03:38 +0100894 struct stream *s;
895 struct applet *applet = &dns_session_applet;
Christopher Fauleta9e8b392022-03-23 11:01:09 +0100896 struct sockaddr_storage *addr = NULL;
Emeric Brunfd647d52021-02-12 20:03:38 +0100897
Christopher Faulet9ec2f4d2022-03-23 15:15:29 +0100898 appctx = appctx_new(applet, NULL);
Christopher Faulet2479e5f2022-01-19 14:50:11 +0100899 if (!appctx)
Christopher Fauleta9e8b392022-03-23 11:01:09 +0100900 goto out_close;
Willy Tarreau0d626a52022-05-04 20:41:19 +0200901 appctx->svcctx = (void *)ds;
Emeric Brunfd647d52021-02-12 20:03:38 +0100902
903 sess = session_new(ds->dss->srv->proxy, NULL, &appctx->obj_type);
904 if (!sess) {
Christopher Faulet13a35e52021-12-20 15:34:16 +0100905 ha_alert("out of memory in dns_session_create().\n");
Emeric Brunfd647d52021-02-12 20:03:38 +0100906 goto out_free_appctx;
907 }
908
Christopher Fauleta9e8b392022-03-23 11:01:09 +0100909 if (!sockaddr_alloc(&addr, &ds->dss->srv->addr, sizeof(ds->dss->srv->addr)))
Christopher Faulet2479e5f2022-01-19 14:50:11 +0100910 goto out_free_sess;
Christopher Fauleta9e8b392022-03-23 11:01:09 +0100911
Christopher Faulet9ec2f4d2022-03-23 15:15:29 +0100912 cs = cs_new_from_applet(appctx->endp, sess, &BUF_NULL);
Christopher Fauleta9e8b392022-03-23 11:01:09 +0100913 if (!cs) {
914 ha_alert("Failed to initialize stream in dns_session_create().\n");
Christopher Fauleta9e8b392022-03-23 11:01:09 +0100915 goto out_free_addr;
Christopher Faulet13a35e52021-12-20 15:34:16 +0100916 }
917
Christopher Fauleta9e8b392022-03-23 11:01:09 +0100918 s = DISGUISE(cs_strm(cs));
Christopher Faulet8da67aa2022-03-29 17:53:09 +0200919 s->csb->dst = addr;
Christopher Faulet8abe7122022-03-30 15:10:18 +0200920 s->csb->flags |= CS_FL_NOLINGER;
Emeric Brunfd647d52021-02-12 20:03:38 +0100921 s->target = &ds->dss->srv->obj_type;
Willy Tarreau03bd3952022-05-02 16:36:47 +0200922 s->flags = SF_ASSIGNED;
Emeric Brunfd647d52021-02-12 20:03:38 +0100923
924 s->do_log = NULL;
925 s->uniq_id = 0;
926
927 s->res.flags |= CF_READ_DONTWAIT;
928 /* for rto and rex to eternity to not expire on idle recv:
929 * We are using a syslog server.
930 */
931 s->res.rto = TICK_ETERNITY;
932 s->res.rex = TICK_ETERNITY;
933 ds->appctx = appctx;
Emeric Brunfd647d52021-02-12 20:03:38 +0100934 return appctx;
935
936 /* Error unrolling */
Christopher Fauleta9e8b392022-03-23 11:01:09 +0100937 out_free_addr:
938 sockaddr_free(&addr);
Emeric Brunfd647d52021-02-12 20:03:38 +0100939 out_free_sess:
940 session_free(sess);
941 out_free_appctx:
942 appctx_free(appctx);
943 out_close:
944 return NULL;
945}
946
947/* Task processing expiration of unresponded queries, this one is supposed
948 * to be stuck on the same thread than the appctx handler
949 */
Willy Tarreau144f84a2021-03-02 16:09:26 +0100950static struct task *dns_process_query_exp(struct task *t, void *context, unsigned int state)
Emeric Brunfd647d52021-02-12 20:03:38 +0100951{
952 struct dns_session *ds = (struct dns_session *)context;
953 struct dns_query *query, *queryb;
954
955 t->expire = TICK_ETERNITY;
956
957 list_for_each_entry_safe(query, queryb, &ds->queries, list) {
958 if (tick_is_expired(query->expire, now_ms)) {
959 eb32_delete(&query->qid);
Willy Tarreau2b718102021-04-21 07:32:39 +0200960 LIST_DELETE(&query->list);
Emeric Brunfd647d52021-02-12 20:03:38 +0100961 pool_free(dns_query_pool, query);
962 ds->onfly_queries--;
963 }
964 else {
965 t->expire = query->expire;
966 break;
967 }
968 }
969
970 return t;
971}
972
973/* Task processing expiration of idle sessions */
Willy Tarreau144f84a2021-03-02 16:09:26 +0100974static struct task *dns_process_idle_exp(struct task *t, void *context, unsigned int state)
Emeric Brunfd647d52021-02-12 20:03:38 +0100975{
976 struct dns_stream_server *dss = (struct dns_stream_server *)context;
977 struct dns_session *ds, *dsb;
978 int target = 0;
979 int cur_active_conns;
980
981 HA_SPIN_LOCK(DNS_LOCK, &dss->lock);
982
983
984 cur_active_conns = dss->cur_conns - dss->idle_conns;
985 if (cur_active_conns > dss->max_active_conns)
986 dss->max_active_conns = cur_active_conns;
987
988 target = (dss->max_active_conns - cur_active_conns) / 2;
989 list_for_each_entry_safe(ds, dsb, &dss->idle_sess, list) {
990 if (!target)
991 break;
992
993 /* remove conn to pending list to ensure it won't be reused */
994 LIST_DEL_INIT(&ds->list);
995
996 /* force session shutdown */
997 ds->shutdown = 1;
998
Ilya Shipitsin0de36ad2021-02-20 00:23:36 +0500999 /* to be sure that the appctx won't miss shutdown */
Emeric Brunfd647d52021-02-12 20:03:38 +01001000 __ha_barrier_store();
1001
1002 /* wake appctx to perform the shutdown */
1003 appctx_wakeup(ds->appctx);
1004 }
1005
1006 /* reset max to current active conns */
1007 dss->max_active_conns = cur_active_conns;
1008
1009 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
1010
1011 t->expire = tick_add(now_ms, 5000);
1012
1013 return t;
1014}
1015
1016struct dns_session *dns_session_new(struct dns_stream_server *dss)
1017{
1018 struct dns_session *ds;
1019
1020 if (dss->maxconn && (dss->maxconn <= dss->cur_conns))
1021 return NULL;
1022
1023 ds = pool_alloc(dns_session_pool);
1024 if (!ds)
1025 return NULL;
1026
1027 ds->ofs = ~0;
1028 ds->dss = dss;
1029 LIST_INIT(&ds->list);
1030 LIST_INIT(&ds->queries);
1031 LIST_INIT(&ds->waiter);
1032 ds->rx_msg.offset = ds->rx_msg.len = 0;
1033 ds->rx_msg.area = NULL;
1034 ds->tx_ring_area = NULL;
1035 ds->task_exp = NULL;
1036 ds->appctx = NULL;
1037 ds->shutdown = 0;
1038 ds->nb_queries = 0;
1039 ds->query_ids = EB_ROOT_UNIQUE;
1040 ds->rx_msg.area = pool_alloc(dns_msg_buf);
1041 if (!ds->rx_msg.area)
1042 goto error;
1043
1044 ds->tx_ring_area = pool_alloc(dns_msg_buf);
1045 if (!ds->tx_ring_area)
1046 goto error;
1047
1048 ring_init(&ds->ring, ds->tx_ring_area, DNS_TCP_MSG_RING_MAX_SIZE);
Christopher Faulet1a1b6742021-03-04 16:53:27 +01001049 /* never fail because it is the first watcher attached to the ring */
1050 DISGUISE(ring_attach(&ds->ring));
Emeric Brunfd647d52021-02-12 20:03:38 +01001051
Willy Tarreaubeeabf52021-10-01 18:23:30 +02001052 if ((ds->task_exp = task_new_here()) == NULL)
Emeric Brunfd647d52021-02-12 20:03:38 +01001053 goto error;
1054
1055 ds->task_exp->process = dns_process_query_exp;
1056 ds->task_exp->context = ds;
1057
1058 ds->appctx = dns_session_create(ds);
1059 if (!ds->appctx)
1060 goto error;
1061
1062 dss->cur_conns++;
1063
1064 return ds;
1065
1066error:
1067 if (ds->task_exp)
1068 task_destroy(ds->task_exp);
1069 if (ds->rx_msg.area)
1070 pool_free(dns_msg_buf, ds->rx_msg.area);
1071 if (ds->tx_ring_area)
1072 pool_free(dns_msg_buf, ds->tx_ring_area);
1073
1074 pool_free(dns_session_pool, ds);
1075
1076 return NULL;
1077}
1078
1079/*
1080 * Task used to consume pending messages from nameserver ring
1081 * and forward them to dns_session ring.
1082 * Note: If no slot found a new dns_session is allocated
1083 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01001084static struct task *dns_process_req(struct task *t, void *context, unsigned int state)
Emeric Brunfd647d52021-02-12 20:03:38 +01001085{
1086 struct dns_nameserver *ns = (struct dns_nameserver *)context;
1087 struct dns_stream_server *dss = ns->stream;
1088 struct ring *ring = dss->ring_req;
1089 struct buffer *buf = &ring->buf;
1090 uint64_t msg_len;
1091 size_t len, cnt, ofs;
1092 struct dns_session *ds, *ads;
1093 HA_SPIN_LOCK(DNS_LOCK, &dss->lock);
1094
1095 ofs = dss->ofs_req;
1096
1097 HA_RWLOCK_RDLOCK(DNS_LOCK, &ring->lock);
1098
1099 /* explanation for the initialization below: it would be better to do
1100 * this in the parsing function but this would occasionally result in
1101 * dropped events because we'd take a reference on the oldest message
1102 * and keep it while being scheduled. Thus instead let's take it the
1103 * first time we enter here so that we have a chance to pass many
1104 * existing messages before grabbing a reference to a location. This
1105 * value cannot be produced after initialization.
1106 */
1107 if (unlikely(ofs == ~0)) {
1108 ofs = 0;
Willy Tarreau4781b152021-04-06 13:53:36 +02001109 HA_ATOMIC_INC(b_peek(buf, ofs));
Emeric Brunfd647d52021-02-12 20:03:38 +01001110 ofs += ring->ofs;
1111 }
1112
1113 /* we were already there, adjust the offset to be relative to
1114 * the buffer's head and remove us from the counter.
1115 */
1116 ofs -= ring->ofs;
1117 BUG_ON(ofs >= buf->size);
Willy Tarreau4781b152021-04-06 13:53:36 +02001118 HA_ATOMIC_DEC(b_peek(buf, ofs));
Emeric Brunfd647d52021-02-12 20:03:38 +01001119
1120 while (ofs + 1 < b_data(buf)) {
1121 struct ist myist;
1122
1123 cnt = 1;
1124 len = b_peek_varint(buf, ofs + cnt, &msg_len);
1125 if (!len)
1126 break;
1127 cnt += len;
1128 BUG_ON(msg_len + ofs + cnt + 1 > b_data(buf));
1129 if (unlikely(msg_len > DNS_TCP_MSG_MAX_SIZE)) {
1130 /* too large a message to ever fit, let's skip it */
1131 ofs += cnt + msg_len;
1132 continue;
1133 }
1134
1135 len = b_getblk(buf, dns_msg_trash, msg_len, ofs + cnt);
1136
Tim Duesterhus92c696e2021-02-28 16:11:36 +01001137 myist = ist2(dns_msg_trash, len);
Emeric Brunfd647d52021-02-12 20:03:38 +01001138
1139 ads = NULL;
Ilya Shipitsin0de36ad2021-02-20 00:23:36 +05001140 /* try to push request into active sess with free slot */
Emeric Brunfd647d52021-02-12 20:03:38 +01001141 if (!LIST_ISEMPTY(&dss->free_sess)) {
1142 ds = LIST_NEXT(&dss->free_sess, struct dns_session *, list);
1143
1144 if (ring_write(&ds->ring, DNS_TCP_MSG_MAX_SIZE, NULL, 0, &myist, 1) > 0) {
1145 ds->nb_queries++;
1146 if (ds->nb_queries >= DNS_STREAM_MAX_PIPELINED_REQ)
1147 LIST_DEL_INIT(&ds->list);
1148 ads = ds;
1149 }
1150 else {
1151 /* it means we were unable to put a request in this slot,
1152 * it may be close to be full so we put it at the end
1153 * of free conn list */
1154 LIST_DEL_INIT(&ds->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02001155 LIST_APPEND(&dss->free_sess, &ds->list);
Emeric Brunfd647d52021-02-12 20:03:38 +01001156 }
1157 }
1158
1159 if (!ads) {
Ilya Shipitsin0de36ad2021-02-20 00:23:36 +05001160 /* try to push request into idle, this one should have enough free space */
Emeric Brunfd647d52021-02-12 20:03:38 +01001161 if (!LIST_ISEMPTY(&dss->idle_sess)) {
1162 ds = LIST_NEXT(&dss->idle_sess, struct dns_session *, list);
1163
1164 /* ring is empty so this ring_write should never fail */
1165 ring_write(&ds->ring, DNS_TCP_MSG_MAX_SIZE, NULL, 0, &myist, 1);
1166 ds->nb_queries++;
1167 LIST_DEL_INIT(&ds->list);
1168
1169 ds->dss->idle_conns--;
1170
1171 /* we may have to update the max_active_conns */
1172 if (ds->dss->max_active_conns < ds->dss->cur_conns - ds->dss->idle_conns)
1173 ds->dss->max_active_conns = ds->dss->cur_conns - ds->dss->idle_conns;
1174
1175 /* since we may unable to find a free list to handle
1176 * this request, this request may be large and fill
1177 * the ring buffer so we prefer to put at the end of free
1178 * list. */
Willy Tarreau2b718102021-04-21 07:32:39 +02001179 LIST_APPEND(&dss->free_sess, &ds->list);
Emeric Brunfd647d52021-02-12 20:03:38 +01001180 ads = ds;
1181 }
1182 }
1183
Ilya Shipitsin0de36ad2021-02-20 00:23:36 +05001184 /* we didn't find a session available with large enough room */
Emeric Brunfd647d52021-02-12 20:03:38 +01001185 if (!ads) {
1186 /* allocate a new session */
1187 ads = dns_session_new(dss);
1188 if (ads) {
1189 /* ring is empty so this ring_write should never fail */
1190 ring_write(&ads->ring, DNS_TCP_MSG_MAX_SIZE, NULL, 0, &myist, 1);
1191 ads->nb_queries++;
Willy Tarreau2b718102021-04-21 07:32:39 +02001192 LIST_INSERT(&dss->free_sess, &ads->list);
Emeric Brunfd647d52021-02-12 20:03:38 +01001193 }
1194 else
1195 ns->counters->snd_error++;
1196 }
1197
1198 if (ads)
1199 ns->counters->sent++;
1200
1201 ofs += cnt + len;
1202 }
1203
Willy Tarreau4781b152021-04-06 13:53:36 +02001204 HA_ATOMIC_INC(b_peek(buf, ofs));
Emeric Brunfd647d52021-02-12 20:03:38 +01001205 ofs += ring->ofs;
1206 dss->ofs_req = ofs;
1207 HA_RWLOCK_RDUNLOCK(DNS_LOCK, &ring->lock);
1208
1209
1210 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
1211 return t;
1212}
1213
1214/*
1215 * Task used to consume response
1216 * Note: upper layer callback is called
1217 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01001218static struct task *dns_process_rsp(struct task *t, void *context, unsigned int state)
Emeric Brunfd647d52021-02-12 20:03:38 +01001219{
1220 struct dns_nameserver *ns = (struct dns_nameserver *)context;
1221
1222 ns->process_responses(ns);
1223
1224 return t;
1225}
1226
1227/* Function used to initialize an TCP nameserver */
1228int dns_stream_init(struct dns_nameserver *ns, struct server *srv)
1229{
1230 struct dns_stream_server *dss = NULL;
1231
1232 dss = calloc(1, sizeof(*dss));
1233 if (!dss) {
1234 ha_alert("memory allocation error initializing dns tcp server '%s'.\n", srv->id);
1235 goto out;
1236 }
1237
1238 dss->srv = srv;
1239 dss->maxconn = srv->maxconn;
1240
1241 dss->ofs_req = ~0; /* init ring offset */
1242 dss->ring_req = ring_new(2*DNS_TCP_MSG_RING_MAX_SIZE);
1243 if (!dss->ring_req) {
1244 ha_alert("memory allocation error initializing the ring for dns tcp server '%s'.\n", srv->id);
1245 goto out;
1246 }
1247 /* Create the task associated to the resolver target handling conns */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02001248 if ((dss->task_req = task_new_anywhere()) == NULL) {
Emeric Brunfd647d52021-02-12 20:03:38 +01001249 ha_alert("memory allocation error initializing the ring for dns tcp server '%s'.\n", srv->id);
1250 goto out;
1251 }
1252
1253 /* Update task's parameters */
1254 dss->task_req->process = dns_process_req;
1255 dss->task_req->context = ns;
1256
1257 /* attach the task as reader */
1258 if (!ring_attach(dss->ring_req)) {
1259 /* mark server attached to the ring */
1260 ha_alert("server '%s': too many watchers for ring. this should never happen.\n", srv->id);
1261 goto out;
1262 }
1263
1264 /* Create the task associated to the resolver target handling conns */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02001265 if ((dss->task_rsp = task_new_anywhere()) == NULL) {
Emeric Brunfd647d52021-02-12 20:03:38 +01001266 ha_alert("memory allocation error initializing the ring for dns tcp server '%s'.\n", srv->id);
1267 goto out;
1268 }
1269
1270 /* Update task's parameters */
1271 dss->task_rsp->process = dns_process_rsp;
1272 dss->task_rsp->context = ns;
1273
1274 /* Create the task associated to the resolver target handling conns */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02001275 if ((dss->task_idle = task_new_anywhere()) == NULL) {
Emeric Brunfd647d52021-02-12 20:03:38 +01001276 ha_alert("memory allocation error initializing the ring for dns tcp server '%s'.\n", srv->id);
1277 goto out;
1278 }
1279
1280 /* Update task's parameters */
1281 dss->task_idle->process = dns_process_idle_exp;
1282 dss->task_idle->context = dss;
1283 dss->task_idle->expire = tick_add(now_ms, 5000);
1284
Ilya Shipitsin0de36ad2021-02-20 00:23:36 +05001285 /* let start the task to free idle conns immediately */
Emeric Brunfd647d52021-02-12 20:03:38 +01001286 task_queue(dss->task_idle);
1287
1288 LIST_INIT(&dss->free_sess);
1289 LIST_INIT(&dss->idle_sess);
1290 LIST_INIT(&dss->wait_sess);
1291 HA_SPIN_INIT(&dss->lock);
1292 ns->stream = dss;
1293 return 0;
1294out:
1295 if (dss && dss->task_rsp)
1296 task_destroy(dss->task_rsp);
1297 if (dss && dss->task_req)
1298 task_destroy(dss->task_req);
1299 if (dss && dss->ring_req)
1300 ring_free(dss->ring_req);
1301
1302 free(dss);
Emeric Brunc9437992021-02-12 19:42:55 +01001303 return -1;
Christopher Faulet67957bd2017-09-27 11:00:59 +02001304}
1305
Emeric Brunc9437992021-02-12 19:42:55 +01001306int init_dns_buffers()
Baptiste Assmann325137d2015-04-13 23:40:55 +02001307{
Emeric Brunc9437992021-02-12 19:42:55 +01001308 dns_msg_trash = malloc(DNS_TCP_MSG_MAX_SIZE);
1309 if (!dns_msg_trash)
1310 return 0;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001311
Emeric Brunc9437992021-02-12 19:42:55 +01001312 return 1;
1313}
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001314
Emeric Brunc9437992021-02-12 19:42:55 +01001315void deinit_dns_buffers()
1316{
Willy Tarreau61cfdf42021-02-20 10:46:51 +01001317 ha_free(&dns_msg_trash);
Emeric Brunc9437992021-02-12 19:42:55 +01001318}
Emeric Brund26a6232021-01-04 13:32:20 +01001319
1320REGISTER_PER_THREAD_ALLOC(init_dns_buffers);
1321REGISTER_PER_THREAD_FREE(deinit_dns_buffers);