1
0
mirror of https://github.com/RIOT-OS/RIOT.git synced 2024-12-29 04:50:03 +01:00

Merge pull request #6694 from kaspar030/add_sock_dns_client

sys: net: add sock dns client
This commit is contained in:
Martine Lenders 2017-03-29 10:14:38 +02:00 committed by GitHub
commit 33991832d1
11 changed files with 703 additions and 0 deletions

View File

@ -615,6 +615,10 @@ ifneq (,$(filter vfs,$(USEMODULE)))
endif
endif
ifneq (,$(filter sock_dns,$(USEMODULE)))
USEMODULE += sock_util
endif
# include package dependencies
-include $(USEPKG:%=$(RIOTPKG)/%/Makefile.dep)

View File

@ -111,6 +111,12 @@ endif
ifneq (,$(filter emcute,$(USEMODULE)))
DIRS += net/application_layer/emcute
endif
ifneq (,$(filter sock_util,$(USEMODULE)))
DIRS += net/sock
endif
ifneq (,$(filter sock_dns,$(USEMODULE)))
DIRS += net/application_layer/dns
endif
ifneq (,$(filter constfs,$(USEMODULE)))
DIRS += fs/constfs

View File

@ -0,0 +1,98 @@
/*
* 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.
*/
/**
* @defgroup net_sock_dns DNS sock API
* @ingroup net_sock
*
* @brief Sock DNS client
*
* @{
*
* @file
* @brief DNS sock definitions
*
* @author Kaspar Schleiser <kaspar@schleiser.de>
*/
#ifndef SOCK_DNS_H
#define SOCK_DNS_H
#include <errno.h>
#include <stdint.h>
#include <unistd.h>
#include "net/sock/udp.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief DNS internal structure
*/
typedef struct {
uint16_t id; /**< read */
uint16_t flags; /**< DNS */
uint16_t qdcount; /**< RFC */
uint16_t ancount; /**< for */
uint16_t nscount; /**< detailed */
uint16_t arcount; /**< explanations */
uint8_t payload[]; /**< !! */
} sock_dns_hdr_t;
/**
* @name DNS defines
* @{
*/
#define DNS_TYPE_A (1)
#define DNS_TYPE_AAAA (28)
#define DNS_CLASS_IN (1)
#define SOCK_DNS_PORT (53)
#define SOCK_DNS_RETRIES (2)
#define SOCK_DNS_MAX_NAME_LEN (64U) /* we're in embedded context. */
#define SOCK_DNS_QUERYBUF_LEN (sizeof(sock_dns_hdr_t) + 4 + SOCK_DNS_MAX_NAME_LEN)
/** @} */
/**
* @brief Get IP address for DNS name
*
* This function will synchronously try to resolve a DNS A or AAAA record by contacting
* the DNS server specified in the global variable @ref sock_dns_server.
*
* By supplying AF_INET, AF_INET6 or AF_UNSPEC in @p family requesting of A
* records (IPv4), AAAA records (IPv6) or both can be selected.
*
* This fuction will return the first DNS record it receives. IF both A and
* AAAA are requested, AAAA will be preferred.
*
* @note @p addr_out needs to provide space for any possible result!
* (4byte when family==AF_INET, 16byte otherwise)
*
* @param[in] domain_name DNS name to resolve into address
* @param[out] addr_out buffer to write result into
* @param[in] family Either AF_INET, AF_INET6 or AF_UNSPEC
*
* @return 0 on success
* @return !=0 otherwise
*/
int sock_dns_query(const char *domain_name, void *addr_out, int family);
/**
* @brief global DNS server endpoint
*/
extern sock_udp_ep_t sock_dns_server;
#ifdef __cplusplus
}
#endif
#endif /* SOCK_DNS_H */
/** @} */

View File

@ -0,0 +1,91 @@
/*
* 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.
*/
/**
* @defgroup net_sock_util sock utility functions
* @ingroup net_sock
*
* @brief sock utility function
*
* @{
*
* @file
* @brief sock utility function definitions
*
* @author Kaspar Schleiser <kaspar@schleiser.de>
*/
#ifndef SOCK_UTIL_H
#define SOCK_UTIL_H
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Format UDP endpoint to string and port
*
* @param[in] endpoint endpoint to format
* @param[out] addr_str where to write address as string
* @param[out] port where to write prt number as uint16_t
*
* @returns number of bytes written to @p addr_str on success
* @returns <0 otherwise
*/
int sock_udp_ep_fmt(const sock_udp_ep_t *endpoint, char *addr_str, uint16_t *port);
/**
* @brief Split url to host:port and url path
*
* Will split e.g., "https://host.name:1234/url/path" into
* "host.name:1234" and "/url/path".
*
* @note Caller has to make sure hostport and urlpath can hold the results!
* Make sure to provide space for SOCK_HOSTPORT_MAXLEN respectively
* SOCK_URLPATH_MAXLEN bytes.
*
* @param[in] url URL to split
* @param[out] hostport where to write host:port
* @param[out] urlpath where to write url path
*
* @returns 0 on success
* @returns <0 otherwise
*/
int sock_urlsplit(const char *url, char *hostport, char *urlpath);
/**
* @brief Convert string to UDP endpoint
*
* Takes eg., "[2001:db8::1]:1234" and converts it into the corresponding UDP
* endpoint structure.
*
* @param[out] ep_out endpoint structure to fill
* @param[in] str string to read from
*
* @returns 0 on success
* @returns <0 otherwise
*/
int sock_udp_str2ep(sock_udp_ep_t *ep_out, const char *str);
/**
* @name helper definitions
* @{
*/
#define SOCK_HOSTPORT_MAXLEN (64U) /**< maximum length of host:port part for
sock_urlsplit() */
#define SOCK_URLPATH_MAXLEN (64U) /**< maximum length path for
sock_urlsplit() */
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* SOCK_UTIL_H */
/** @} */

View File

@ -0,0 +1,2 @@
MODULE=sock_dns
include $(RIOTBASE)/Makefile.base

View File

@ -0,0 +1,192 @@
/*
* 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>
* @}
*/
#include <string.h>
#include <stdio.h>
#include "net/sock/udp.h"
#include "net/sock/dns.h"
#ifdef RIOT_VERSION
#include "byteorder.h"
#define ntohs NTOHS
#define htons HTONS
#endif
/* min domain name length is 1, so minimum record length is 7 */
#define DNS_MIN_REPLY_LEN (unsigned)(sizeof(sock_dns_hdr_t ) + 7)
static ssize_t _enc_domain_name(uint8_t *out, const char *domain_name)
{
/*
* DNS encodes domain names with "<len><part><len><part>", e.g.,
* "example.org" ends up as "\7example\3org" in the packet.
*/
uint8_t *part_start = out;
uint8_t *out_pos = ++out;
char c;
while ((c = *domain_name)) {
if (c == '.') {
/* replace dot with length of name part as byte */
*part_start = (out_pos - part_start - 1);
part_start = out_pos++;
}
else {
*out_pos++ = c;
}
domain_name++;
}
*part_start = (out_pos - part_start - 1);
*out_pos++ = 0;
return out_pos - out + 1;
}
static unsigned _put_short(uint8_t *out, uint16_t val)
{
memcpy(out, &val, 2);
return 2;
}
static unsigned _get_short(uint8_t *buf)
{
uint16_t _tmp;
memcpy(&_tmp, buf, 2);
return _tmp;
}
static size_t _skip_hostname(uint8_t *buf)
{
uint8_t *bufpos = buf;
/* handle DNS Message Compression */
if (*bufpos >= 192) {
return 2;
}
while(*bufpos) {
bufpos += *bufpos + 1;
}
return (bufpos - buf + 1);
}
static int _parse_dns_reply(uint8_t *buf, size_t len, void* addr_out, int family)
{
sock_dns_hdr_t *hdr = (sock_dns_hdr_t*) buf;
uint8_t *bufpos = buf + sizeof(*hdr);
/* skip all queries that are part of the reply */
for (unsigned n = 0; n < ntohs(hdr->qdcount); n++) {
bufpos += _skip_hostname(bufpos);
bufpos += 4; /* skip type and class of query */
}
for (unsigned n = 0; n < ntohs(hdr->ancount); n++) {
bufpos += _skip_hostname(bufpos);
uint16_t _type = ntohs(_get_short(bufpos));
bufpos += 2;
uint16_t class = ntohs(_get_short(bufpos));
bufpos += 2;
bufpos += 4; /* skip ttl */
unsigned addrlen = ntohs(_get_short(bufpos));
bufpos += 2;
if ((bufpos + addrlen) > (buf + len)) {
return -EBADMSG;
}
/* skip unwanted answers */
if ((class != DNS_CLASS_IN) ||
((_type == DNS_TYPE_A) && (family == AF_INET6)) ||
((_type == DNS_TYPE_AAAA) && (family == AF_INET)) ||
! ((_type == DNS_TYPE_A) || ((_type == DNS_TYPE_AAAA))
)) {
bufpos += addrlen;
continue;
}
memcpy(addr_out, bufpos, addrlen);
return addrlen;
}
return -1;
}
int sock_dns_query(const char *domain_name, void *addr_out, int family)
{
uint8_t buf[SOCK_DNS_QUERYBUF_LEN];
uint8_t reply_buf[512];
if (strlen(domain_name) > SOCK_DNS_MAX_NAME_LEN) {
return -ENOSPC;
}
sock_dns_hdr_t *hdr = (sock_dns_hdr_t*) buf;
memset(hdr, 0, sizeof(*hdr));
hdr->id = 0; /* random? */
hdr->flags = htons(0x0120);
hdr->qdcount = htons(1 + (family == AF_UNSPEC));
uint8_t *bufpos = buf + sizeof(*hdr);
unsigned _name_ptr;
if ((family == AF_INET6) || (family == AF_UNSPEC)) {
_name_ptr = (bufpos - buf);
bufpos += _enc_domain_name(bufpos, domain_name);
bufpos += _put_short(bufpos, htons(DNS_TYPE_AAAA));
bufpos += _put_short(bufpos, htons(DNS_CLASS_IN));
}
if ((family == AF_INET) || (family == AF_UNSPEC)) {
if (family == AF_UNSPEC) {
bufpos += _put_short(bufpos, htons((0xc000) | (_name_ptr)));
}
else {
bufpos += _enc_domain_name(bufpos, domain_name);
}
bufpos += _put_short(bufpos, htons(DNS_TYPE_A));
bufpos += _put_short(bufpos, htons(DNS_CLASS_IN));
}
sock_udp_t sock_dns;
ssize_t res = sock_udp_create(&sock_dns, NULL, &sock_dns_server, 0);
if (res) {
puts("a");
goto out;
}
for (int i = 0; i < SOCK_DNS_RETRIES; i++) {
res = sock_udp_send(&sock_dns, buf, (bufpos-buf), NULL);
if (res <= 0) {
continue;
}
res = sock_udp_recv(&sock_dns, reply_buf, sizeof(reply_buf), 1000000LU, NULL);
if ((res > 0) && (res > (int)DNS_MIN_REPLY_LEN)) {
if ((res = _parse_dns_reply(reply_buf, res, addr_out, family)) > 0) {
goto out;
}
}
}
out:
sock_udp_close(&sock_dns);
return res;
}

2
sys/net/sock/Makefile Normal file
View File

@ -0,0 +1,2 @@
MODULE = sock_util
include $(RIOTBASE)/Makefile.base

183
sys/net/sock/sock_util.c Normal file
View File

@ -0,0 +1,183 @@
/*
* 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_util
* @{
* @file
* @brief sock utility functions implementation
* @author Kaspar Schleiser <kaspar@schleiser.de>
* @}
*/
#include <arpa/inet.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include "net/sock/udp.h"
#include "net/sock/util.h"
#ifdef RIOT_VERSION
#include "fmt.h"
#endif
#define SOCK_HOST_MAXLEN (64U) /**< maximum length of host part for
sock_udp_str2ep() */
int sock_udp_ep_fmt(const sock_udp_ep_t *endpoint, char *addr_str, uint16_t *port)
{
void *addr_ptr;
*addr_str = '\0';
switch (endpoint->family) {
#if defined(SOCK_HAS_IPV4)
case AF_INET:
{
addr_ptr = (void*)&endpoint->addr.ipv4;
break;
}
#endif
#if defined(SOCK_HAS_IPV6)
case AF_INET6:
{
addr_ptr = (void*)&endpoint->addr.ipv6;
break;
}
#endif /* else fall through */
default:
return -ENOTSUP;
}
if (!inet_ntop(endpoint->family, addr_ptr, addr_str, INET6_ADDRSTRLEN)) {
return 0;
}
#if defined(SOCK_HAS_IPV6)
if ((endpoint->family == AF_INET6) && endpoint->netif) {
#ifdef RIOT_VERSION
char *tmp = addr_str + strlen(addr_str);
*tmp++ = '%';
tmp += fmt_u16_dec(tmp, endpoint->netif);
*tmp = '0';
#else
sprintf(addr_str + strlen(addr_str), "%%%4u", endpoint->netif);
#endif
}
#endif
if (port) {
*port = endpoint->port;
}
return strlen(addr_str);
}
static char* _find_hoststart(const char *url)
{
char *urlpos = (char*)url;
while(*urlpos) {
if (*urlpos++ == ':') {
if (strncmp(urlpos, "//", 2) == 0) {
return urlpos + 2;
}
break;
}
urlpos++;
}
return NULL;
}
static char* _find_pathstart(const char *url)
{
char *urlpos = (char*)url;
while(*urlpos) {
if (*urlpos == '/') {
return urlpos;
}
urlpos++;
}
return NULL;
}
int sock_urlsplit(const char *url, char *hostport, char *urlpath)
{
char *hoststart = _find_hoststart(url);
if (!hoststart) {
return -EINVAL;
}
char *pathstart = _find_pathstart(hoststart);
if(!pathstart) {
return -EINVAL;
}
memcpy(hostport, hoststart, pathstart - hoststart);
size_t pathlen = strlen(pathstart);
if (pathlen) {
memcpy(urlpath, pathstart, pathlen);
}
else {
*urlpath = '\0';
}
return 0;
}
int sock_udp_str2ep(sock_udp_ep_t *ep_out, const char *str)
{
unsigned brackets_flag;
char *hoststart = (char*)str;
char *hostend = hoststart;
char hostbuf[SOCK_HOST_MAXLEN];
memset(ep_out, 0, sizeof(sock_udp_ep_t));
if (*hoststart == '[') {
brackets_flag = 1;
for (hostend = ++hoststart; *hostend && *hostend != ']';
hostend++);
if (! *hostend) {
/* none found, bail out */
return -EINVAL;
}
}
else {
brackets_flag = 0;
for (hostend = hoststart; *hostend && *hostend != ':';
hostend++);
}
if (*(hostend + brackets_flag) == ':') {
ep_out->port = atoi(hostend + brackets_flag + 1);
}
size_t hostlen = hostend - hoststart;
if (hostlen >= sizeof(hostbuf)) {
return -EINVAL;
}
memcpy(hostbuf, hoststart, hostlen);
hostbuf[hostlen] = '\0';
if (!brackets_flag) {
if (inet_pton(AF_INET, hostbuf, &ep_out->addr.ipv4) == 1) {
ep_out->family = AF_INET;
return 0;
}
}
#if defined(SOCK_HAS_IPV6)
if (inet_pton(AF_INET6, hostbuf, ep_out->addr.ipv6) == 1) {
ep_out->family = AF_INET6;
return 0;
}
#endif
return -EINVAL;
}

View File

@ -0,0 +1,26 @@
APPLICATION = gnrc_sock_dns
include ../Makefile.tests_common
RIOTBASE ?= $(CURDIR)/../..
BOARD_INSUFFICIENT_MEMORY := chronos telosb nucleo32-f042 nucleo32-f031 nucleo-f030 nucleo-l053 nucleo32-l031 stm32f0discovery
USEMODULE += sock_dns
USEMODULE += gnrc_sock_udp
USEMODULE += gnrc_ipv6_default
USEMODULE += gnrc_netdev_default
USEMODULE += auto_init_gnrc_netif
USEMODULE += shell_commands
USEMODULE += posix
CFLAGS += -DDEVELHELP
LOW_MEMORY_BOARDS := nucleo-f334 msb-430 msb-430h weio
ifeq ($(BOARD),$(filter $(BOARD),$(LOW_MEMORY_BOARDS)))
CFLAGS += -DGNRC_PKTBUF_SIZE=512 -DGNRC_IPV6_NETIF_ADDR_NUMOF=4 -DGNRC_IPV6_NC_SIZE=1
endif
include $(RIOTBASE)/Makefile.include

View File

@ -0,0 +1,30 @@
# Overview
This folder contains a test application for RIOT's sock-based DNS client.
# How to test with native
Setup up a tap interface:
$ sudo ip tuntap add dev tap0 mode tap user $(id -u -n)
$ sudo ip a a 2001:db8::1/64 dev tap0
$ sudo ip link set up dev tap0
Start dnsmasq (in another console):
$ sudo dnsmasq -d -2 -z -i tap0 -q --no-resolv \
--dhcp-range=::1,constructor:tap0,ra-only \
--listen-address 2001:db8::1 \
--host-record=example.org,10.0.0.1,2001:db8::1
(NetworkManager is known to start an interfering dnsmasq instance. It needs to
be stopped before this test.)
Then run the test application
$ make term
The application will take a little while to auto-configure it's IP address.
Then you should see something like
example.org resolves to 2001:db8::1

View File

@ -0,0 +1,69 @@
/*
* 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 tests
* @{
*
* @file
* @brief sock DNS client test application
*
* @author Kaspar Schleiser <kaspar@schleiser.de>
*
* @}
*/
#include <stddef.h>
#include <stdio.h>
#include <arpa/inet.h>
#include "net/sock/dns.h"
#include "net/sock/util.h"
#include "xtimer.h"
#ifndef TEST_NAME
#define TEST_NAME "example.org"
#endif
#ifndef DNS_SERVER
#define DNS_SERVER "[2001:db8::1]:53"
#endif
/* global DNS server UDP endpoint */
sock_udp_ep_t sock_dns_server;
/* import "ifconfig" shell command, used for printing addresses */
extern int _netif_config(int argc, char **argv);
int main(void)
{
uint8_t addr[16] = {0};
sock_udp_str2ep(&sock_dns_server, DNS_SERVER);
puts("waiting for router advertisement...");
xtimer_usleep(1U*1000000);
/* print network addresses */
puts("Configured network interfaces:");
_netif_config(0, NULL);
int res = sock_dns_query(TEST_NAME, addr, AF_UNSPEC);
if (res > 0) {
char addrstr[INET6_ADDRSTRLEN];
inet_ntop(res == 4 ? AF_INET : AF_INET6, addr, addrstr, sizeof(addrstr));
printf("%s resolves to %s\n", TEST_NAME, addrstr);
}
else {
printf("error resolving %s\n", TEST_NAME);
}
return 0;
}