blob: f16d681861e753b29ca546d54586321be1b0dde7 [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>
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>
Willy Tarreau5edca2f2022-05-27 09:25:10 +020034#include <haproxy/sc_strm.h>
Willy Tarreaucb086c62022-05-27 09:47:12 +020035#include <haproxy/stconn.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;
Willy Tarreau27a32452022-07-07 08:29:00 +020077 fd_insert(fd, dgram, dgram_fd_handler, tgid, tg->threads_enabled);
Christopher Faulet1e711be2021-03-04 16:58:35 +010078 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;
Emeric Brun314e6ec2022-05-10 11:35:48 +020093 int fd;
Emeric Brund26a6232021-01-04 13:32:20 +010094
Emeric Brun314e6ec2022-05-10 11:35:48 +020095 HA_SPIN_LOCK(DNS_LOCK, &dgram->lock);
96 fd = dgram->t.sock.fd;
97 if (fd == -1) {
98 if (dns_connect_nameserver(ns) == -1) {
99 HA_SPIN_UNLOCK(DNS_LOCK, &dgram->lock);
Emeric Brund26a6232021-01-04 13:32:20 +0100100 return -1;
Emeric Brun314e6ec2022-05-10 11:35:48 +0200101 }
Emeric Brund26a6232021-01-04 13:32:20 +0100102 fd = dgram->t.sock.fd;
103 }
104
105 ret = send(fd, buf, len, 0);
106 if (ret < 0) {
Willy Tarreauacef5e22022-04-25 20:32:15 +0200107 if (errno == EAGAIN || errno == EWOULDBLOCK) {
Emeric Brund26a6232021-01-04 13:32:20 +0100108 struct ist myist;
109
Tim Duesterhus92c696e2021-02-28 16:11:36 +0100110 myist = ist2(buf, len);
Emeric Brund26a6232021-01-04 13:32:20 +0100111 ret = ring_write(ns->dgram->ring_req, DNS_TCP_MSG_MAX_SIZE, NULL, 0, &myist, 1);
112 if (!ret) {
113 ns->counters->snd_error++;
Emeric Brun314e6ec2022-05-10 11:35:48 +0200114 HA_SPIN_UNLOCK(DNS_LOCK, &dgram->lock);
Emeric Brund26a6232021-01-04 13:32:20 +0100115 return -1;
116 }
117 fd_cant_send(fd);
Emeric Brun314e6ec2022-05-10 11:35:48 +0200118 HA_SPIN_UNLOCK(DNS_LOCK, &dgram->lock);
Emeric Brund26a6232021-01-04 13:32:20 +0100119 return ret;
120 }
121 ns->counters->snd_error++;
122 fd_delete(fd);
Emeric Brund26a6232021-01-04 13:32:20 +0100123 dgram->t.sock.fd = -1;
Emeric Brun314e6ec2022-05-10 11:35:48 +0200124 HA_SPIN_UNLOCK(DNS_LOCK, &dgram->lock);
Emeric Brund26a6232021-01-04 13:32:20 +0100125 return -1;
126 }
127 ns->counters->sent++;
Emeric Brun314e6ec2022-05-10 11:35:48 +0200128 HA_SPIN_UNLOCK(DNS_LOCK, &dgram->lock);
Emeric Brund26a6232021-01-04 13:32:20 +0100129 }
Emeric Brunfd647d52021-02-12 20:03:38 +0100130 else if (ns->stream) {
131 struct ist myist;
132
Tim Duesterhus92c696e2021-02-28 16:11:36 +0100133 myist = ist2(buf, len);
Emeric Brunfd647d52021-02-12 20:03:38 +0100134 ret = ring_write(ns->stream->ring_req, DNS_TCP_MSG_MAX_SIZE, NULL, 0, &myist, 1);
135 if (!ret) {
136 ns->counters->snd_error++;
137 return -1;
138 }
139 task_wakeup(ns->stream->task_req, TASK_WOKEN_MSG);
140 return ret;
141 }
Emeric Brund26a6232021-01-04 13:32:20 +0100142
143 return ret;
144}
145
Emeric Brunfd647d52021-02-12 20:03:38 +0100146void dns_session_free(struct dns_session *);
147
Emeric Brund26a6232021-01-04 13:32:20 +0100148/* Receives a dns message
149 * Returns message length
150 * 0 is returned if no more message available
151 * -1 in error case
152 */
153ssize_t dns_recv_nameserver(struct dns_nameserver *ns, void *data, size_t size)
154{
155 ssize_t ret = -1;
156
157 if (ns->dgram) {
158 struct dgram_conn *dgram = &ns->dgram->conn;
Emeric Brun314e6ec2022-05-10 11:35:48 +0200159 int fd;
Emeric Brund26a6232021-01-04 13:32:20 +0100160
Emeric Brun314e6ec2022-05-10 11:35:48 +0200161 HA_SPIN_LOCK(DNS_LOCK, &dgram->lock);
162 fd = dgram->t.sock.fd;
163 if (fd == -1) {
164 HA_SPIN_UNLOCK(DNS_LOCK, &dgram->lock);
Emeric Brund26a6232021-01-04 13:32:20 +0100165 return -1;
Emeric Brun314e6ec2022-05-10 11:35:48 +0200166 }
Emeric Brund26a6232021-01-04 13:32:20 +0100167
168 if ((ret = recv(fd, data, size, 0)) < 0) {
Willy Tarreauacef5e22022-04-25 20:32:15 +0200169 if (errno == EAGAIN || errno == EWOULDBLOCK) {
Emeric Brund26a6232021-01-04 13:32:20 +0100170 fd_cant_recv(fd);
Emeric Brun314e6ec2022-05-10 11:35:48 +0200171 HA_SPIN_UNLOCK(DNS_LOCK, &dgram->lock);
Emeric Brund26a6232021-01-04 13:32:20 +0100172 return 0;
173 }
174 fd_delete(fd);
Emeric Brund26a6232021-01-04 13:32:20 +0100175 dgram->t.sock.fd = -1;
Emeric Brun314e6ec2022-05-10 11:35:48 +0200176 HA_SPIN_UNLOCK(DNS_LOCK, &dgram->lock);
Emeric Brund26a6232021-01-04 13:32:20 +0100177 return -1;
178 }
Emeric Brun314e6ec2022-05-10 11:35:48 +0200179 HA_SPIN_UNLOCK(DNS_LOCK, &dgram->lock);
Emeric Brund26a6232021-01-04 13:32:20 +0100180 }
Emeric Brunfd647d52021-02-12 20:03:38 +0100181 else if (ns->stream) {
182 struct dns_stream_server *dss = ns->stream;
183 struct dns_session *ds;
184
185 HA_SPIN_LOCK(DNS_LOCK, &dss->lock);
186
187 if (!LIST_ISEMPTY(&dss->wait_sess)) {
188 ds = LIST_NEXT(&dss->wait_sess, struct dns_session *, waiter);
Emeric Brunfd647d52021-02-12 20:03:38 +0100189 ret = ds->rx_msg.len < size ? ds->rx_msg.len : size;
190 memcpy(data, ds->rx_msg.area, ret);
191
192 ds->rx_msg.len = 0;
193
Willy Tarreaudde1b442021-10-21 14:33:38 +0200194 /* This barrier is here to ensure that all data is
195 * stored if the appctx detect the elem is out of the
196 * list.
197 */
198 __ha_barrier_store();
199
Emeric Brunfd647d52021-02-12 20:03:38 +0100200 LIST_DEL_INIT(&ds->waiter);
201
202 if (ds->appctx) {
Willy Tarreaudde1b442021-10-21 14:33:38 +0200203 /* This second barrier is here to ensure that
204 * the waked up appctx won't miss that the elem
205 * is removed from the list.
206 */
207 __ha_barrier_store();
208
Ilya Shipitsin0de36ad2021-02-20 00:23:36 +0500209 /* awake appctx because it may have other
Emeric Brunfd647d52021-02-12 20:03:38 +0100210 * message to receive
211 */
212 appctx_wakeup(ds->appctx);
213
214 /* dns_session could already be into free_sess list
215 * so we firstly remove it */
216 LIST_DEL_INIT(&ds->list);
217
218 /* decrease nb_queries to free a slot for a new query on that sess */
219 ds->nb_queries--;
220 if (ds->nb_queries) {
221 /* it remains pipelined unanswered request
222 * into this session but we just decrease
223 * the counter so the session
224 * can not be full of pipelined requests
225 * so we can add if to free_sess list
226 * to receive a new request
227 */
Willy Tarreau2b718102021-04-21 07:32:39 +0200228 LIST_INSERT(&ds->dss->free_sess, &ds->list);
Emeric Brunfd647d52021-02-12 20:03:38 +0100229 }
230 else {
231 /* there is no more pipelined requests
232 * into this session, so we move it
233 * to idle_sess list */
Willy Tarreau2b718102021-04-21 07:32:39 +0200234 LIST_INSERT(&ds->dss->idle_sess, &ds->list);
Emeric Brunfd647d52021-02-12 20:03:38 +0100235
236 /* update the counter of idle sessions */
237 ds->dss->idle_conns++;
238
239 /* Note: this is useless there to update
240 * the max_active_conns since we increase
241 * the idle count */
242 }
243 }
244 else {
245 /* there is no more appctx for this session
246 * it means it is ready to die
247 */
248 dns_session_free(ds);
249 }
250
251
252 }
253
254 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
255 }
Emeric Brund26a6232021-01-04 13:32:20 +0100256
257 return ret;
258}
259
260static void dns_resolve_recv(struct dgram_conn *dgram)
261{
262 struct dns_nameserver *ns;
263 int fd;
264
Emeric Brun314e6ec2022-05-10 11:35:48 +0200265 HA_SPIN_LOCK(DNS_LOCK, &dgram->lock);
266
Emeric Brund26a6232021-01-04 13:32:20 +0100267 fd = dgram->t.sock.fd;
268
269 /* check if ready for reading */
Emeric Brun314e6ec2022-05-10 11:35:48 +0200270 if ((fd == -1) || !fd_recv_ready(fd)) {
271 HA_SPIN_UNLOCK(DNS_LOCK, &dgram->lock);
Emeric Brund26a6232021-01-04 13:32:20 +0100272 return;
Emeric Brun314e6ec2022-05-10 11:35:48 +0200273 }
Emeric Brund26a6232021-01-04 13:32:20 +0100274
275 /* no need to go further if we can't retrieve the nameserver */
276 if ((ns = dgram->owner) == NULL) {
Willy Tarreauf5090652021-04-06 17:23:40 +0200277 _HA_ATOMIC_AND(&fdtab[fd].state, ~(FD_POLL_HUP|FD_POLL_ERR));
Emeric Brund26a6232021-01-04 13:32:20 +0100278 fd_stop_recv(fd);
Emeric Brun314e6ec2022-05-10 11:35:48 +0200279 HA_SPIN_UNLOCK(DNS_LOCK, &dgram->lock);
Emeric Brund26a6232021-01-04 13:32:20 +0100280 return;
281 }
282
Emeric Brun314e6ec2022-05-10 11:35:48 +0200283 HA_SPIN_UNLOCK(DNS_LOCK, &dgram->lock);
284
Emeric Brund26a6232021-01-04 13:32:20 +0100285 ns->process_responses(ns);
286}
287
288/* Called when a dns network socket is ready to send data */
289static void dns_resolve_send(struct dgram_conn *dgram)
290{
291 int fd;
292 struct dns_nameserver *ns;
293 struct ring *ring;
294 struct buffer *buf;
295 uint64_t msg_len;
296 size_t len, cnt, ofs;
297
Emeric Brun314e6ec2022-05-10 11:35:48 +0200298 HA_SPIN_LOCK(DNS_LOCK, &dgram->lock);
299
Emeric Brund26a6232021-01-04 13:32:20 +0100300 fd = dgram->t.sock.fd;
301
302 /* check if ready for sending */
Emeric Brun314e6ec2022-05-10 11:35:48 +0200303 if ((fd == -1) || !fd_send_ready(fd)) {
304 HA_SPIN_UNLOCK(DNS_LOCK, &dgram->lock);
Emeric Brund26a6232021-01-04 13:32:20 +0100305 return;
Emeric Brun314e6ec2022-05-10 11:35:48 +0200306 }
Emeric Brund26a6232021-01-04 13:32:20 +0100307
308 /* no need to go further if we can't retrieve the nameserver */
309 if ((ns = dgram->owner) == NULL) {
Willy Tarreauf5090652021-04-06 17:23:40 +0200310 _HA_ATOMIC_AND(&fdtab[fd].state, ~(FD_POLL_HUP|FD_POLL_ERR));
Emeric Brund26a6232021-01-04 13:32:20 +0100311 fd_stop_send(fd);
Emeric Brun314e6ec2022-05-10 11:35:48 +0200312 HA_SPIN_UNLOCK(DNS_LOCK, &dgram->lock);
Emeric Brund26a6232021-01-04 13:32:20 +0100313 return;
314 }
315
316 ring = ns->dgram->ring_req;
317 buf = &ring->buf;
318
319 HA_RWLOCK_RDLOCK(DNS_LOCK, &ring->lock);
Emeric Brund26a6232021-01-04 13:32:20 +0100320
321 /* explanation for the initialization below: it would be better to do
322 * this in the parsing function but this would occasionally result in
323 * dropped events because we'd take a reference on the oldest message
324 * and keep it while being scheduled. Thus instead let's take it the
325 * first time we enter here so that we have a chance to pass many
326 * existing messages before grabbing a reference to a location. This
327 * value cannot be produced after initialization.
328 */
Aurelien DARRAGONbce0c0c2023-03-07 18:01:34 +0100329 if (unlikely(ns->dgram->ofs_req == ~0)) {
330 ns->dgram->ofs_req = b_peek_ofs(buf, 0);
331 HA_ATOMIC_INC(b_orig(buf) + ns->dgram->ofs_req);
Emeric Brund26a6232021-01-04 13:32:20 +0100332 }
333
334 /* we were already there, adjust the offset to be relative to
335 * the buffer's head and remove us from the counter.
336 */
Aurelien DARRAGONbce0c0c2023-03-07 18:01:34 +0100337 ofs = ns->dgram->ofs_req - b_head_ofs(buf);
338 if (ns->dgram->ofs_req < b_head_ofs(buf))
339 ofs += b_size(buf);
Emeric Brund26a6232021-01-04 13:32:20 +0100340 BUG_ON(ofs >= buf->size);
Willy Tarreau4781b152021-04-06 13:53:36 +0200341 HA_ATOMIC_DEC(b_peek(buf, ofs));
Emeric Brund26a6232021-01-04 13:32:20 +0100342
343 while (ofs + 1 < b_data(buf)) {
344 int ret;
345
346 cnt = 1;
347 len = b_peek_varint(buf, ofs + cnt, &msg_len);
348 if (!len)
349 break;
350 cnt += len;
351 BUG_ON(msg_len + ofs + cnt + 1 > b_data(buf));
352 if (unlikely(msg_len > DNS_TCP_MSG_MAX_SIZE)) {
353 /* too large a message to ever fit, let's skip it */
354 ofs += cnt + msg_len;
355 continue;
356 }
357
358 len = b_getblk(buf, dns_msg_trash, msg_len, ofs + cnt);
359
360 ret = send(fd, dns_msg_trash, len, 0);
361 if (ret < 0) {
Willy Tarreauacef5e22022-04-25 20:32:15 +0200362 if (errno == EAGAIN || errno == EWOULDBLOCK) {
Emeric Brund26a6232021-01-04 13:32:20 +0100363 fd_cant_send(fd);
364 goto out;
365 }
366 ns->counters->snd_error++;
367 fd_delete(fd);
Emeric Brund26a6232021-01-04 13:32:20 +0100368 fd = dgram->t.sock.fd = -1;
369 goto out;
370 }
371 ns->counters->sent++;
372
373 ofs += cnt + len;
374 }
375
376 /* we don't want/need to be waked up any more for sending
377 * because all ring content is sent */
378 fd_stop_send(fd);
379
380out:
Willy Tarreau4781b152021-04-06 13:53:36 +0200381 HA_ATOMIC_INC(b_peek(buf, ofs));
Aurelien DARRAGONbce0c0c2023-03-07 18:01:34 +0100382 ns->dgram->ofs_req = b_peek_ofs(buf, ofs);
Emeric Brund26a6232021-01-04 13:32:20 +0100383 HA_RWLOCK_RDUNLOCK(DNS_LOCK, &ring->lock);
Emeric Brun314e6ec2022-05-10 11:35:48 +0200384 HA_SPIN_UNLOCK(DNS_LOCK, &dgram->lock);
Emeric Brund26a6232021-01-04 13:32:20 +0100385}
386
Emeric Brunc9437992021-02-12 19:42:55 +0100387/* proto_udp callback functions for a DNS resolution */
388struct dgram_data_cb dns_dgram_cb = {
389 .recv = dns_resolve_recv,
390 .send = dns_resolve_send,
391};
Baptiste Assmann325137d2015-04-13 23:40:55 +0200392
Emeric Brunc9437992021-02-12 19:42:55 +0100393int dns_dgram_init(struct dns_nameserver *ns, struct sockaddr_storage *sk)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200394{
Emeric Brunc9437992021-02-12 19:42:55 +0100395 struct dns_dgram_server *dgram;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200396
Emeric Brunc9437992021-02-12 19:42:55 +0100397 if ((dgram = calloc(1, sizeof(*dgram))) == NULL)
Christopher Faulet67957bd2017-09-27 11:00:59 +0200398 return -1;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200399
Emeric Brunc9437992021-02-12 19:42:55 +0100400 /* Leave dgram partially initialized, no FD attached for
401 * now. */
402 dgram->conn.owner = ns;
403 dgram->conn.data = &dns_dgram_cb;
404 dgram->conn.t.sock.fd = -1;
405 dgram->conn.addr.to = *sk;
Emeric Brun314e6ec2022-05-10 11:35:48 +0200406 HA_SPIN_INIT(&dgram->conn.lock);
Emeric Brunc9437992021-02-12 19:42:55 +0100407 ns->dgram = dgram;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200408
Emeric Brunc9437992021-02-12 19:42:55 +0100409 dgram->ofs_req = ~0; /* init ring offset */
410 dgram->ring_req = ring_new(2*DNS_TCP_MSG_RING_MAX_SIZE);
411 if (!dgram->ring_req) {
412 ha_alert("memory allocation error initializing the ring for nameserver.\n");
413 goto out;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200414 }
415
Emeric Brunc9437992021-02-12 19:42:55 +0100416 /* attach the task as reader */
417 if (!ring_attach(dgram->ring_req)) {
418 /* mark server attached to the ring */
419 ha_alert("nameserver sets too many watchers > 255 on ring. This is a bug and should not happen.\n");
420 goto out;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200421 }
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200422 return 0;
Emeric Brunc9437992021-02-12 19:42:55 +0100423out:
424 if (dgram->ring_req)
425 ring_free(dgram->ring_req);
Christopher Fauletd6c6b5f2020-09-08 10:27:24 +0200426
Emeric Brunc9437992021-02-12 19:42:55 +0100427 free(dgram);
Olivier Houchard2ec2db92018-01-08 16:28:57 +0100428
Emeric Brunfd647d52021-02-12 20:03:38 +0100429 return -1;
430}
431
432/*
433 * IO Handler to handle message push to dns tcp server
Willy Tarreau0d626a52022-05-04 20:41:19 +0200434 * It takes its context from appctx->svcctx.
Emeric Brunfd647d52021-02-12 20:03:38 +0100435 */
436static void dns_session_io_handler(struct appctx *appctx)
437{
Willy Tarreauc12b3212022-05-27 11:08:15 +0200438 struct stconn *sc = appctx_sc(appctx);
Willy Tarreau0d626a52022-05-04 20:41:19 +0200439 struct dns_session *ds = appctx->svcctx;
Emeric Brunfd647d52021-02-12 20:03:38 +0100440 struct ring *ring = &ds->ring;
441 struct buffer *buf = &ring->buf;
442 uint64_t msg_len;
443 int available_room;
444 size_t len, cnt, ofs;
445 int ret = 0;
446
447 /* if stopping was requested, close immediately */
448 if (unlikely(stopping))
449 goto close;
450
451 /* we want to be sure to not miss that we have been awaked for a shutdown */
452 __ha_barrier_load();
453
454 /* that means the connection was requested to shutdown
455 * for instance idle expire */
456 if (ds->shutdown)
457 goto close;
458
Christopher Fauletda89e9b2023-01-04 14:11:10 +0100459 if (unlikely(sc_ic(sc)->flags & CF_SHUTW))
Emeric Brunfd647d52021-02-12 20:03:38 +0100460 goto close;
461
462 /* con closed by server side, we will skip data write and drain data from channel */
Willy Tarreaud7950ad2022-05-27 10:33:42 +0200463 if ((sc_oc(sc)->flags & CF_SHUTW)) {
Emeric Brunfd647d52021-02-12 20:03:38 +0100464 goto read;
465 }
466
467 /* if the connection is not established, inform the stream that we want
468 * to be notified whenever the connection completes.
469 */
Willy Tarreaud7950ad2022-05-27 10:33:42 +0200470 if (sc_opposite(sc)->state < SC_ST_EST) {
Willy Tarreau90e8b452022-05-25 18:21:43 +0200471 applet_need_more_data(appctx);
Willy Tarreaub23edc82022-05-24 16:49:03 +0200472 se_need_remote_conn(appctx->sedesc);
Willy Tarreau4164eb92022-05-25 15:42:03 +0200473 applet_have_more_data(appctx);
Emeric Brunfd647d52021-02-12 20:03:38 +0100474 return;
475 }
476
Emeric Brunfd647d52021-02-12 20:03:38 +0100477 HA_RWLOCK_WRLOCK(DNS_LOCK, &ring->lock);
478 LIST_DEL_INIT(&appctx->wait_entry);
479 HA_RWLOCK_WRUNLOCK(DNS_LOCK, &ring->lock);
480
481 HA_RWLOCK_RDLOCK(DNS_LOCK, &ring->lock);
482
483 /* explanation for the initialization below: it would be better to do
484 * this in the parsing function but this would occasionally result in
485 * dropped events because we'd take a reference on the oldest message
486 * and keep it while being scheduled. Thus instead let's take it the
487 * first time we enter here so that we have a chance to pass many
488 * existing messages before grabbing a reference to a location. This
489 * value cannot be produced after initialization.
490 */
Amaury Denoyelle737d10f2023-03-07 11:18:27 +0100491 if (unlikely(ds->ofs == ~0)) {
Aurelien DARRAGON5a43db22023-03-07 17:45:02 +0100492 ds->ofs = b_peek_ofs(buf, 0);
493 HA_ATOMIC_INC(b_orig(buf) + ds->ofs);
Emeric Brunfd647d52021-02-12 20:03:38 +0100494 }
495
Christopher Faulet4d3283f2023-03-31 10:42:22 +0200496 /* we were already there, adjust the offset to be relative to
497 * the buffer's head and remove us from the counter.
Emeric Brunfd647d52021-02-12 20:03:38 +0100498 */
Christopher Faulet4d3283f2023-03-31 10:42:22 +0200499 ofs = ds->ofs - b_head_ofs(buf);
500 if (ds->ofs < b_head_ofs(buf))
501 ofs += b_size(buf);
Amaury Denoyelle737d10f2023-03-07 11:18:27 +0100502
Christopher Faulet4d3283f2023-03-31 10:42:22 +0200503 BUG_ON(ofs >= buf->size);
504 HA_ATOMIC_DEC(b_peek(buf, ofs));
Emeric Brunfd647d52021-02-12 20:03:38 +0100505
Christopher Faulet4d3283f2023-03-31 10:42:22 +0200506 /* in following loop, ofs always points to the counter byte that
507 * precedes the message so that we can take our reference there if we
508 * have to stop before the end (ret=0).
509 */
510 ret = 1;
511 while (ofs + 1 < b_data(buf)) {
512 struct dns_query *query;
513 uint16_t original_qid;
514 uint16_t new_qid;
Emeric Brunfd647d52021-02-12 20:03:38 +0100515
Christopher Faulet4d3283f2023-03-31 10:42:22 +0200516 cnt = 1;
517 len = b_peek_varint(buf, ofs + cnt, &msg_len);
518 if (!len)
519 break;
520 cnt += len;
521 BUG_ON(msg_len + ofs + cnt + 1 > b_data(buf));
Emeric Brunfd647d52021-02-12 20:03:38 +0100522
Christopher Faulet4d3283f2023-03-31 10:42:22 +0200523 /* retrieve available room on output channel */
524 available_room = channel_recv_max(sc_ic(sc));
Emeric Brunfd647d52021-02-12 20:03:38 +0100525
Christopher Faulet4d3283f2023-03-31 10:42:22 +0200526 /* tx_msg_offset null means we are at the start of a new message */
527 if (!ds->tx_msg_offset) {
528 uint16_t slen;
Emeric Brunfd647d52021-02-12 20:03:38 +0100529
Christopher Faulet4d3283f2023-03-31 10:42:22 +0200530 /* check if there is enough room to put message len and query id */
531 if (available_room < sizeof(slen) + sizeof(new_qid)) {
532 sc_need_room(sc);
533 ret = 0;
534 break;
535 }
Emeric Brunfd647d52021-02-12 20:03:38 +0100536
Christopher Faulet4d3283f2023-03-31 10:42:22 +0200537 /* put msg len into then channel */
538 slen = (uint16_t)msg_len;
539 slen = htons(slen);
540 applet_putblk(appctx, (char *)&slen, sizeof(slen));
541 available_room -= sizeof(slen);
Emeric Brunfd647d52021-02-12 20:03:38 +0100542
Christopher Faulet4d3283f2023-03-31 10:42:22 +0200543 /* backup original query id */
544 len = b_getblk(buf, (char *)&original_qid, sizeof(original_qid), ofs + cnt);
545 if (!len) {
546 /* should never happen since messages are atomically
547 * written into ring
548 */
549 ret = 0;
550 break;
551 }
Emeric Brunfd647d52021-02-12 20:03:38 +0100552
Christopher Faulet4d3283f2023-03-31 10:42:22 +0200553 /* generates new query id */
554 new_qid = ++ds->query_counter;
555 new_qid = htons(new_qid);
Emeric Brunfd647d52021-02-12 20:03:38 +0100556
Christopher Faulet4d3283f2023-03-31 10:42:22 +0200557 /* put new query id into the channel */
558 applet_putblk(appctx, (char *)&new_qid, sizeof(new_qid));
559 available_room -= sizeof(new_qid);
Emeric Brunfd647d52021-02-12 20:03:38 +0100560
Christopher Faulet4d3283f2023-03-31 10:42:22 +0200561 /* keep query id mapping */
Emeric Brunfd647d52021-02-12 20:03:38 +0100562
Christopher Faulet4d3283f2023-03-31 10:42:22 +0200563 query = pool_alloc(dns_query_pool);
564 if (query) {
565 query->qid.key = new_qid;
566 query->original_qid = original_qid;
567 query->expire = tick_add(now_ms, 5000);
568 LIST_INIT(&query->list);
569 if (LIST_ISEMPTY(&ds->queries)) {
570 /* enable task to handle expire */
571 ds->task_exp->expire = query->expire;
572 /* ensure this will be executed by the same
573 * thread than ds_session_release
574 * to ensure session_release is free
575 * to destroy the task */
576 task_queue(ds->task_exp);
Emeric Brunfd647d52021-02-12 20:03:38 +0100577 }
Christopher Faulet4d3283f2023-03-31 10:42:22 +0200578 LIST_APPEND(&ds->queries, &query->list);
579 eb32_insert(&ds->query_ids, &query->qid);
580 ds->onfly_queries++;
Emeric Brunfd647d52021-02-12 20:03:38 +0100581 }
582
Christopher Faulet4d3283f2023-03-31 10:42:22 +0200583 /* update the tx_offset to handle output in 16k streams */
584 ds->tx_msg_offset = sizeof(original_qid);
Emeric Brunfd647d52021-02-12 20:03:38 +0100585
Christopher Faulet4d3283f2023-03-31 10:42:22 +0200586 }
Emeric Brunfd647d52021-02-12 20:03:38 +0100587
Christopher Faulet4d3283f2023-03-31 10:42:22 +0200588 /* check if it remains available room on output chan */
589 if (unlikely(!available_room)) {
590 sc_need_room(sc);
591 ret = 0;
592 break;
593 }
Emeric Brunfd647d52021-02-12 20:03:38 +0100594
Christopher Faulet4d3283f2023-03-31 10:42:22 +0200595 chunk_reset(&trash);
596 if ((msg_len - ds->tx_msg_offset) > available_room) {
597 /* remaining msg data is too large to be written in output channel at one time */
Emeric Brunfd647d52021-02-12 20:03:38 +0100598
Christopher Faulet4d3283f2023-03-31 10:42:22 +0200599 len = b_getblk(buf, trash.area, available_room, ofs + cnt + ds->tx_msg_offset);
Emeric Brunfd647d52021-02-12 20:03:38 +0100600
Christopher Faulet4d3283f2023-03-31 10:42:22 +0200601 /* update offset to complete mesg forwarding later */
602 ds->tx_msg_offset += len;
603 }
604 else {
605 /* remaining msg data can be written in output channel at one time */
606 len = b_getblk(buf, trash.area, msg_len - ds->tx_msg_offset, ofs + cnt + ds->tx_msg_offset);
Emeric Brunfd647d52021-02-12 20:03:38 +0100607
Christopher Faulet4d3283f2023-03-31 10:42:22 +0200608 /* reset tx_msg_offset to mark forward fully processed */
609 ds->tx_msg_offset = 0;
610 }
611 trash.data += len;
Emeric Brunfd647d52021-02-12 20:03:38 +0100612
Christopher Faulet4d3283f2023-03-31 10:42:22 +0200613 if (applet_putchk(appctx, &trash) == -1) {
614 /* should never happen since we
615 * check available_room is large
616 * enough here.
617 */
618 ret = 0;
619 break;
Emeric Brunfd647d52021-02-12 20:03:38 +0100620 }
621
Christopher Faulet4d3283f2023-03-31 10:42:22 +0200622 if (ds->tx_msg_offset) {
623 /* msg was not fully processed, we must be awake to drain pending data */
624
625 sc_need_room(sc);
626 ret = 0;
627 break;
628 }
629 /* switch to next message */
630 ofs += cnt + msg_len;
Emeric Brunfd647d52021-02-12 20:03:38 +0100631 }
Christopher Faulet4d3283f2023-03-31 10:42:22 +0200632
633 HA_ATOMIC_INC(b_peek(buf, ofs));
634 ds->ofs = b_peek_ofs(buf, ofs);
635
Emeric Brunfd647d52021-02-12 20:03:38 +0100636 HA_RWLOCK_RDUNLOCK(DNS_LOCK, &ring->lock);
637
638 if (ret) {
639 /* let's be woken up once new request to write arrived */
640 HA_RWLOCK_WRLOCK(DNS_LOCK, &ring->lock);
Willy Tarreau62e467c2021-10-20 11:02:13 +0200641 BUG_ON(LIST_INLIST(&appctx->wait_entry));
Willy Tarreau2b718102021-04-21 07:32:39 +0200642 LIST_APPEND(&ring->waiters, &appctx->wait_entry);
Emeric Brunfd647d52021-02-12 20:03:38 +0100643 HA_RWLOCK_WRUNLOCK(DNS_LOCK, &ring->lock);
Willy Tarreau4164eb92022-05-25 15:42:03 +0200644 applet_have_no_more_data(appctx);
Emeric Brunfd647d52021-02-12 20:03:38 +0100645 }
646
647read:
648
Ilya Shipitsin0de36ad2021-02-20 00:23:36 +0500649 /* if session is not a waiter it means there is no committed
Emeric Brunfd647d52021-02-12 20:03:38 +0100650 * message into rx_buf and we are free to use it
651 * Note: we need a load barrier here to not miss the
652 * delete from the list
653 */
Emeric Brun70455902021-10-20 10:49:53 +0200654
Willy Tarreaudde1b442021-10-21 14:33:38 +0200655 __ha_barrier_load();
656 if (!LIST_INLIST_ATOMIC(&ds->waiter)) {
Emeric Brunfd647d52021-02-12 20:03:38 +0100657 while (1) {
658 uint16_t query_id;
659 struct eb32_node *eb;
660 struct dns_query *query;
661
662 if (!ds->rx_msg.len) {
Emeric Brunfd647d52021-02-12 20:03:38 +0100663 /* retrieve message len */
Christopher Faulet28975e12023-03-30 15:49:30 +0200664 ret = co_getblk(sc_oc(sc), (char *)&msg_len, 2, 0);
665 if (ret <= 0) {
666 if (ret == -1)
667 goto close;
668 applet_need_more_data(appctx);
669 break;
670 }
Emeric Brunfd647d52021-02-12 20:03:38 +0100671
672 /* mark as consumed */
Willy Tarreaud7950ad2022-05-27 10:33:42 +0200673 co_skip(sc_oc(sc), 2);
Emeric Brunfd647d52021-02-12 20:03:38 +0100674
675 /* store message len */
676 ds->rx_msg.len = ntohs(msg_len);
Christopher Faulet28975e12023-03-30 15:49:30 +0200677 if (!ds->rx_msg.len)
678 continue;
Emeric Brunfd647d52021-02-12 20:03:38 +0100679 }
680
Willy Tarreaud7950ad2022-05-27 10:33:42 +0200681 if (co_data(sc_oc(sc)) + ds->rx_msg.offset < ds->rx_msg.len) {
Emeric Brunfd647d52021-02-12 20:03:38 +0100682 /* message only partially available */
683
684 /* read available data */
Christopher Faulet28975e12023-03-30 15:49:30 +0200685 ret = co_getblk(sc_oc(sc), ds->rx_msg.area + ds->rx_msg.offset, co_data(sc_oc(sc)), 0);
686 if (ret <= 0) {
687 if (ret == -1)
688 goto close;
689 applet_need_more_data(appctx);
690 break;
691 }
Emeric Brunfd647d52021-02-12 20:03:38 +0100692
693 /* update message offset */
Willy Tarreaud7950ad2022-05-27 10:33:42 +0200694 ds->rx_msg.offset += co_data(sc_oc(sc));
Emeric Brunfd647d52021-02-12 20:03:38 +0100695
696 /* consume all pending data from the channel */
Willy Tarreaud7950ad2022-05-27 10:33:42 +0200697 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
Emeric Brunfd647d52021-02-12 20:03:38 +0100698
699 /* we need to wait for more data */
Christopher Faulet28975e12023-03-30 15:49:30 +0200700 applet_need_more_data(appctx);
Emeric Brunfd647d52021-02-12 20:03:38 +0100701 break;
702 }
703
Ilya Shipitsin0de36ad2021-02-20 00:23:36 +0500704 /* enough data is available into the channel to read the message until the end */
Emeric Brunfd647d52021-02-12 20:03:38 +0100705
706 /* read from the channel until the end of the message */
Christopher Faulet28975e12023-03-30 15:49:30 +0200707 ret = co_getblk(sc_oc(sc), ds->rx_msg.area + ds->rx_msg.offset, ds->rx_msg.len - ds->rx_msg.offset, 0);
708 if (ret <= 0) {
709 if (ret == -1)
710 goto close;
711 applet_need_more_data(appctx);
712 break;
713 }
Emeric Brunfd647d52021-02-12 20:03:38 +0100714
715 /* consume all data until the end of the message from the channel */
Willy Tarreaud7950ad2022-05-27 10:33:42 +0200716 co_skip(sc_oc(sc), ds->rx_msg.len - ds->rx_msg.offset);
Emeric Brunfd647d52021-02-12 20:03:38 +0100717
718 /* reset reader offset to 0 for next message reand */
719 ds->rx_msg.offset = 0;
720
721 /* try remap query id to original */
722 memcpy(&query_id, ds->rx_msg.area, sizeof(query_id));
723 eb = eb32_lookup(&ds->query_ids, query_id);
724 if (!eb) {
725 /* query id not found means we have an unknown corresponding
726 * request, perhaps server's bug or or the query reached
727 * timeout
728 */
729 ds->rx_msg.len = 0;
730 continue;
731 }
732
733 /* re-map the original query id set by the requester */
734 query = eb32_entry(eb, struct dns_query, qid);
735 memcpy(ds->rx_msg.area, &query->original_qid, sizeof(query->original_qid));
736
737 /* remove query ids mapping from pending queries list/tree */
738 eb32_delete(&query->qid);
Willy Tarreau2b718102021-04-21 07:32:39 +0200739 LIST_DELETE(&query->list);
Emeric Brunfd647d52021-02-12 20:03:38 +0100740 pool_free(dns_query_pool, query);
741 ds->onfly_queries--;
742
Emeric Brunfd647d52021-02-12 20:03:38 +0100743 /* the dns_session is also added in queue of the
744 * wait_sess list where the task processing
745 * response will pop available responses
746 */
Willy Tarreaudde1b442021-10-21 14:33:38 +0200747 HA_SPIN_LOCK(DNS_LOCK, &ds->dss->lock);
748
Willy Tarreau62e467c2021-10-20 11:02:13 +0200749 BUG_ON(LIST_INLIST(&ds->waiter));
Willy Tarreau2b718102021-04-21 07:32:39 +0200750 LIST_APPEND(&ds->dss->wait_sess, &ds->waiter);
Emeric Brunfd647d52021-02-12 20:03:38 +0100751
Willy Tarreaudde1b442021-10-21 14:33:38 +0200752 HA_SPIN_UNLOCK(DNS_LOCK, &ds->dss->lock);
753
Emeric Brunfd647d52021-02-12 20:03:38 +0100754 /* awake the task processing the responses */
755 task_wakeup(ds->dss->task_rsp, TASK_WOKEN_INIT);
756
757 break;
758 }
759
Willy Tarreau2b718102021-04-21 07:32:39 +0200760 if (!LIST_INLIST(&ds->waiter)) {
Emeric Brunfd647d52021-02-12 20:03:38 +0100761 /* there is no more pending data to read and the con was closed by the server side */
Willy Tarreaud7950ad2022-05-27 10:33:42 +0200762 if (!co_data(sc_oc(sc)) && (sc_oc(sc)->flags & CF_SHUTW)) {
Emeric Brunfd647d52021-02-12 20:03:38 +0100763 goto close;
764 }
765 }
766
767 }
768
Emeric Brunfd647d52021-02-12 20:03:38 +0100769 return;
770close:
Willy Tarreaud7950ad2022-05-27 10:33:42 +0200771 sc_shutw(sc);
772 sc_shutr(sc);
Emeric Brunfd647d52021-02-12 20:03:38 +0100773}
774
775void dns_queries_flush(struct dns_session *ds)
776{
777 struct dns_query *query, *queryb;
778
779 list_for_each_entry_safe(query, queryb, &ds->queries, list) {
780 eb32_delete(&query->qid);
Willy Tarreau2b718102021-04-21 07:32:39 +0200781 LIST_DELETE(&query->list);
Emeric Brunfd647d52021-02-12 20:03:38 +0100782 pool_free(dns_query_pool, query);
783 }
784}
785
786void dns_session_free(struct dns_session *ds)
787{
788 if (ds->rx_msg.area)
789 pool_free(dns_msg_buf, ds->rx_msg.area);
790 if (ds->tx_ring_area)
791 pool_free(dns_msg_buf, ds->tx_ring_area);
792 if (ds->task_exp)
793 task_destroy(ds->task_exp);
794
795 dns_queries_flush(ds);
796
Emeric Brund20dc212021-10-19 15:40:10 +0200797 /* Ensure to remove this session from external lists
798 * Note: we are under the lock of dns_stream_server
799 * which own the heads of those lists.
800 */
801 LIST_DEL_INIT(&ds->waiter);
802 LIST_DEL_INIT(&ds->list);
803
Emeric Brunfd647d52021-02-12 20:03:38 +0100804 ds->dss->cur_conns--;
805 /* Note: this is useless to update
806 * max_active_conns here because
807 * we decrease the value
808 */
Willy Tarreau62e467c2021-10-20 11:02:13 +0200809
810 BUG_ON(!LIST_ISEMPTY(&ds->list));
811 BUG_ON(!LIST_ISEMPTY(&ds->waiter));
812 BUG_ON(!LIST_ISEMPTY(&ds->queries));
813 BUG_ON(!LIST_ISEMPTY(&ds->ring.waiters));
814 BUG_ON(!eb_is_empty(&ds->query_ids));
Emeric Brunfd647d52021-02-12 20:03:38 +0100815 pool_free(dns_session_pool, ds);
816}
817
818static struct appctx *dns_session_create(struct dns_session *ds);
819
Christopher Faulet92238512022-05-12 15:24:46 +0200820static int dns_session_init(struct appctx *appctx)
821{
822 struct dns_session *ds = appctx->svcctx;
823 struct stream *s;
824 struct sockaddr_storage *addr = NULL;
825
826 if (!sockaddr_alloc(&addr, &ds->dss->srv->addr, sizeof(ds->dss->srv->addr)))
827 goto error;
828
829 if (appctx_finalize_startup(appctx, ds->dss->srv->proxy, &BUF_NULL) == -1)
830 goto error;
831
832 s = appctx_strm(appctx);
Willy Tarreau7cb9e6c2022-05-17 19:40:40 +0200833 s->scb->dst = addr;
Christopher Faulet9a790f62023-03-16 14:40:03 +0100834 s->scb->flags |= (SC_FL_RCV_ONCE|SC_FL_NOLINGER);
Christopher Faulet92238512022-05-12 15:24:46 +0200835 s->target = &ds->dss->srv->obj_type;
836 s->flags = SF_ASSIGNED;
837
838 s->do_log = NULL;
839 s->uniq_id = 0;
840
Christopher Faulet2ca4cc12023-02-22 14:22:56 +0100841 applet_expect_no_data(appctx);
Christopher Faulet92238512022-05-12 15:24:46 +0200842 ds->appctx = appctx;
843 return 0;
844
845 error:
846 return -1;
847}
848
Emeric Brunfd647d52021-02-12 20:03:38 +0100849/*
850 * Function to release a DNS tcp session
851 */
852static void dns_session_release(struct appctx *appctx)
853{
Willy Tarreau0d626a52022-05-04 20:41:19 +0200854 struct dns_session *ds = appctx->svcctx;
Willy Tarreaue3e648c2021-02-24 17:38:46 +0100855 struct dns_stream_server *dss __maybe_unused;
Emeric Brunfd647d52021-02-12 20:03:38 +0100856
857 if (!ds)
858 return;
859
Willy Tarreaub56a8782021-10-20 14:38:43 +0200860 /* We do not call ring_appctx_detach here
861 * because we want to keep readers counters
862 * to retry a conn with a different appctx.
863 */
864 HA_RWLOCK_WRLOCK(DNS_LOCK, &ds->ring.lock);
865 LIST_DEL_INIT(&appctx->wait_entry);
866 HA_RWLOCK_WRUNLOCK(DNS_LOCK, &ds->ring.lock);
867
Emeric Brunfd647d52021-02-12 20:03:38 +0100868 dss = ds->dss;
869
870 HA_SPIN_LOCK(DNS_LOCK, &dss->lock);
871 LIST_DEL_INIT(&ds->list);
872
873 if (stopping) {
874 dns_session_free(ds);
875 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
876 return;
877 }
878
879 if (!ds->nb_queries) {
880 /* this is an idle session */
881 /* Note: this is useless to update max_active_sess
882 * here because we decrease idle_conns but
883 * dns_session_free decrease curconns
884 */
885
886 ds->dss->idle_conns--;
887 dns_session_free(ds);
888 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
889 return;
890 }
891
892 if (ds->onfly_queries == ds->nb_queries) {
893 /* the session can be released because
894 * it means that all queries AND
895 * responses are in fly */
896 dns_session_free(ds);
897 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
898 return;
899 }
900
Emeric Brunfd647d52021-02-12 20:03:38 +0100901 /* if there is no pending complete response
902 * message, ensure to reset
903 * message offsets if the session
904 * was closed with an incomplete pending response
905 */
Willy Tarreau2b718102021-04-21 07:32:39 +0200906 if (!LIST_INLIST(&ds->waiter))
Emeric Brunfd647d52021-02-12 20:03:38 +0100907 ds->rx_msg.len = ds->rx_msg.offset = 0;
908
909 /* we flush pending sent queries because we never
910 * have responses
911 */
912 ds->nb_queries -= ds->onfly_queries;
913 dns_queries_flush(ds);
914
915 /* reset offset to be sure to start from message start */
916 ds->tx_msg_offset = 0;
917
918 /* here the ofs and the attached counter
919 * are kept unchanged
920 */
921
922 /* Create a new appctx, We hope we can
923 * create from the release callback! */
924 ds->appctx = dns_session_create(ds);
925 if (!ds->appctx) {
926 dns_session_free(ds);
927 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
928 return;
929 }
930
931 if (ds->nb_queries < DNS_STREAM_MAX_PIPELINED_REQ)
Willy Tarreau2b718102021-04-21 07:32:39 +0200932 LIST_INSERT(&ds->dss->free_sess, &ds->list);
Emeric Brunfd647d52021-02-12 20:03:38 +0100933
934 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
935}
936
937/* DNS tcp session applet */
938static struct applet dns_session_applet = {
939 .obj_type = OBJ_TYPE_APPLET,
940 .name = "<STRMDNS>", /* used for logging */
941 .fct = dns_session_io_handler,
Christopher Faulet92238512022-05-12 15:24:46 +0200942 .init = dns_session_init,
Emeric Brunfd647d52021-02-12 20:03:38 +0100943 .release = dns_session_release,
944};
945
946/*
947 * Function used to create an appctx for a DNS session
Willy Tarreau0d626a52022-05-04 20:41:19 +0200948 * It sets its context into appctx->svcctx.
Emeric Brunfd647d52021-02-12 20:03:38 +0100949 */
950static struct appctx *dns_session_create(struct dns_session *ds)
951{
952 struct appctx *appctx;
Emeric Brunfd647d52021-02-12 20:03:38 +0100953
Christopher Faulet6095d572022-05-16 17:09:48 +0200954 appctx = appctx_new_here(&dns_session_applet, NULL);
Christopher Faulet2479e5f2022-01-19 14:50:11 +0100955 if (!appctx)
Christopher Fauleta9e8b392022-03-23 11:01:09 +0100956 goto out_close;
Willy Tarreau0d626a52022-05-04 20:41:19 +0200957 appctx->svcctx = (void *)ds;
Emeric Brunfd647d52021-02-12 20:03:38 +0100958
Christopher Faulet92238512022-05-12 15:24:46 +0200959 if (appctx_init(appctx) == -1) {
Christopher Faulet13a35e52021-12-20 15:34:16 +0100960 ha_alert("out of memory in dns_session_create().\n");
Emeric Brunfd647d52021-02-12 20:03:38 +0100961 goto out_free_appctx;
Christopher Faulet13a35e52021-12-20 15:34:16 +0100962 }
963
Emeric Brunfd647d52021-02-12 20:03:38 +0100964 return appctx;
965
966 /* Error unrolling */
Emeric Brunfd647d52021-02-12 20:03:38 +0100967 out_free_appctx:
Christopher Faulet92238512022-05-12 15:24:46 +0200968 appctx_free_on_early_error(appctx);
Emeric Brunfd647d52021-02-12 20:03:38 +0100969 out_close:
970 return NULL;
971}
972
973/* Task processing expiration of unresponded queries, this one is supposed
974 * to be stuck on the same thread than the appctx handler
975 */
Willy Tarreau144f84a2021-03-02 16:09:26 +0100976static struct task *dns_process_query_exp(struct task *t, void *context, unsigned int state)
Emeric Brunfd647d52021-02-12 20:03:38 +0100977{
978 struct dns_session *ds = (struct dns_session *)context;
979 struct dns_query *query, *queryb;
980
981 t->expire = TICK_ETERNITY;
982
983 list_for_each_entry_safe(query, queryb, &ds->queries, list) {
984 if (tick_is_expired(query->expire, now_ms)) {
985 eb32_delete(&query->qid);
Willy Tarreau2b718102021-04-21 07:32:39 +0200986 LIST_DELETE(&query->list);
Emeric Brunfd647d52021-02-12 20:03:38 +0100987 pool_free(dns_query_pool, query);
988 ds->onfly_queries--;
989 }
990 else {
991 t->expire = query->expire;
992 break;
993 }
994 }
995
996 return t;
997}
998
999/* Task processing expiration of idle sessions */
Willy Tarreau144f84a2021-03-02 16:09:26 +01001000static struct task *dns_process_idle_exp(struct task *t, void *context, unsigned int state)
Emeric Brunfd647d52021-02-12 20:03:38 +01001001{
1002 struct dns_stream_server *dss = (struct dns_stream_server *)context;
1003 struct dns_session *ds, *dsb;
1004 int target = 0;
1005 int cur_active_conns;
1006
1007 HA_SPIN_LOCK(DNS_LOCK, &dss->lock);
1008
1009
1010 cur_active_conns = dss->cur_conns - dss->idle_conns;
1011 if (cur_active_conns > dss->max_active_conns)
1012 dss->max_active_conns = cur_active_conns;
1013
1014 target = (dss->max_active_conns - cur_active_conns) / 2;
1015 list_for_each_entry_safe(ds, dsb, &dss->idle_sess, list) {
1016 if (!target)
1017 break;
1018
1019 /* remove conn to pending list to ensure it won't be reused */
1020 LIST_DEL_INIT(&ds->list);
1021
1022 /* force session shutdown */
1023 ds->shutdown = 1;
1024
Ilya Shipitsin0de36ad2021-02-20 00:23:36 +05001025 /* to be sure that the appctx won't miss shutdown */
Emeric Brunfd647d52021-02-12 20:03:38 +01001026 __ha_barrier_store();
1027
1028 /* wake appctx to perform the shutdown */
1029 appctx_wakeup(ds->appctx);
1030 }
1031
1032 /* reset max to current active conns */
1033 dss->max_active_conns = cur_active_conns;
1034
1035 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
1036
1037 t->expire = tick_add(now_ms, 5000);
1038
1039 return t;
1040}
1041
1042struct dns_session *dns_session_new(struct dns_stream_server *dss)
1043{
1044 struct dns_session *ds;
1045
1046 if (dss->maxconn && (dss->maxconn <= dss->cur_conns))
1047 return NULL;
1048
Christopher Faulet14a60d42022-08-03 10:30:06 +02001049 ds = pool_zalloc(dns_session_pool);
Emeric Brunfd647d52021-02-12 20:03:38 +01001050 if (!ds)
1051 return NULL;
1052
1053 ds->ofs = ~0;
1054 ds->dss = dss;
1055 LIST_INIT(&ds->list);
1056 LIST_INIT(&ds->queries);
1057 LIST_INIT(&ds->waiter);
1058 ds->rx_msg.offset = ds->rx_msg.len = 0;
1059 ds->rx_msg.area = NULL;
1060 ds->tx_ring_area = NULL;
1061 ds->task_exp = NULL;
1062 ds->appctx = NULL;
1063 ds->shutdown = 0;
1064 ds->nb_queries = 0;
1065 ds->query_ids = EB_ROOT_UNIQUE;
1066 ds->rx_msg.area = pool_alloc(dns_msg_buf);
1067 if (!ds->rx_msg.area)
1068 goto error;
1069
1070 ds->tx_ring_area = pool_alloc(dns_msg_buf);
1071 if (!ds->tx_ring_area)
1072 goto error;
1073
1074 ring_init(&ds->ring, ds->tx_ring_area, DNS_TCP_MSG_RING_MAX_SIZE);
Christopher Faulet1a1b6742021-03-04 16:53:27 +01001075 /* never fail because it is the first watcher attached to the ring */
1076 DISGUISE(ring_attach(&ds->ring));
Emeric Brunfd647d52021-02-12 20:03:38 +01001077
Willy Tarreaubeeabf52021-10-01 18:23:30 +02001078 if ((ds->task_exp = task_new_here()) == NULL)
Emeric Brunfd647d52021-02-12 20:03:38 +01001079 goto error;
1080
1081 ds->task_exp->process = dns_process_query_exp;
1082 ds->task_exp->context = ds;
1083
1084 ds->appctx = dns_session_create(ds);
1085 if (!ds->appctx)
1086 goto error;
1087
1088 dss->cur_conns++;
1089
1090 return ds;
1091
1092error:
1093 if (ds->task_exp)
1094 task_destroy(ds->task_exp);
1095 if (ds->rx_msg.area)
1096 pool_free(dns_msg_buf, ds->rx_msg.area);
1097 if (ds->tx_ring_area)
1098 pool_free(dns_msg_buf, ds->tx_ring_area);
1099
1100 pool_free(dns_session_pool, ds);
1101
1102 return NULL;
1103}
1104
1105/*
1106 * Task used to consume pending messages from nameserver ring
1107 * and forward them to dns_session ring.
1108 * Note: If no slot found a new dns_session is allocated
1109 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01001110static struct task *dns_process_req(struct task *t, void *context, unsigned int state)
Emeric Brunfd647d52021-02-12 20:03:38 +01001111{
1112 struct dns_nameserver *ns = (struct dns_nameserver *)context;
1113 struct dns_stream_server *dss = ns->stream;
1114 struct ring *ring = dss->ring_req;
1115 struct buffer *buf = &ring->buf;
1116 uint64_t msg_len;
1117 size_t len, cnt, ofs;
1118 struct dns_session *ds, *ads;
1119 HA_SPIN_LOCK(DNS_LOCK, &dss->lock);
1120
Emeric Brunfd647d52021-02-12 20:03:38 +01001121 HA_RWLOCK_RDLOCK(DNS_LOCK, &ring->lock);
1122
1123 /* explanation for the initialization below: it would be better to do
1124 * this in the parsing function but this would occasionally result in
1125 * dropped events because we'd take a reference on the oldest message
1126 * and keep it while being scheduled. Thus instead let's take it the
1127 * first time we enter here so that we have a chance to pass many
1128 * existing messages before grabbing a reference to a location. This
1129 * value cannot be produced after initialization.
1130 */
Amaury Denoyelle737d10f2023-03-07 11:18:27 +01001131 if (unlikely(dss->ofs_req == ~0)) {
Aurelien DARRAGON5a43db22023-03-07 17:45:02 +01001132 dss->ofs_req = b_peek_ofs(buf, 0);
1133 HA_ATOMIC_INC(b_orig(buf) + dss->ofs_req);
Emeric Brunfd647d52021-02-12 20:03:38 +01001134 }
1135
1136 /* we were already there, adjust the offset to be relative to
1137 * the buffer's head and remove us from the counter.
1138 */
Amaury Denoyelle737d10f2023-03-07 11:18:27 +01001139 ofs = dss->ofs_req - b_head_ofs(buf);
1140 if (dss->ofs_req < b_head_ofs(buf))
1141 ofs += b_size(buf);
1142
Emeric Brunfd647d52021-02-12 20:03:38 +01001143 BUG_ON(ofs >= buf->size);
Willy Tarreau4781b152021-04-06 13:53:36 +02001144 HA_ATOMIC_DEC(b_peek(buf, ofs));
Emeric Brunfd647d52021-02-12 20:03:38 +01001145
1146 while (ofs + 1 < b_data(buf)) {
1147 struct ist myist;
1148
1149 cnt = 1;
1150 len = b_peek_varint(buf, ofs + cnt, &msg_len);
1151 if (!len)
1152 break;
1153 cnt += len;
1154 BUG_ON(msg_len + ofs + cnt + 1 > b_data(buf));
1155 if (unlikely(msg_len > DNS_TCP_MSG_MAX_SIZE)) {
1156 /* too large a message to ever fit, let's skip it */
1157 ofs += cnt + msg_len;
1158 continue;
1159 }
1160
1161 len = b_getblk(buf, dns_msg_trash, msg_len, ofs + cnt);
1162
Tim Duesterhus92c696e2021-02-28 16:11:36 +01001163 myist = ist2(dns_msg_trash, len);
Emeric Brunfd647d52021-02-12 20:03:38 +01001164
1165 ads = NULL;
Ilya Shipitsin0de36ad2021-02-20 00:23:36 +05001166 /* try to push request into active sess with free slot */
Emeric Brunfd647d52021-02-12 20:03:38 +01001167 if (!LIST_ISEMPTY(&dss->free_sess)) {
1168 ds = LIST_NEXT(&dss->free_sess, struct dns_session *, list);
1169
1170 if (ring_write(&ds->ring, DNS_TCP_MSG_MAX_SIZE, NULL, 0, &myist, 1) > 0) {
1171 ds->nb_queries++;
1172 if (ds->nb_queries >= DNS_STREAM_MAX_PIPELINED_REQ)
1173 LIST_DEL_INIT(&ds->list);
1174 ads = ds;
1175 }
1176 else {
1177 /* it means we were unable to put a request in this slot,
1178 * it may be close to be full so we put it at the end
1179 * of free conn list */
1180 LIST_DEL_INIT(&ds->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02001181 LIST_APPEND(&dss->free_sess, &ds->list);
Emeric Brunfd647d52021-02-12 20:03:38 +01001182 }
1183 }
1184
1185 if (!ads) {
Ilya Shipitsin0de36ad2021-02-20 00:23:36 +05001186 /* try to push request into idle, this one should have enough free space */
Emeric Brunfd647d52021-02-12 20:03:38 +01001187 if (!LIST_ISEMPTY(&dss->idle_sess)) {
1188 ds = LIST_NEXT(&dss->idle_sess, struct dns_session *, list);
1189
1190 /* ring is empty so this ring_write should never fail */
1191 ring_write(&ds->ring, DNS_TCP_MSG_MAX_SIZE, NULL, 0, &myist, 1);
1192 ds->nb_queries++;
1193 LIST_DEL_INIT(&ds->list);
1194
1195 ds->dss->idle_conns--;
1196
1197 /* we may have to update the max_active_conns */
1198 if (ds->dss->max_active_conns < ds->dss->cur_conns - ds->dss->idle_conns)
1199 ds->dss->max_active_conns = ds->dss->cur_conns - ds->dss->idle_conns;
1200
1201 /* since we may unable to find a free list to handle
1202 * this request, this request may be large and fill
1203 * the ring buffer so we prefer to put at the end of free
1204 * list. */
Willy Tarreau2b718102021-04-21 07:32:39 +02001205 LIST_APPEND(&dss->free_sess, &ds->list);
Emeric Brunfd647d52021-02-12 20:03:38 +01001206 ads = ds;
1207 }
1208 }
1209
Ilya Shipitsin0de36ad2021-02-20 00:23:36 +05001210 /* we didn't find a session available with large enough room */
Emeric Brunfd647d52021-02-12 20:03:38 +01001211 if (!ads) {
1212 /* allocate a new session */
1213 ads = dns_session_new(dss);
1214 if (ads) {
1215 /* ring is empty so this ring_write should never fail */
1216 ring_write(&ads->ring, DNS_TCP_MSG_MAX_SIZE, NULL, 0, &myist, 1);
1217 ads->nb_queries++;
Willy Tarreau2b718102021-04-21 07:32:39 +02001218 LIST_INSERT(&dss->free_sess, &ads->list);
Emeric Brunfd647d52021-02-12 20:03:38 +01001219 }
1220 else
1221 ns->counters->snd_error++;
1222 }
1223
1224 if (ads)
1225 ns->counters->sent++;
1226
1227 ofs += cnt + len;
1228 }
1229
Willy Tarreau4781b152021-04-06 13:53:36 +02001230 HA_ATOMIC_INC(b_peek(buf, ofs));
Amaury Denoyelle737d10f2023-03-07 11:18:27 +01001231 dss->ofs_req = b_peek_ofs(buf, ofs);
Emeric Brunfd647d52021-02-12 20:03:38 +01001232 HA_RWLOCK_RDUNLOCK(DNS_LOCK, &ring->lock);
1233
1234
1235 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
1236 return t;
1237}
1238
1239/*
1240 * Task used to consume response
1241 * Note: upper layer callback is called
1242 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01001243static struct task *dns_process_rsp(struct task *t, void *context, unsigned int state)
Emeric Brunfd647d52021-02-12 20:03:38 +01001244{
1245 struct dns_nameserver *ns = (struct dns_nameserver *)context;
1246
1247 ns->process_responses(ns);
1248
1249 return t;
1250}
1251
1252/* Function used to initialize an TCP nameserver */
1253int dns_stream_init(struct dns_nameserver *ns, struct server *srv)
1254{
1255 struct dns_stream_server *dss = NULL;
1256
1257 dss = calloc(1, sizeof(*dss));
1258 if (!dss) {
1259 ha_alert("memory allocation error initializing dns tcp server '%s'.\n", srv->id);
1260 goto out;
1261 }
1262
1263 dss->srv = srv;
1264 dss->maxconn = srv->maxconn;
1265
1266 dss->ofs_req = ~0; /* init ring offset */
1267 dss->ring_req = ring_new(2*DNS_TCP_MSG_RING_MAX_SIZE);
1268 if (!dss->ring_req) {
1269 ha_alert("memory allocation error initializing the ring for dns tcp server '%s'.\n", srv->id);
1270 goto out;
1271 }
1272 /* Create the task associated to the resolver target handling conns */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02001273 if ((dss->task_req = task_new_anywhere()) == NULL) {
Emeric Brunfd647d52021-02-12 20:03:38 +01001274 ha_alert("memory allocation error initializing the ring for dns tcp server '%s'.\n", srv->id);
1275 goto out;
1276 }
1277
1278 /* Update task's parameters */
1279 dss->task_req->process = dns_process_req;
1280 dss->task_req->context = ns;
1281
1282 /* attach the task as reader */
1283 if (!ring_attach(dss->ring_req)) {
1284 /* mark server attached to the ring */
1285 ha_alert("server '%s': too many watchers for ring. this should never happen.\n", srv->id);
1286 goto out;
1287 }
1288
1289 /* Create the task associated to the resolver target handling conns */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02001290 if ((dss->task_rsp = task_new_anywhere()) == NULL) {
Emeric Brunfd647d52021-02-12 20:03:38 +01001291 ha_alert("memory allocation error initializing the ring for dns tcp server '%s'.\n", srv->id);
1292 goto out;
1293 }
1294
1295 /* Update task's parameters */
1296 dss->task_rsp->process = dns_process_rsp;
1297 dss->task_rsp->context = ns;
1298
1299 /* Create the task associated to the resolver target handling conns */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02001300 if ((dss->task_idle = task_new_anywhere()) == NULL) {
Emeric Brunfd647d52021-02-12 20:03:38 +01001301 ha_alert("memory allocation error initializing the ring for dns tcp server '%s'.\n", srv->id);
1302 goto out;
1303 }
1304
1305 /* Update task's parameters */
1306 dss->task_idle->process = dns_process_idle_exp;
1307 dss->task_idle->context = dss;
1308 dss->task_idle->expire = tick_add(now_ms, 5000);
1309
Ilya Shipitsin0de36ad2021-02-20 00:23:36 +05001310 /* let start the task to free idle conns immediately */
Emeric Brunfd647d52021-02-12 20:03:38 +01001311 task_queue(dss->task_idle);
1312
1313 LIST_INIT(&dss->free_sess);
1314 LIST_INIT(&dss->idle_sess);
1315 LIST_INIT(&dss->wait_sess);
1316 HA_SPIN_INIT(&dss->lock);
1317 ns->stream = dss;
1318 return 0;
1319out:
1320 if (dss && dss->task_rsp)
1321 task_destroy(dss->task_rsp);
1322 if (dss && dss->task_req)
1323 task_destroy(dss->task_req);
1324 if (dss && dss->ring_req)
1325 ring_free(dss->ring_req);
1326
1327 free(dss);
Emeric Brunc9437992021-02-12 19:42:55 +01001328 return -1;
Christopher Faulet67957bd2017-09-27 11:00:59 +02001329}
1330
Emeric Brunc9437992021-02-12 19:42:55 +01001331int init_dns_buffers()
Baptiste Assmann325137d2015-04-13 23:40:55 +02001332{
Emeric Brunc9437992021-02-12 19:42:55 +01001333 dns_msg_trash = malloc(DNS_TCP_MSG_MAX_SIZE);
1334 if (!dns_msg_trash)
1335 return 0;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001336
Emeric Brunc9437992021-02-12 19:42:55 +01001337 return 1;
1338}
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001339
Emeric Brunc9437992021-02-12 19:42:55 +01001340void deinit_dns_buffers()
1341{
Willy Tarreau61cfdf42021-02-20 10:46:51 +01001342 ha_free(&dns_msg_trash);
Emeric Brunc9437992021-02-12 19:42:55 +01001343}
Emeric Brund26a6232021-01-04 13:32:20 +01001344
1345REGISTER_PER_THREAD_ALLOC(init_dns_buffers);
1346REGISTER_PER_THREAD_FREE(deinit_dns_buffers);