diff --git a/net/golioth/system_client.c b/net/golioth/system_client.c index 13c6cb24..3e801247 100644 --- a/net/golioth/system_client.c +++ b/net/golioth/system_client.c @@ -19,12 +19,41 @@ LOG_MODULE_REGISTER(golioth_system, CONFIG_GOLIOTH_SYSTEM_CLIENT_LOG_LEVEL); #define RX_BUFFER_SIZE CONFIG_GOLIOTH_SYSTEM_CLIENT_RX_BUF_SIZE +static char golioth_system_server_host[40] = CONFIG_GOLIOTH_SYSTEM_SERVER_HOST; + static const uint8_t tls_ca_crt[] = { #if defined(CONFIG_GOLIOTH_SYSTEM_CLIENT_CA_PATH) #include "golioth-systemclient-ca.inc" #endif }; +#ifdef CONFIG_NET_L2_OPENTHREAD +#include +#include +#include +#include + +static otDnsQueryConfig dns_query; +K_SEM_DEFINE(ot_dns_resolve, 0, 1); + +/* Callback for NAT64 IPv6 translated Golioth System Server address from the DNS query response */ +static void ot_dns_callback(otError aError, const otDnsAddressResponse *aResponse, void *aContext) +{ + otIp6Address golioth_ipv6_addr; + + if (aError != OT_ERROR_NONE) { + LOG_ERR("Golioth System Server DNS resolving error %d", aError); + return; + } + + if (otDnsAddressResponseGetAddress(aResponse, 0, &golioth_ipv6_addr, NULL) == OT_ERROR_NONE) { + otIp6AddressToString(&golioth_ipv6_addr, golioth_system_server_host, OT_IP6_ADDRESS_STRING_SIZE); + } + + k_sem_give(&ot_dns_resolve); +} +#endif + #define PING_INTERVAL (CONFIG_GOLIOTH_SYSTEM_CLIENT_PING_INTERVAL_SEC * 1000) #define RECV_TIMEOUT (CONFIG_GOLIOTH_SYSTEM_CLIENT_RX_TIMEOUT_SEC * 1000) @@ -244,11 +273,50 @@ SYS_INIT(golioth_system_init, APPLICATION, static int client_connect(struct golioth_client *client) { - int err; + int err = 0; + +/* + * Get the IPv6 address of GOLIOTH_SYSTEM_SERVER_HOST to avoid hardcoding it + * in user application. NAT64 prefix used by the Thread Border Router + * is set while synthesizing the IPv6 address. + */ +#if defined (CONFIG_NET_L2_OPENTHREAD) + struct openthread_context *ot_context = openthread_get_default_context(); + + otIp4Address dns_server_addr; + + err = otIp4AddressFromString(CONFIG_DNS_SERVER1, &dns_server_addr); + if (err != OT_ERROR_NONE) { + LOG_ERR("DNS server IPv4 address error: %d", err); + return err; + } + + err = otNat64SynthesizeIp6Address(ot_context->instance, + &dns_server_addr, + &dns_query.mServerSockAddr.mAddress); + if (err != OT_ERROR_NONE) { + LOG_ERR("Synthesize DNS server IPv6 address error: %d", err); + return err; + } + + err = otDnsClientResolveIp4Address(ot_context->instance, + CONFIG_GOLIOTH_SYSTEM_SERVER_HOST, + ot_dns_callback, + ot_context, + &dns_query); + if (err != OT_ERROR_NONE) { + LOG_ERR("Golioth System Server address resolution DNS query error: %d", err); + return err; + } + + k_sem_take(&ot_dns_resolve, K_FOREVER); + +#endif err = golioth_connect(client, - CONFIG_GOLIOTH_SYSTEM_SERVER_HOST, + golioth_system_server_host, CONFIG_GOLIOTH_SYSTEM_SERVER_PORT); + if (err) { LOG_ERR("Failed to connect: %d", err); return err;