llmnr_client.c
Go to the documentation of this file.
1 /**
2  * @file llmnr_client.c
3  * @brief LLMNR client (Link-Local Multicast Name Resolution)
4  *
5  * @section License
6  *
7  * SPDX-License-Identifier: GPL-2.0-or-later
8  *
9  * Copyright (C) 2010-2019 Oryx Embedded SARL. All rights reserved.
10  *
11  * This file is part of CycloneTCP Open.
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License
15  * as published by the Free Software Foundation; either version 2
16  * of the License, or (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26  *
27  * @author Oryx Embedded SARL (www.oryx-embedded.com)
28  * @version 1.9.2
29  **/
30 
31 //Switch to the appropriate trace level
32 #define TRACE_LEVEL LLMNR_TRACE_LEVEL
33 
34 //Dependencies
35 #include "core/net.h"
36 #include "ipv4/ipv4_misc.h"
37 #include "llmnr/llmnr_client.h"
38 #include "llmnr/llmnr_common.h"
39 #include "dns/dns_debug.h"
40 #include "debug.h"
41 
42 //Check TCP/IP stack configuration
43 #if (LLMNR_CLIENT_SUPPORT == ENABLED)
44 
45 
46 /**
47  * @brief Resolve a host name using LLMNR
48  * @param[in] interface Underlying network interface
49  * @param[in] name Name of the host to be resolved
50  * @param[out] ipAddr IP address corresponding to the specified host name
51  **/
52 
54 {
55  error_t error;
56  DnsCacheEntry *entry;
57 
58 #if (NET_RTOS_SUPPORT == ENABLED)
59  systime_t delay;
60 
61  //Debug message
62  TRACE_INFO("Resolving host name %s (LLMNR resolver)...\r\n", name);
63 #endif
64 
65  //Get exclusive access
67 
68  //Search the DNS cache for the specified host name
70 
71  //Check whether a matching entry has been found
72  if(entry)
73  {
74  //Host name already resolved?
75  if(entry->state == DNS_STATE_RESOLVED ||
76  entry->state == DNS_STATE_PERMANENT)
77  {
78  //Return the corresponding IP address
79  *ipAddr = entry->ipAddr;
80  //Successful host name resolution
81  error = NO_ERROR;
82  }
83  else
84  {
85  //Host name resolution is in progress...
86  error = ERROR_IN_PROGRESS;
87  }
88  }
89  else
90  {
91  //If no entry exists, then create a new one
92  entry = dnsCreateEntry();
93 
94  //Record the host name whose IP address is unknown
95  strcpy(entry->name, name);
96 
97  //Initialize DNS cache entry
98  entry->type = HOST_TYPE_IPV4;
100  entry->interface = interface;
101 
102  //Initialize retransmission counter
104  //Send LLMNR query
105  error = llmnrSendQuery(entry);
106 
107  //LLMNR message successfully sent?
108  if(!error)
109  {
110  //Save the time at which the query message was sent
111  entry->timestamp = osGetSystemTime();
112  //Set timeout value
115  //Decrement retransmission counter
116  entry->retransmitCount--;
117 
118  //Switch state
119  entry->state = DNS_STATE_IN_PROGRESS;
120  //Host name resolution is in progress
121  error = ERROR_IN_PROGRESS;
122  }
123  }
124 
125  //Release exclusive access
127 
128 #if (NET_RTOS_SUPPORT == ENABLED)
129  //Set default polling interval
131 
132  //Wait the host name resolution to complete
133  while(error == ERROR_IN_PROGRESS)
134  {
135  //Wait until the next polling period
136  osDelayTask(delay);
137 
138  //Get exclusive access
140 
141  //Search the DNS cache for the specified host name
143 
144  //Check whether a matching entry has been found
145  if(entry)
146  {
147  //Host name successfully resolved?
148  if(entry->state == DNS_STATE_RESOLVED)
149  {
150  //Return the corresponding IP address
151  *ipAddr = entry->ipAddr;
152  //Successful host name resolution
153  error = NO_ERROR;
154  }
155  }
156  else
157  {
158  //Host name resolution failed
159  error = ERROR_FAILURE;
160  }
161 
162  //Release exclusive access
164 
165  //Backoff support for less aggressive polling
166  delay = MIN(delay * 2, DNS_CACHE_MAX_POLLING_INTERVAL);
167  }
168 
169  //Check status code
170  if(error)
171  {
172  //Failed to resolve host name
173  TRACE_INFO("Host name resolution failed!\r\n");
174  }
175  else
176  {
177  //Successful host name resolution
178  TRACE_INFO("Host name resolved to %s...\r\n", ipAddrToString(ipAddr, NULL));
179  }
180 #endif
181 
182  //Return status code
183  return error;
184 }
185 
186 
187 /**
188  * @brief Send a LLMNR query message
189  * @param[in] entry Pointer to a valid DNS cache entry
190  * @return Error code
191  **/
192 
194 {
195  error_t error;
196  size_t length;
197  size_t offset;
198  NetBuffer *buffer;
200  DnsQuestion *dnsQuestion;
202 
203  //Allocate a memory buffer to hold the LLMNR query message
204  buffer = udpAllocBuffer(DNS_MESSAGE_MAX_SIZE, &offset);
205  //Failed to allocate buffer?
206  if(buffer == NULL)
207  return ERROR_OUT_OF_MEMORY;
208 
209  //Point to the LLMNR header
210  message = netBufferAt(buffer, offset);
211 
212  //Format LLMNR query message
213  message->id = htons(entry->id);
214  message->qr = 0;
215  message->opcode = DNS_OPCODE_QUERY;
216  message->aa = 0;
217  message->tc = 0;
218  message->rd = 0;
219  message->ra = 0;
220  message->z = 0;
221  message->b = 1;
222  message->rcode = DNS_RCODE_NO_ERROR;
223 
224  //The LLMNR query contains one question
225  message->qdcount = HTONS(1);
226  message->ancount = 0;
227  message->nscount = 0;
228  message->arcount = 0;
229 
230  //Length of the LLMNR query message
231  length = sizeof(DnsHeader);
232 
233  //Encode the NetBIOS name
234  length += llmnrEncodeName(entry->name, message->questions);
235 
236  //Point to the corresponding question structure
237  dnsQuestion = DNS_GET_QUESTION(message, length);
238  //Fill in question structure
239  dnsQuestion->qtype = HTONS(DNS_RR_TYPE_NB);
240  dnsQuestion->qclass = HTONS(DNS_RR_CLASS_IN);
241 
242  //Update the length of the LLMNR query message
243  length += sizeof(DnsQuestion);
244 
245  //Adjust the length of the multi-part buffer
246  netBufferSetLength(buffer, offset + length);
247 
248  //Debug message
249  TRACE_INFO("Sending LLMNR message (%" PRIuSIZE " bytes)...\r\n", length);
250  //Dump message
252 
253  //The destination address is the broadcast address
254  destIpAddr.length = sizeof(Ipv4Addr);
255  ipv4GetBroadcastAddr(entry->interface, &destIpAddr.ipv4Addr);
256 
257  //A request packet is always sent to the well known port 137
258  error = udpSendDatagramEx(entry->interface, NULL, LLMNR_PORT,
259  &destIpAddr, LLMNR_PORT, buffer, offset, IPV4_DEFAULT_TTL);
260 
261  //Free previously allocated memory
262  netBufferFree(buffer);
263  //Return status code
264  return error;
265 }
266 
267 
268 /**
269  * @brief Process LLMNR response message
270  * @param[in] interface Underlying network interface
271  * @param[in] pseudoHeader UDP pseudo header
272  * @param[in] udpHeader UDP header
273  * @param[in] message Pointer to the LLMNR response message
274  * @param[in] length Length of the message
275  **/
276 
277 void llmnrProcessResponse(NetInterface *interface, const IpPseudoHeader *pseudoHeader,
278  const UdpHeader *udpHeader, const LlmnrHeader *message, size_t length)
279 {
280  uint_t i;
281  size_t pos;
282  DnsCacheEntry *entry;
283  DnsResourceRecord *record;
284  NbnsAddrEntry *addrEntry;
285 
286  //LLMNR senders must silently discard LLMNR responses with QDCOUNT not
287  //equal to one (refer to RFC 4795, section 2.1.1)
288  if(ntohs(message->qdcount) != 1)
289  return;
290 
291  //The LLMNR response shall contain one answer
292  if(ntohs(message->qdcount) != 0 && ntohs(message->ancount) != 1)
293  return;
294 
295  //Parse NetBIOS name
296  pos = llmnrParseName(message, length, sizeof(DnsHeader), NULL);
297  //Invalid name?
298  if(!pos)
299  return;
300 
301  //Point to the associated resource record
302  record = DNS_GET_RESOURCE_RECORD(message, pos);
303  //Point to the resource data
304  pos += sizeof(DnsResourceRecord);
305 
306  //Make sure the resource record is valid
307  if(pos > length)
308  return;
309  if((pos + ntohs(record->rdlength)) > length)
310  return;
311 
312  //Check the class and the type of the resource record
313  if(ntohs(record->rclass) != DNS_RR_CLASS_IN)
314  return;
315  if(ntohs(record->rtype) != DNS_RR_TYPE_NB)
316  return;
317 
318  //Verify the length of the data field
319  if(ntohs(record->rdlength) < sizeof(NbnsAddrEntry))
320  return;
321 
322  //Loop through DNS cache entries
323  for(i = 0; i < DNS_CACHE_SIZE; i++)
324  {
325  //Point to the current entry
326  entry = &dnsCache[i];
327 
328  //LLMNR name resolution in progress?
329  if(entry->state == DNS_STATE_IN_PROGRESS &&
331  entry->type == HOST_TYPE_IPV4)
332  {
333  //Compare identifiers
334  if(entry->id == ntohs(message->id))
335  {
336  //Compare NetBIOS names
337  if(llmnrCompareName(message, length, sizeof(DnsHeader), entry->name))
338  {
339  //Point to the address entry array
340  addrEntry = (NbnsAddrEntry *) record->rdata;
341  //Copy the IPv4 address
342  entry->ipAddr.length = sizeof(Ipv4Addr);
343  entry->ipAddr.ipv4Addr = addrEntry->addr;
344 
345  //Save current time
346  entry->timestamp = osGetSystemTime();
347  //Save TTL value
348  entry->timeout = ntohl(record->ttl) * 1000;
349  //Limit the lifetime of the LLMNR cache entries
350  entry->timeout = MIN(entry->timeout, LLMNR_MAX_LIFETIME);
351 
352  //Host name successfully resolved
353  entry->state = DNS_STATE_RESOLVED;
354  }
355  }
356  }
357  }
358 }
359 
360 #endif
#define DNS_GET_QUESTION(message, offset)
Definition: dns_common.h:63
uint32_t Ipv4Addr
IPv4 network address.
Definition: ipv4.h:235
__start_packed struct @151 DnsQuestion
Question format.
#define DNS_GET_RESOURCE_RECORD(message, offset)
Definition: dns_common.h:64
uint32_t systime_t
Definition: compiler_port.h:46
DnsCacheEntry dnsCache[DNS_CACHE_SIZE]
Definition: dns_cache.c:51
char char_t
Definition: compiler_port.h:43
HostnameResolver protocol
Name resolution protocol.
Definition: dns_cache.h:100
Ipv4Addr ipv4Addr
Definition: ip.h:65
NetBIOS name service.
Definition: dns_common.h:134
systime_t osGetSystemTime(void)
Retrieve system time.
TCP/IP stack core.
void netBufferFree(NetBuffer *buffer)
Dispose a multi-part buffer.
Definition: net_mem.c:282
Debugging facilities.
__start_packed struct @264 NbnsHeader
NBNS message header.
Internet.
Definition: dns_common.h:110
#define LLMNR_CLIENT_MAX_RETRIES
Definition: llmnr_client.h:51
Generic error code.
Definition: error.h:45
uint8_t message[]
Definition: chap.h:152
error_t netBufferSetLength(NetBuffer *buffer, size_t length)
Adjust the length of a multi-part buffer.
Definition: net_mem.c:320
IpAddr ipAddr
IP address.
Definition: dns_cache.h:106
HostType type
IPv4 or IPv6 host?
Definition: dns_cache.h:99
IP network address.
Definition: ip.h:59
systime_t timeout
Retransmission timeout.
Definition: dns_cache.h:108
char_t * ipAddrToString(const IpAddr *ipAddr, char_t *str)
Convert a binary IP address to a string representation.
Definition: ip.c:688
error_t ipv4GetBroadcastAddr(NetInterface *interface, Ipv4Addr *addr)
Get IPv4 broadcast address.
Definition: ipv4_misc.c:613
#define htons(value)
Definition: cpu_endian.h:392
uint16_t id
Identifier used to match queries and responses.
Definition: dns_cache.h:104
#define HTONS(value)
Definition: cpu_endian.h:390
error_t udpSendDatagramEx(NetInterface *interface, const IpAddr *srcIpAddr, uint16_t srcPort, const IpAddr *destIpAddr, uint16_t destPort, NetBuffer *buffer, size_t offset, uint8_t ttl)
Send a UDP datagram (raw interface)
Definition: udp.c:452
systime_t timestamp
Time stamp to manage entry lifetime.
Definition: dns_cache.h:107
#define LLMNR_CLIENT_MAX_TIMEOUT
Definition: llmnr_client.h:65
uint8_t ipAddr[4]
Definition: mib_common.h:187
#define IPV4_DEFAULT_TTL
Definition: ipv4.h:56
Data logging functions for debugging purpose (DNS)
__start_packed struct @265 NbnsAddrEntry
NBNS address entry.
#define ntohl(value)
Definition: cpu_endian.h:399
#define LLMNR_PORT
Definition: llmnr_common.h:46
char_t name[DNS_MAX_NAME_LEN+1]
Domain name.
Definition: dns_cache.h:105
error_t llmnrResolve(NetInterface *interface, const char_t *name, IpAddr *ipAddr)
Resolve a host name using LLMNR.
Definition: llmnr_client.c:53
__start_packed struct @150 DnsHeader
DNS message header.
DnsCacheEntry * dnsFindEntry(NetInterface *interface, const char_t *name, HostType type, HostnameResolver protocol)
Search the DNS cache for a given domain name.
Definition: dns_cache.c:183
#define ntohs(value)
Definition: cpu_endian.h:398
DNS cache entry.
Definition: dns_cache.h:96
#define LLMNR_CLIENT_INIT_TIMEOUT
Definition: llmnr_client.h:58
void * netBufferAt(const NetBuffer *buffer, size_t offset)
Returns a pointer to the data at the specified position.
Definition: net_mem.c:413
Helper functions for IPv4.
char_t name[]
__start_packed struct @126 UdpHeader
UDP header.
void osDelayTask(systime_t delay)
Delay routine.
Structure describing a buffer that spans multiple chunks.
Definition: net_mem.h:88
DnsCacheEntry * dnsCreateEntry(void)
Create a new entry in the DNS cache.
Definition: dns_cache.c:101
#define MIN(a, b)
Definition: os_port.h:62
NetInterface * interface
Underlying network interface.
Definition: dns_cache.h:101
#define DNS_CACHE_MAX_POLLING_INTERVAL
Definition: dns_cache.h:68
#define DNS_CACHE_INIT_POLLING_INTERVAL
Definition: dns_cache.h:61
void dnsDumpMessage(const DnsHeader *message, size_t length)
Dump DNS message for debugging purpose.
Definition: dns_debug.c:52
NetBuffer * udpAllocBuffer(size_t length, size_t *offset)
Allocate a buffer to hold a UDP packet.
Definition: udp.c:684
#define TRACE_INFO(...)
Definition: debug.h:94
systime_t maxTimeout
Maximum retransmission timeout.
Definition: dns_cache.h:109
Success.
Definition: error.h:44
#define DNS_MESSAGE_MAX_SIZE
Definition: dns_common.h:45
error_t
Error codes.
Definition: error.h:42
Ipv4Addr destIpAddr
Definition: ipcp.h:78
size_t length
Definition: ip.h:61
unsigned int uint_t
Definition: compiler_port.h:45
void osReleaseMutex(OsMutex *mutex)
Release ownership of the specified mutex object.
#define PRIuSIZE
Definition: compiler_port.h:78
#define NetInterface
Definition: net.h:36
__start_packed struct @208 LlmnrHeader
LLMNR message header.
IP pseudo header.
Definition: ip.h:78
void llmnrProcessResponse(NetInterface *interface, const IpPseudoHeader *pseudoHeader, const UdpHeader *udpHeader, const LlmnrHeader *message, size_t length)
Process LLMNR response message.
Definition: llmnr_client.c:277
error_t llmnrSendQuery(DnsCacheEntry *entry)
Send a LLMNR query message.
Definition: llmnr_client.c:193
Definitions common to LLMNR client and responder.
__start_packed struct @152 DnsResourceRecord
Resource record format.
LLMNR client (Link-Local Multicast Name Resolution)
OsMutex netMutex
Definition: net.c:74
DnsState state
Entry state.
Definition: dns_cache.h:98
#define LLMNR_MAX_LIFETIME
Definition: llmnr_client.h:72
uint8_t length
Definition: dtls_misc.h:142
uint_t retransmitCount
Retransmission counter.
Definition: dns_cache.h:110
void osAcquireMutex(OsMutex *mutex)
Acquire ownership of the specified mutex object.
#define DNS_CACHE_SIZE
Definition: dns_cache.h:47