blob: 352e88c9aa05411d4c1a00ab6bdf2084feae476a [file] [log] [blame]
Baptiste Assmann325137d2015-04-13 23:40:55 +02001/*
2 * Name server resolution
3 *
Emeric Brunc9437992021-02-12 19:42:55 +01004 * Copyright 2020 Haproxy Technologies
Baptiste Assmann325137d2015-04-13 23:40:55 +02005 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
13#include <errno.h>
14#include <fcntl.h>
15#include <stdio.h>
16#include <stdlib.h>
17#include <string.h>
18#include <unistd.h>
19
20#include <sys/types.h>
21
Willy Tarreau122eba92020-06-04 10:15:32 +020022#include <haproxy/action.h>
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020023#include <haproxy/api.h>
Willy Tarreau6be78492020-06-05 00:00:29 +020024#include <haproxy/cfgparse.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020025#include <haproxy/channel.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020026#include <haproxy/check.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020027#include <haproxy/cli.h>
Willy Tarreau7c18b542020-06-11 09:23:02 +020028#include <haproxy/dgram.h>
Willy Tarreaueb92deb2020-06-04 10:53:16 +020029#include <haproxy/dns.h>
Willy Tarreau8d366972020-05-27 16:10:29 +020030#include <haproxy/errors.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020031#include <haproxy/fd.h>
Willy Tarreauaeed4a82020-06-04 22:01:04 +020032#include <haproxy/log.h>
Emeric Brund26a6232021-01-04 13:32:20 +010033#include <haproxy/ring.h>
Emeric Brunfd647d52021-02-12 20:03:38 +010034#include <haproxy/stream.h>
35#include <haproxy/stream_interface.h>
Baptiste Assmann325137d2015-04-13 23:40:55 +020036
Emeric Brund26a6232021-01-04 13:32:20 +010037static THREAD_LOCAL char *dns_msg_trash;
Baptiste Assmann325137d2015-04-13 23:40:55 +020038
Emeric Brunfd647d52021-02-12 20:03:38 +010039DECLARE_STATIC_POOL(dns_session_pool, "dns_session", sizeof(struct dns_session));
40DECLARE_STATIC_POOL(dns_query_pool, "dns_query", sizeof(struct dns_query));
41DECLARE_STATIC_POOL(dns_msg_buf, "dns_msg_buf", DNS_TCP_MSG_RING_MAX_SIZE);
42
Christopher Faulet67957bd2017-09-27 11:00:59 +020043/* Opens an UDP socket on the namesaver's IP/Port, if required. Returns 0 on
44 * success, -1 otherwise.
Baptiste Assmann325137d2015-04-13 23:40:55 +020045 */
Emeric Brund26a6232021-01-04 13:32:20 +010046static int dns_connect_nameserver(struct dns_nameserver *ns)
Baptiste Assmann325137d2015-04-13 23:40:55 +020047{
Emeric Brund26a6232021-01-04 13:32:20 +010048 if (ns->dgram) {
49 struct dgram_conn *dgram = &ns->dgram->conn;
50 int fd;
Baptiste Assmann325137d2015-04-13 23:40:55 +020051
Emeric Brund26a6232021-01-04 13:32:20 +010052 /* Already connected */
53 if (dgram->t.sock.fd != -1)
54 return 0;
Baptiste Assmann325137d2015-04-13 23:40:55 +020055
Emeric Brund26a6232021-01-04 13:32:20 +010056 /* Create an UDP socket and connect it on the nameserver's IP/Port */
57 if ((fd = socket(dgram->addr.to.ss_family, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
58 send_log(NULL, LOG_WARNING,
Emeric Brunc9437992021-02-12 19:42:55 +010059 "DNS : section '%s': can't create socket for nameserver '%s'.\n",
Emeric Brund26a6232021-01-04 13:32:20 +010060 ns->counters->pid, ns->id);
61 return -1;
62 }
63 if (connect(fd, (struct sockaddr*)&dgram->addr.to, get_addr_len(&dgram->addr.to)) == -1) {
64 send_log(NULL, LOG_WARNING,
Emeric Brunc9437992021-02-12 19:42:55 +010065 "DNS : section '%s': can't connect socket for nameserver '%s'.\n",
Emeric Brund26a6232021-01-04 13:32:20 +010066 ns->counters->id, ns->id);
Emeric Brunc9437992021-02-12 19:42:55 +010067 close(fd);
Emeric Brund26a6232021-01-04 13:32:20 +010068 return -1;
69 }
Baptiste Assmann325137d2015-04-13 23:40:55 +020070
Emeric Brund26a6232021-01-04 13:32:20 +010071 /* Make the socket non blocking */
72 fcntl(fd, F_SETFL, O_NONBLOCK);
Olivier Houcharda8c6db82017-07-06 18:46:47 +020073
Emeric Brund26a6232021-01-04 13:32:20 +010074 /* Add the fd in the fd list and update its parameters */
75 dgram->t.sock.fd = fd;
76 fd_insert(fd, dgram, dgram_fd_handler, MAX_THREADS_MASK);
77 fd_want_recv(fd);
Emeric Brunc9437992021-02-12 19:42:55 +010078 }
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) {
103 if (errno == EAGAIN) {
104 struct ist myist;
105
106 myist.ptr = buf;
107 myist.len = len;
108 ret = ring_write(ns->dgram->ring_req, DNS_TCP_MSG_MAX_SIZE, NULL, 0, &myist, 1);
109 if (!ret) {
110 ns->counters->snd_error++;
111 return -1;
112 }
113 fd_cant_send(fd);
114 return ret;
115 }
116 ns->counters->snd_error++;
117 fd_delete(fd);
118 close(fd);
119 dgram->t.sock.fd = -1;
120 return -1;
121 }
122 ns->counters->sent++;
123 }
Emeric Brunfd647d52021-02-12 20:03:38 +0100124 else if (ns->stream) {
125 struct ist myist;
126
127 myist.ptr = buf;
128 myist.len = len;
129 ret = ring_write(ns->stream->ring_req, DNS_TCP_MSG_MAX_SIZE, NULL, 0, &myist, 1);
130 if (!ret) {
131 ns->counters->snd_error++;
132 return -1;
133 }
134 task_wakeup(ns->stream->task_req, TASK_WOKEN_MSG);
135 return ret;
136 }
Emeric Brund26a6232021-01-04 13:32:20 +0100137
138 return ret;
139}
140
Emeric Brunfd647d52021-02-12 20:03:38 +0100141void dns_session_free(struct dns_session *);
142
Emeric Brund26a6232021-01-04 13:32:20 +0100143/* Receives a dns message
144 * Returns message length
145 * 0 is returned if no more message available
146 * -1 in error case
147 */
148ssize_t dns_recv_nameserver(struct dns_nameserver *ns, void *data, size_t size)
149{
150 ssize_t ret = -1;
151
152 if (ns->dgram) {
153 struct dgram_conn *dgram = &ns->dgram->conn;
154 int fd = dgram->t.sock.fd;
155
156 if (fd == -1)
157 return -1;
158
159 if ((ret = recv(fd, data, size, 0)) < 0) {
160 if (errno == EAGAIN) {
161 fd_cant_recv(fd);
162 return 0;
163 }
164 fd_delete(fd);
165 close(fd);
166 dgram->t.sock.fd = -1;
167 return -1;
168 }
169 }
Emeric Brunfd647d52021-02-12 20:03:38 +0100170 else if (ns->stream) {
171 struct dns_stream_server *dss = ns->stream;
172 struct dns_session *ds;
173
174 HA_SPIN_LOCK(DNS_LOCK, &dss->lock);
175
176 if (!LIST_ISEMPTY(&dss->wait_sess)) {
177 ds = LIST_NEXT(&dss->wait_sess, struct dns_session *, waiter);
178 fprintf(stderr, "ds: %p\n", ds);
179 ret = ds->rx_msg.len < size ? ds->rx_msg.len : size;
180 memcpy(data, ds->rx_msg.area, ret);
181
182 ds->rx_msg.len = 0;
183
184 /* This barrier is here to ensure that all data is
185 * stored if the appctx detect the elem is out of the list */
186 __ha_barrier_store();
187
188 LIST_DEL_INIT(&ds->waiter);
189
190 if (ds->appctx) {
191 /* This second barrier is here to ensure that
192 * the waked up appctx won't miss that the
193 * elem is removed from the list */
194 __ha_barrier_store();
195
196 /* awake appctx beacause it may have other
197 * message to receive
198 */
199 appctx_wakeup(ds->appctx);
200
201 /* dns_session could already be into free_sess list
202 * so we firstly remove it */
203 LIST_DEL_INIT(&ds->list);
204
205 /* decrease nb_queries to free a slot for a new query on that sess */
206 ds->nb_queries--;
207 if (ds->nb_queries) {
208 /* it remains pipelined unanswered request
209 * into this session but we just decrease
210 * the counter so the session
211 * can not be full of pipelined requests
212 * so we can add if to free_sess list
213 * to receive a new request
214 */
215 LIST_ADD(&ds->dss->free_sess, &ds->list);
216 }
217 else {
218 /* there is no more pipelined requests
219 * into this session, so we move it
220 * to idle_sess list */
221 LIST_ADD(&ds->dss->idle_sess, &ds->list);
222
223 /* update the counter of idle sessions */
224 ds->dss->idle_conns++;
225
226 /* Note: this is useless there to update
227 * the max_active_conns since we increase
228 * the idle count */
229 }
230 }
231 else {
232 /* there is no more appctx for this session
233 * it means it is ready to die
234 */
235 dns_session_free(ds);
236 }
237
238
239 }
240
241 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
242 }
Emeric Brund26a6232021-01-04 13:32:20 +0100243
244 return ret;
245}
246
247static void dns_resolve_recv(struct dgram_conn *dgram)
248{
249 struct dns_nameserver *ns;
250 int fd;
251
252 fd = dgram->t.sock.fd;
253
254 /* check if ready for reading */
255 if (!fd_recv_ready(fd))
256 return;
257
258 /* no need to go further if we can't retrieve the nameserver */
259 if ((ns = dgram->owner) == NULL) {
260 _HA_ATOMIC_AND(&fdtab[fd].ev, ~(FD_POLL_HUP|FD_POLL_ERR));
261 fd_stop_recv(fd);
262 return;
263 }
264
265 ns->process_responses(ns);
266}
267
268/* Called when a dns network socket is ready to send data */
269static void dns_resolve_send(struct dgram_conn *dgram)
270{
271 int fd;
272 struct dns_nameserver *ns;
273 struct ring *ring;
274 struct buffer *buf;
275 uint64_t msg_len;
276 size_t len, cnt, ofs;
277
278 fd = dgram->t.sock.fd;
279
280 /* check if ready for sending */
281 if (!fd_send_ready(fd))
282 return;
283
284 /* no need to go further if we can't retrieve the nameserver */
285 if ((ns = dgram->owner) == NULL) {
286 _HA_ATOMIC_AND(&fdtab[fd].ev, ~(FD_POLL_HUP|FD_POLL_ERR));
287 fd_stop_send(fd);
288 return;
289 }
290
291 ring = ns->dgram->ring_req;
292 buf = &ring->buf;
293
294 HA_RWLOCK_RDLOCK(DNS_LOCK, &ring->lock);
295 ofs = ns->dgram->ofs_req;
296
297 /* explanation for the initialization below: it would be better to do
298 * this in the parsing function but this would occasionally result in
299 * dropped events because we'd take a reference on the oldest message
300 * and keep it while being scheduled. Thus instead let's take it the
301 * first time we enter here so that we have a chance to pass many
302 * existing messages before grabbing a reference to a location. This
303 * value cannot be produced after initialization.
304 */
305 if (unlikely(ofs == ~0)) {
306 ofs = 0;
307 HA_ATOMIC_ADD(b_peek(buf, ofs), 1);
308 ofs += ring->ofs;
309 }
310
311 /* we were already there, adjust the offset to be relative to
312 * the buffer's head and remove us from the counter.
313 */
314 ofs -= ring->ofs;
315 BUG_ON(ofs >= buf->size);
316 HA_ATOMIC_SUB(b_peek(buf, ofs), 1);
317
318 while (ofs + 1 < b_data(buf)) {
319 int ret;
320
321 cnt = 1;
322 len = b_peek_varint(buf, ofs + cnt, &msg_len);
323 if (!len)
324 break;
325 cnt += len;
326 BUG_ON(msg_len + ofs + cnt + 1 > b_data(buf));
327 if (unlikely(msg_len > DNS_TCP_MSG_MAX_SIZE)) {
328 /* too large a message to ever fit, let's skip it */
329 ofs += cnt + msg_len;
330 continue;
331 }
332
333 len = b_getblk(buf, dns_msg_trash, msg_len, ofs + cnt);
334
335 ret = send(fd, dns_msg_trash, len, 0);
336 if (ret < 0) {
337 if (errno == EAGAIN) {
338 fd_cant_send(fd);
339 goto out;
340 }
341 ns->counters->snd_error++;
342 fd_delete(fd);
343 close(fd);
344 fd = dgram->t.sock.fd = -1;
345 goto out;
346 }
347 ns->counters->sent++;
348
349 ofs += cnt + len;
350 }
351
352 /* we don't want/need to be waked up any more for sending
353 * because all ring content is sent */
354 fd_stop_send(fd);
355
356out:
357
358 HA_ATOMIC_ADD(b_peek(buf, ofs), 1);
359 ofs += ring->ofs;
360 ns->dgram->ofs_req = ofs;
361 HA_RWLOCK_RDUNLOCK(DNS_LOCK, &ring->lock);
362
363}
364
Emeric Brunc9437992021-02-12 19:42:55 +0100365/* proto_udp callback functions for a DNS resolution */
366struct dgram_data_cb dns_dgram_cb = {
367 .recv = dns_resolve_recv,
368 .send = dns_resolve_send,
369};
Baptiste Assmann325137d2015-04-13 23:40:55 +0200370
Emeric Brunc9437992021-02-12 19:42:55 +0100371int dns_dgram_init(struct dns_nameserver *ns, struct sockaddr_storage *sk)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200372{
Emeric Brunc9437992021-02-12 19:42:55 +0100373 struct dns_dgram_server *dgram;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200374
Emeric Brunc9437992021-02-12 19:42:55 +0100375 if ((dgram = calloc(1, sizeof(*dgram))) == NULL)
Christopher Faulet67957bd2017-09-27 11:00:59 +0200376 return -1;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200377
Emeric Brunc9437992021-02-12 19:42:55 +0100378 /* Leave dgram partially initialized, no FD attached for
379 * now. */
380 dgram->conn.owner = ns;
381 dgram->conn.data = &dns_dgram_cb;
382 dgram->conn.t.sock.fd = -1;
383 dgram->conn.addr.to = *sk;
384 ns->dgram = dgram;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200385
Emeric Brunc9437992021-02-12 19:42:55 +0100386 dgram->ofs_req = ~0; /* init ring offset */
387 dgram->ring_req = ring_new(2*DNS_TCP_MSG_RING_MAX_SIZE);
388 if (!dgram->ring_req) {
389 ha_alert("memory allocation error initializing the ring for nameserver.\n");
390 goto out;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200391 }
392
Emeric Brunc9437992021-02-12 19:42:55 +0100393 /* attach the task as reader */
394 if (!ring_attach(dgram->ring_req)) {
395 /* mark server attached to the ring */
396 ha_alert("nameserver sets too many watchers > 255 on ring. This is a bug and should not happen.\n");
397 goto out;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200398 }
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200399 return 0;
Emeric Brunc9437992021-02-12 19:42:55 +0100400out:
401 if (dgram->ring_req)
402 ring_free(dgram->ring_req);
Christopher Fauletd6c6b5f2020-09-08 10:27:24 +0200403
Emeric Brunc9437992021-02-12 19:42:55 +0100404 free(dgram);
Olivier Houchard2ec2db92018-01-08 16:28:57 +0100405
Emeric Brunfd647d52021-02-12 20:03:38 +0100406 return -1;
407}
408
409/*
410 * IO Handler to handle message push to dns tcp server
411 */
412static void dns_session_io_handler(struct appctx *appctx)
413{
414 struct stream_interface *si = appctx->owner;
415 struct dns_session *ds = appctx->ctx.sft.ptr;
416 struct ring *ring = &ds->ring;
417 struct buffer *buf = &ring->buf;
418 uint64_t msg_len;
419 int available_room;
420 size_t len, cnt, ofs;
421 int ret = 0;
422
423 /* if stopping was requested, close immediately */
424 if (unlikely(stopping))
425 goto close;
426
427 /* we want to be sure to not miss that we have been awaked for a shutdown */
428 __ha_barrier_load();
429
430 /* that means the connection was requested to shutdown
431 * for instance idle expire */
432 if (ds->shutdown)
433 goto close;
434
435 /* an error was detected */
436 if (unlikely(si_ic(si)->flags & (CF_WRITE_ERROR|CF_SHUTW)))
437 goto close;
438
439 /* con closed by server side, we will skip data write and drain data from channel */
440 if ((si_oc(si)->flags & CF_SHUTW)) {
441 goto read;
442 }
443
444 /* if the connection is not established, inform the stream that we want
445 * to be notified whenever the connection completes.
446 */
447 if (si_opposite(si)->state < SI_ST_EST) {
448 si_cant_get(si);
449 si_rx_conn_blk(si);
450 si_rx_endp_more(si);
451 return;
452 }
453
454
455 ofs = ds->ofs;
456
457 HA_RWLOCK_WRLOCK(DNS_LOCK, &ring->lock);
458 LIST_DEL_INIT(&appctx->wait_entry);
459 HA_RWLOCK_WRUNLOCK(DNS_LOCK, &ring->lock);
460
461 HA_RWLOCK_RDLOCK(DNS_LOCK, &ring->lock);
462
463 /* explanation for the initialization below: it would be better to do
464 * this in the parsing function but this would occasionally result in
465 * dropped events because we'd take a reference on the oldest message
466 * and keep it while being scheduled. Thus instead let's take it the
467 * first time we enter here so that we have a chance to pass many
468 * existing messages before grabbing a reference to a location. This
469 * value cannot be produced after initialization.
470 */
471 if (unlikely(ofs == ~0)) {
472 ofs = 0;
473
474 HA_ATOMIC_ADD(b_peek(buf, ofs), 1);
475 ofs += ring->ofs;
476 }
477
478 /* in this loop, ofs always points to the counter byte that precedes
479 * the message so that we can take our reference there if we have to
480 * stop before the end (ret=0).
481 */
482 if (si_opposite(si)->state == SI_ST_EST) {
483 /* we were already there, adjust the offset to be relative to
484 * the buffer's head and remove us from the counter.
485 */
486 ofs -= ring->ofs;
487 BUG_ON(ofs >= buf->size);
488 HA_ATOMIC_SUB(b_peek(buf, ofs), 1);
489
490 ret = 1;
491 while (ofs + 1 < b_data(buf)) {
492 struct dns_query *query;
493 uint16_t original_qid;
494 uint16_t new_qid;
495
496 cnt = 1;
497 len = b_peek_varint(buf, ofs + cnt, &msg_len);
498 if (!len)
499 break;
500 cnt += len;
501 BUG_ON(msg_len + ofs + cnt + 1 > b_data(buf));
502
503 /* retrieve available room on output channel */
504 available_room = channel_recv_max(si_ic(si));
505
506 /* tx_msg_offset null means we are at the start of a new message */
507 if (!ds->tx_msg_offset) {
508 uint16_t slen;
509
510 /* check if there is enough room to put message len and query id */
511 if (available_room < sizeof(slen) + sizeof(new_qid)) {
512 si_rx_room_blk(si);
513 ret = 0;
514 break;
515 }
516
517 /* put msg len into then channel */
518 slen = (uint16_t)msg_len;
519 slen = htons(slen);
520 ci_putblk(si_ic(si), (char *)&slen, sizeof(slen));
521 available_room -= sizeof(slen);
522
523 /* backup original query id */
524 len = b_getblk(buf, (char *)&original_qid, sizeof(original_qid), ofs + cnt);
525
526 /* generates new query id */
527 new_qid = ++ds->query_counter;
528 new_qid = htons(new_qid);
529
530 /* put new query id into the channel */
531 ci_putblk(si_ic(si), (char *)&new_qid, sizeof(new_qid));
532 available_room -= sizeof(new_qid);
533
534 /* keep query id mapping */
535
536 query = pool_alloc(dns_query_pool);
537 if (query) {
538 query->qid.key = new_qid;
539 query->original_qid = original_qid;
540 query->expire = tick_add(now_ms, 5000);
541 LIST_INIT(&query->list);
542 if (LIST_ISEMPTY(&ds->queries)) {
543 /* enable task to handle expire */
544 ds->task_exp->expire = query->expire;
545 /* ensure this will be executed by the same
546 * thread than ds_session_release
547 * to ensure session_release is free
548 * to destroy the task */
549 task_queue(ds->task_exp);
550 }
551 LIST_ADDQ(&ds->queries, &query->list);
552 eb32_insert(&ds->query_ids, &query->qid);
553 ds->onfly_queries++;
554 }
555
556 /* update the tx_offset to handle output in 16k streams */
557 ds->tx_msg_offset = sizeof(original_qid);
558
559 }
560
561 /* check if it remains available room on output chan */
562 if (unlikely(!available_room)) {
563 si_rx_room_blk(si);
564 ret = 0;
565 break;
566 }
567
568 chunk_reset(&trash);
569 if ((msg_len - ds->tx_msg_offset) > available_room) {
570 /* remaining msg data is too large to be written in output channel at one time */
571
572 len = b_getblk(buf, trash.area, available_room, ofs + cnt + ds->tx_msg_offset);
573
574 /* update offset to complete mesg forwarding later */
575 ds->tx_msg_offset += len;
576 }
577 else {
578 /* remaining msg data can be written in output channel at one time */
579 len = b_getblk(buf, trash.area, msg_len - ds->tx_msg_offset, ofs + cnt + ds->tx_msg_offset);
580
581 /* reset tx_msg_offset to mark forward fully processed */
582 ds->tx_msg_offset = 0;
583 }
584 trash.data += len;
585
586 ci_putchk(si_ic(si), &trash);
587
588 if (ds->tx_msg_offset) {
589 /* msg was not fully processed, we must be awake to drain pending data */
590
591 si_rx_room_blk(si);
592 ret = 0;
593 break;
594 }
595 /* switch to next message */
596 ofs += cnt + msg_len;
597 }
598
599 HA_ATOMIC_ADD(b_peek(buf, ofs), 1);
600 ofs += ring->ofs;
601 ds->ofs = ofs;
602 }
603 HA_RWLOCK_RDUNLOCK(DNS_LOCK, &ring->lock);
604
605 if (ret) {
606 /* let's be woken up once new request to write arrived */
607 HA_RWLOCK_WRLOCK(DNS_LOCK, &ring->lock);
608 LIST_ADDQ(&ring->waiters, &appctx->wait_entry);
609 HA_RWLOCK_WRUNLOCK(DNS_LOCK, &ring->lock);
610 si_rx_endp_done(si);
611 }
612
613read:
614
615 /* if session is not a waiter it means there is no commited
616 * message into rx_buf and we are free to use it
617 * Note: we need a load barrier here to not miss the
618 * delete from the list
619 */
620 __ha_barrier_load();
621 if (!LIST_ADDED(&ds->waiter)) {
622 while (1) {
623 uint16_t query_id;
624 struct eb32_node *eb;
625 struct dns_query *query;
626
627 if (!ds->rx_msg.len) {
628 /* next message len is not fully available into the channel */
629 if (co_data(si_oc(si)) < 2)
630 break;
631
632 /* retrieve message len */
633 co_getblk(si_oc(si), (char *)&msg_len, 2, 0);
634
635 /* mark as consumed */
636 co_skip(si_oc(si), 2);
637
638 /* store message len */
639 ds->rx_msg.len = ntohs(msg_len);
640 }
641
642 if (!co_data(si_oc(si))) {
643 /* we need more data but nothing is available */
644 break;
645 }
646
647 if (co_data(si_oc(si)) + ds->rx_msg.offset < ds->rx_msg.len) {
648 /* message only partially available */
649
650 /* read available data */
651 co_getblk(si_oc(si), ds->rx_msg.area + ds->rx_msg.offset, co_data(si_oc(si)), 0);
652
653 /* update message offset */
654 ds->rx_msg.offset += co_data(si_oc(si));
655
656 /* consume all pending data from the channel */
657 co_skip(si_oc(si), co_data(si_oc(si)));
658
659 /* we need to wait for more data */
660 break;
661 }
662
663 /* enougth data is available into the channel to read the message until the end */
664
665 /* read from the channel until the end of the message */
666 co_getblk(si_oc(si), ds->rx_msg.area + ds->rx_msg.offset, ds->rx_msg.len - ds->rx_msg.offset, 0);
667
668 /* consume all data until the end of the message from the channel */
669 co_skip(si_oc(si), ds->rx_msg.len - ds->rx_msg.offset);
670
671 /* reset reader offset to 0 for next message reand */
672 ds->rx_msg.offset = 0;
673
674 /* try remap query id to original */
675 memcpy(&query_id, ds->rx_msg.area, sizeof(query_id));
676 eb = eb32_lookup(&ds->query_ids, query_id);
677 if (!eb) {
678 /* query id not found means we have an unknown corresponding
679 * request, perhaps server's bug or or the query reached
680 * timeout
681 */
682 ds->rx_msg.len = 0;
683 continue;
684 }
685
686 /* re-map the original query id set by the requester */
687 query = eb32_entry(eb, struct dns_query, qid);
688 memcpy(ds->rx_msg.area, &query->original_qid, sizeof(query->original_qid));
689
690 /* remove query ids mapping from pending queries list/tree */
691 eb32_delete(&query->qid);
692 LIST_DEL(&query->list);
693 pool_free(dns_query_pool, query);
694 ds->onfly_queries--;
695
696 /* lock the dns_stream_server containing lists heads */
697 HA_SPIN_LOCK(DNS_LOCK, &ds->dss->lock);
698
699 /* the dns_session is also added in queue of the
700 * wait_sess list where the task processing
701 * response will pop available responses
702 */
703 LIST_ADDQ(&ds->dss->wait_sess, &ds->waiter);
704
705 /* lock the dns_stream_server containing lists heads */
706 HA_SPIN_UNLOCK(DNS_LOCK, &ds->dss->lock);
707
708 /* awake the task processing the responses */
709 task_wakeup(ds->dss->task_rsp, TASK_WOKEN_INIT);
710
711 break;
712 }
713
714 if (!LIST_ADDED(&ds->waiter)) {
715 /* there is no more pending data to read and the con was closed by the server side */
716 if (!co_data(si_oc(si)) && (si_oc(si)->flags & CF_SHUTW)) {
717 goto close;
718 }
719 }
720
721 }
722
723
724 return;
725close:
726 si_shutw(si);
727 si_shutr(si);
728 si_ic(si)->flags |= CF_READ_NULL;
729}
730
731void dns_queries_flush(struct dns_session *ds)
732{
733 struct dns_query *query, *queryb;
734
735 list_for_each_entry_safe(query, queryb, &ds->queries, list) {
736 eb32_delete(&query->qid);
737 LIST_DEL(&query->list);
738 pool_free(dns_query_pool, query);
739 }
740}
741
742void dns_session_free(struct dns_session *ds)
743{
744 if (ds->rx_msg.area)
745 pool_free(dns_msg_buf, ds->rx_msg.area);
746 if (ds->tx_ring_area)
747 pool_free(dns_msg_buf, ds->tx_ring_area);
748 if (ds->task_exp)
749 task_destroy(ds->task_exp);
750
751 dns_queries_flush(ds);
752
753 ds->dss->cur_conns--;
754 /* Note: this is useless to update
755 * max_active_conns here because
756 * we decrease the value
757 */
758 pool_free(dns_session_pool, ds);
759}
760
761static struct appctx *dns_session_create(struct dns_session *ds);
762
763/*
764 * Function to release a DNS tcp session
765 */
766static void dns_session_release(struct appctx *appctx)
767{
768 struct dns_session *ds = appctx->ctx.sft.ptr;
769 struct dns_stream_server *dss;
770
771 if (!ds)
772 return;
773
774 dss = ds->dss;
775
776 HA_SPIN_LOCK(DNS_LOCK, &dss->lock);
777 LIST_DEL_INIT(&ds->list);
778
779 if (stopping) {
780 dns_session_free(ds);
781 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
782 return;
783 }
784
785 if (!ds->nb_queries) {
786 /* this is an idle session */
787 /* Note: this is useless to update max_active_sess
788 * here because we decrease idle_conns but
789 * dns_session_free decrease curconns
790 */
791
792 ds->dss->idle_conns--;
793 dns_session_free(ds);
794 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
795 return;
796 }
797
798 if (ds->onfly_queries == ds->nb_queries) {
799 /* the session can be released because
800 * it means that all queries AND
801 * responses are in fly */
802 dns_session_free(ds);
803 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
804 return;
805 }
806
807 /* We do not call ring_appctx_detach here
808 * because we want to keep readers counters
809 * to retry a con with a different appctx*/
810 HA_RWLOCK_WRLOCK(DNS_LOCK, &ds->ring.lock);
811 LIST_DEL_INIT(&appctx->wait_entry);
812 HA_RWLOCK_WRUNLOCK(DNS_LOCK, &ds->ring.lock);
813
814 /* if there is no pending complete response
815 * message, ensure to reset
816 * message offsets if the session
817 * was closed with an incomplete pending response
818 */
819 if (!LIST_ADDED(&ds->waiter))
820 ds->rx_msg.len = ds->rx_msg.offset = 0;
821
822 /* we flush pending sent queries because we never
823 * have responses
824 */
825 ds->nb_queries -= ds->onfly_queries;
826 dns_queries_flush(ds);
827
828 /* reset offset to be sure to start from message start */
829 ds->tx_msg_offset = 0;
830
831 /* here the ofs and the attached counter
832 * are kept unchanged
833 */
834
835 /* Create a new appctx, We hope we can
836 * create from the release callback! */
837 ds->appctx = dns_session_create(ds);
838 if (!ds->appctx) {
839 dns_session_free(ds);
840 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
841 return;
842 }
843
844 if (ds->nb_queries < DNS_STREAM_MAX_PIPELINED_REQ)
845 LIST_ADD(&ds->dss->free_sess, &ds->list);
846
847 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
848}
849
850/* DNS tcp session applet */
851static struct applet dns_session_applet = {
852 .obj_type = OBJ_TYPE_APPLET,
853 .name = "<STRMDNS>", /* used for logging */
854 .fct = dns_session_io_handler,
855 .release = dns_session_release,
856};
857
858/*
859 * Function used to create an appctx for a DNS session
860 */
861static struct appctx *dns_session_create(struct dns_session *ds)
862{
863 struct appctx *appctx;
864 struct session *sess;
865 struct stream *s;
866 struct applet *applet = &dns_session_applet;
867
868 appctx = appctx_new(applet, tid_bit);
869 if (!appctx)
870 goto out_close;
871
872 appctx->ctx.sft.ptr = (void *)ds;
873
874 sess = session_new(ds->dss->srv->proxy, NULL, &appctx->obj_type);
875 if (!sess) {
876 ha_alert("out of memory in peer_session_create().\n");
877 goto out_free_appctx;
878 }
879
880 if ((s = stream_new(sess, &appctx->obj_type, &BUF_NULL)) == NULL) {
881 ha_alert("Failed to initialize stream in peer_session_create().\n");
882 goto out_free_sess;
883 }
884
885
886 s->target = &ds->dss->srv->obj_type;
887 if (!sockaddr_alloc(&s->target_addr, &ds->dss->srv->addr, sizeof(ds->dss->srv->addr)))
888 goto out_free_strm;
889 s->flags = SF_ASSIGNED|SF_ADDR_SET;
890 s->si[1].flags |= SI_FL_NOLINGER;
891
892 s->do_log = NULL;
893 s->uniq_id = 0;
894
895 s->res.flags |= CF_READ_DONTWAIT;
896 /* for rto and rex to eternity to not expire on idle recv:
897 * We are using a syslog server.
898 */
899 s->res.rto = TICK_ETERNITY;
900 s->res.rex = TICK_ETERNITY;
901 ds->appctx = appctx;
902 task_wakeup(s->task, TASK_WOKEN_INIT);
903 return appctx;
904
905 /* Error unrolling */
906 out_free_strm:
907 LIST_DEL(&s->list);
908 pool_free(pool_head_stream, s);
909 out_free_sess:
910 session_free(sess);
911 out_free_appctx:
912 appctx_free(appctx);
913 out_close:
914 return NULL;
915}
916
917/* Task processing expiration of unresponded queries, this one is supposed
918 * to be stuck on the same thread than the appctx handler
919 */
920static struct task *dns_process_query_exp(struct task *t, void *context, unsigned short state)
921{
922 struct dns_session *ds = (struct dns_session *)context;
923 struct dns_query *query, *queryb;
924
925 t->expire = TICK_ETERNITY;
926
927 list_for_each_entry_safe(query, queryb, &ds->queries, list) {
928 if (tick_is_expired(query->expire, now_ms)) {
929 eb32_delete(&query->qid);
930 LIST_DEL(&query->list);
931 pool_free(dns_query_pool, query);
932 ds->onfly_queries--;
933 }
934 else {
935 t->expire = query->expire;
936 break;
937 }
938 }
939
940 return t;
941}
942
943/* Task processing expiration of idle sessions */
944static struct task *dns_process_idle_exp(struct task *t, void *context, unsigned short state)
945{
946 struct dns_stream_server *dss = (struct dns_stream_server *)context;
947 struct dns_session *ds, *dsb;
948 int target = 0;
949 int cur_active_conns;
950
951 HA_SPIN_LOCK(DNS_LOCK, &dss->lock);
952
953
954 cur_active_conns = dss->cur_conns - dss->idle_conns;
955 if (cur_active_conns > dss->max_active_conns)
956 dss->max_active_conns = cur_active_conns;
957
958 target = (dss->max_active_conns - cur_active_conns) / 2;
959 list_for_each_entry_safe(ds, dsb, &dss->idle_sess, list) {
960 if (!target)
961 break;
962
963 /* remove conn to pending list to ensure it won't be reused */
964 LIST_DEL_INIT(&ds->list);
965
966 /* force session shutdown */
967 ds->shutdown = 1;
968
969 /* to be sure that the appctx wont miss shutdown */
970 __ha_barrier_store();
971
972 /* wake appctx to perform the shutdown */
973 appctx_wakeup(ds->appctx);
974 }
975
976 /* reset max to current active conns */
977 dss->max_active_conns = cur_active_conns;
978
979 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
980
981 t->expire = tick_add(now_ms, 5000);
982
983 return t;
984}
985
986struct dns_session *dns_session_new(struct dns_stream_server *dss)
987{
988 struct dns_session *ds;
989
990 if (dss->maxconn && (dss->maxconn <= dss->cur_conns))
991 return NULL;
992
993 ds = pool_alloc(dns_session_pool);
994 if (!ds)
995 return NULL;
996
997 ds->ofs = ~0;
998 ds->dss = dss;
999 LIST_INIT(&ds->list);
1000 LIST_INIT(&ds->queries);
1001 LIST_INIT(&ds->waiter);
1002 ds->rx_msg.offset = ds->rx_msg.len = 0;
1003 ds->rx_msg.area = NULL;
1004 ds->tx_ring_area = NULL;
1005 ds->task_exp = NULL;
1006 ds->appctx = NULL;
1007 ds->shutdown = 0;
1008 ds->nb_queries = 0;
1009 ds->query_ids = EB_ROOT_UNIQUE;
1010 ds->rx_msg.area = pool_alloc(dns_msg_buf);
1011 if (!ds->rx_msg.area)
1012 goto error;
1013
1014 ds->tx_ring_area = pool_alloc(dns_msg_buf);
1015 if (!ds->tx_ring_area)
1016 goto error;
1017
1018 ring_init(&ds->ring, ds->tx_ring_area, DNS_TCP_MSG_RING_MAX_SIZE);
1019 ring_attach(&ds->ring);
1020
1021 if ((ds->task_exp = task_new(tid_bit)) == NULL)
1022 goto error;
1023
1024 ds->task_exp->process = dns_process_query_exp;
1025 ds->task_exp->context = ds;
1026
1027 ds->appctx = dns_session_create(ds);
1028 if (!ds->appctx)
1029 goto error;
1030
1031 dss->cur_conns++;
1032
1033 return ds;
1034
1035error:
1036 if (ds->task_exp)
1037 task_destroy(ds->task_exp);
1038 if (ds->rx_msg.area)
1039 pool_free(dns_msg_buf, ds->rx_msg.area);
1040 if (ds->tx_ring_area)
1041 pool_free(dns_msg_buf, ds->tx_ring_area);
1042
1043 pool_free(dns_session_pool, ds);
1044
1045 return NULL;
1046}
1047
1048/*
1049 * Task used to consume pending messages from nameserver ring
1050 * and forward them to dns_session ring.
1051 * Note: If no slot found a new dns_session is allocated
1052 */
1053static struct task *dns_process_req(struct task *t, void *context, unsigned short state)
1054{
1055 struct dns_nameserver *ns = (struct dns_nameserver *)context;
1056 struct dns_stream_server *dss = ns->stream;
1057 struct ring *ring = dss->ring_req;
1058 struct buffer *buf = &ring->buf;
1059 uint64_t msg_len;
1060 size_t len, cnt, ofs;
1061 struct dns_session *ds, *ads;
1062 HA_SPIN_LOCK(DNS_LOCK, &dss->lock);
1063
1064 ofs = dss->ofs_req;
1065
1066 HA_RWLOCK_RDLOCK(DNS_LOCK, &ring->lock);
1067
1068 /* explanation for the initialization below: it would be better to do
1069 * this in the parsing function but this would occasionally result in
1070 * dropped events because we'd take a reference on the oldest message
1071 * and keep it while being scheduled. Thus instead let's take it the
1072 * first time we enter here so that we have a chance to pass many
1073 * existing messages before grabbing a reference to a location. This
1074 * value cannot be produced after initialization.
1075 */
1076 if (unlikely(ofs == ~0)) {
1077 ofs = 0;
1078 HA_ATOMIC_ADD(b_peek(buf, ofs), 1);
1079 ofs += ring->ofs;
1080 }
1081
1082 /* we were already there, adjust the offset to be relative to
1083 * the buffer's head and remove us from the counter.
1084 */
1085 ofs -= ring->ofs;
1086 BUG_ON(ofs >= buf->size);
1087 HA_ATOMIC_SUB(b_peek(buf, ofs), 1);
1088
1089 while (ofs + 1 < b_data(buf)) {
1090 struct ist myist;
1091
1092 cnt = 1;
1093 len = b_peek_varint(buf, ofs + cnt, &msg_len);
1094 if (!len)
1095 break;
1096 cnt += len;
1097 BUG_ON(msg_len + ofs + cnt + 1 > b_data(buf));
1098 if (unlikely(msg_len > DNS_TCP_MSG_MAX_SIZE)) {
1099 /* too large a message to ever fit, let's skip it */
1100 ofs += cnt + msg_len;
1101 continue;
1102 }
1103
1104 len = b_getblk(buf, dns_msg_trash, msg_len, ofs + cnt);
1105
1106 myist.ptr = dns_msg_trash;
1107 myist.len = len;
1108
1109 ads = NULL;
1110 /* try to push request into activ sess with free slot */
1111 if (!LIST_ISEMPTY(&dss->free_sess)) {
1112 ds = LIST_NEXT(&dss->free_sess, struct dns_session *, list);
1113
1114 if (ring_write(&ds->ring, DNS_TCP_MSG_MAX_SIZE, NULL, 0, &myist, 1) > 0) {
1115 ds->nb_queries++;
1116 if (ds->nb_queries >= DNS_STREAM_MAX_PIPELINED_REQ)
1117 LIST_DEL_INIT(&ds->list);
1118 ads = ds;
1119 }
1120 else {
1121 /* it means we were unable to put a request in this slot,
1122 * it may be close to be full so we put it at the end
1123 * of free conn list */
1124 LIST_DEL_INIT(&ds->list);
1125 LIST_ADDQ(&dss->free_sess, &ds->list);
1126 }
1127 }
1128
1129 if (!ads) {
1130 /* try to push request into idle, this one should have enought free space */
1131 if (!LIST_ISEMPTY(&dss->idle_sess)) {
1132 ds = LIST_NEXT(&dss->idle_sess, struct dns_session *, list);
1133
1134 /* ring is empty so this ring_write should never fail */
1135 ring_write(&ds->ring, DNS_TCP_MSG_MAX_SIZE, NULL, 0, &myist, 1);
1136 ds->nb_queries++;
1137 LIST_DEL_INIT(&ds->list);
1138
1139 ds->dss->idle_conns--;
1140
1141 /* we may have to update the max_active_conns */
1142 if (ds->dss->max_active_conns < ds->dss->cur_conns - ds->dss->idle_conns)
1143 ds->dss->max_active_conns = ds->dss->cur_conns - ds->dss->idle_conns;
1144
1145 /* since we may unable to find a free list to handle
1146 * this request, this request may be large and fill
1147 * the ring buffer so we prefer to put at the end of free
1148 * list. */
1149 LIST_ADDQ(&dss->free_sess, &ds->list);
1150 ads = ds;
1151 }
1152 }
1153
1154 /* we didn't find a session avalaible with large enough room */
1155 if (!ads) {
1156 /* allocate a new session */
1157 ads = dns_session_new(dss);
1158 if (ads) {
1159 /* ring is empty so this ring_write should never fail */
1160 ring_write(&ads->ring, DNS_TCP_MSG_MAX_SIZE, NULL, 0, &myist, 1);
1161 ads->nb_queries++;
1162 LIST_ADD(&dss->free_sess, &ads->list);
1163 }
1164 else
1165 ns->counters->snd_error++;
1166 }
1167
1168 if (ads)
1169 ns->counters->sent++;
1170
1171 ofs += cnt + len;
1172 }
1173
1174 HA_ATOMIC_ADD(b_peek(buf, ofs), 1);
1175 ofs += ring->ofs;
1176 dss->ofs_req = ofs;
1177 HA_RWLOCK_RDUNLOCK(DNS_LOCK, &ring->lock);
1178
1179
1180 HA_SPIN_UNLOCK(DNS_LOCK, &dss->lock);
1181 return t;
1182}
1183
1184/*
1185 * Task used to consume response
1186 * Note: upper layer callback is called
1187 */
1188static struct task *dns_process_rsp(struct task *t, void *context, unsigned short state)
1189{
1190 struct dns_nameserver *ns = (struct dns_nameserver *)context;
1191
1192 ns->process_responses(ns);
1193
1194 return t;
1195}
1196
1197/* Function used to initialize an TCP nameserver */
1198int dns_stream_init(struct dns_nameserver *ns, struct server *srv)
1199{
1200 struct dns_stream_server *dss = NULL;
1201
1202 dss = calloc(1, sizeof(*dss));
1203 if (!dss) {
1204 ha_alert("memory allocation error initializing dns tcp server '%s'.\n", srv->id);
1205 goto out;
1206 }
1207
1208 dss->srv = srv;
1209 dss->maxconn = srv->maxconn;
1210
1211 dss->ofs_req = ~0; /* init ring offset */
1212 dss->ring_req = ring_new(2*DNS_TCP_MSG_RING_MAX_SIZE);
1213 if (!dss->ring_req) {
1214 ha_alert("memory allocation error initializing the ring for dns tcp server '%s'.\n", srv->id);
1215 goto out;
1216 }
1217 /* Create the task associated to the resolver target handling conns */
1218 if ((dss->task_req = task_new(MAX_THREADS_MASK)) == NULL) {
1219 ha_alert("memory allocation error initializing the ring for dns tcp server '%s'.\n", srv->id);
1220 goto out;
1221 }
1222
1223 /* Update task's parameters */
1224 dss->task_req->process = dns_process_req;
1225 dss->task_req->context = ns;
1226
1227 /* attach the task as reader */
1228 if (!ring_attach(dss->ring_req)) {
1229 /* mark server attached to the ring */
1230 ha_alert("server '%s': too many watchers for ring. this should never happen.\n", srv->id);
1231 goto out;
1232 }
1233
1234 /* Create the task associated to the resolver target handling conns */
1235 if ((dss->task_rsp = task_new(MAX_THREADS_MASK)) == NULL) {
1236 ha_alert("memory allocation error initializing the ring for dns tcp server '%s'.\n", srv->id);
1237 goto out;
1238 }
1239
1240 /* Update task's parameters */
1241 dss->task_rsp->process = dns_process_rsp;
1242 dss->task_rsp->context = ns;
1243
1244 /* Create the task associated to the resolver target handling conns */
1245 if ((dss->task_idle = task_new(MAX_THREADS_MASK)) == NULL) {
1246 ha_alert("memory allocation error initializing the ring for dns tcp server '%s'.\n", srv->id);
1247 goto out;
1248 }
1249
1250 /* Update task's parameters */
1251 dss->task_idle->process = dns_process_idle_exp;
1252 dss->task_idle->context = dss;
1253 dss->task_idle->expire = tick_add(now_ms, 5000);
1254
1255 /* let start the task to free idle conns immediatly */
1256 task_queue(dss->task_idle);
1257
1258 LIST_INIT(&dss->free_sess);
1259 LIST_INIT(&dss->idle_sess);
1260 LIST_INIT(&dss->wait_sess);
1261 HA_SPIN_INIT(&dss->lock);
1262 ns->stream = dss;
1263 return 0;
1264out:
1265 if (dss && dss->task_rsp)
1266 task_destroy(dss->task_rsp);
1267 if (dss && dss->task_req)
1268 task_destroy(dss->task_req);
1269 if (dss && dss->ring_req)
1270 ring_free(dss->ring_req);
1271
1272 free(dss);
Emeric Brunc9437992021-02-12 19:42:55 +01001273 return -1;
Christopher Faulet67957bd2017-09-27 11:00:59 +02001274}
1275
Emeric Brunc9437992021-02-12 19:42:55 +01001276int init_dns_buffers()
Baptiste Assmann325137d2015-04-13 23:40:55 +02001277{
Emeric Brunc9437992021-02-12 19:42:55 +01001278 dns_msg_trash = malloc(DNS_TCP_MSG_MAX_SIZE);
1279 if (!dns_msg_trash)
1280 return 0;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001281
Emeric Brunc9437992021-02-12 19:42:55 +01001282 return 1;
1283}
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001284
Emeric Brunc9437992021-02-12 19:42:55 +01001285void deinit_dns_buffers()
1286{
1287 free(dns_msg_trash);
1288 dns_msg_trash = NULL;
1289}
Emeric Brund26a6232021-01-04 13:32:20 +01001290
1291REGISTER_PER_THREAD_ALLOC(init_dns_buffers);
1292REGISTER_PER_THREAD_FREE(deinit_dns_buffers);