2017-03-03 11:14:41 +01:00
|
|
|
/*
|
|
|
|
* Copyright (C) 2017 Kaspar Schleiser <kaspar@schleiser.de>
|
|
|
|
*
|
|
|
|
* This file is subject to the terms and conditions of the GNU Lesser
|
|
|
|
* General Public License v2.1. See the file LICENSE in the top level
|
|
|
|
* directory for more details.
|
|
|
|
*/
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @ingroup net_sock_dns
|
|
|
|
* @{
|
|
|
|
* @file
|
|
|
|
* @brief sock DNS client implementation
|
|
|
|
* @author Kaspar Schleiser <kaspar@schleiser.de>
|
|
|
|
* @}
|
|
|
|
*/
|
|
|
|
|
2021-07-21 14:57:44 +02:00
|
|
|
#include <errno.h>
|
2017-03-03 11:14:41 +01:00
|
|
|
|
2019-01-09 22:14:08 +01:00
|
|
|
#include "net/dns.h"
|
2021-07-21 14:57:44 +02:00
|
|
|
#include "net/dns/msg.h"
|
2017-03-03 11:14:41 +01:00
|
|
|
#include "net/sock/udp.h"
|
|
|
|
#include "net/sock/dns.h"
|
|
|
|
|
|
|
|
/* min domain name length is 1, so minimum record length is 7 */
|
2021-07-21 14:57:44 +02:00
|
|
|
#define DNS_MIN_REPLY_LEN (unsigned)(sizeof(dns_hdr_t ) + 7)
|
2017-03-03 11:14:41 +01:00
|
|
|
|
2018-02-26 17:31:12 +01:00
|
|
|
/* global DNS server UDP endpoint */
|
|
|
|
sock_udp_ep_t sock_dns_server;
|
|
|
|
|
2017-03-03 11:14:41 +01:00
|
|
|
int sock_dns_query(const char *domain_name, void *addr_out, int family)
|
|
|
|
{
|
2021-07-21 14:57:44 +02:00
|
|
|
static uint8_t dns_buf[CONFIG_DNS_MSG_LEN];
|
2017-03-03 11:14:41 +01:00
|
|
|
|
2018-02-26 17:36:36 +01:00
|
|
|
if (sock_dns_server.port == 0) {
|
|
|
|
return -ECONNREFUSED;
|
|
|
|
}
|
|
|
|
|
2017-03-03 11:14:41 +01:00
|
|
|
if (strlen(domain_name) > SOCK_DNS_MAX_NAME_LEN) {
|
|
|
|
return -ENOSPC;
|
|
|
|
}
|
|
|
|
|
|
|
|
sock_udp_t sock_dns;
|
|
|
|
|
|
|
|
ssize_t res = sock_udp_create(&sock_dns, NULL, &sock_dns_server, 0);
|
|
|
|
if (res) {
|
|
|
|
goto out;
|
|
|
|
}
|
|
|
|
|
2021-07-21 14:57:44 +02:00
|
|
|
uint16_t id = 0;
|
2017-03-03 11:14:41 +01:00
|
|
|
for (int i = 0; i < SOCK_DNS_RETRIES; i++) {
|
2021-07-21 14:57:44 +02:00
|
|
|
size_t buflen = dns_msg_compose_query(dns_buf, domain_name, id, family);
|
2020-02-23 18:59:15 +01:00
|
|
|
|
2021-07-21 14:57:44 +02:00
|
|
|
res = sock_udp_send(&sock_dns, dns_buf, buflen, NULL);
|
2017-03-03 11:14:41 +01:00
|
|
|
if (res <= 0) {
|
|
|
|
continue;
|
|
|
|
}
|
2020-02-23 18:59:15 +01:00
|
|
|
res = sock_udp_recv(&sock_dns, dns_buf, sizeof(dns_buf), 1000000LU, NULL);
|
2019-01-29 19:10:36 +01:00
|
|
|
if (res > 0) {
|
|
|
|
if (res > (int)DNS_MIN_REPLY_LEN) {
|
2021-07-21 14:57:44 +02:00
|
|
|
if ((res = dns_msg_parse_reply(dns_buf, res, family,
|
|
|
|
addr_out)) > 0) {
|
2019-01-29 19:10:36 +01:00
|
|
|
goto out;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
res = -EBADMSG;
|
2017-03-03 11:14:41 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
out:
|
|
|
|
sock_udp_close(&sock_dns);
|
|
|
|
return res;
|
|
|
|
}
|