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.4
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[in] type Host type (IPv4 or IPv6)
51  * @param[out] ipAddr IP address corresponding to the specified host name
52  **/
53 
56 {
57  error_t error;
58  DnsCacheEntry *entry;
59 
60 #if (NET_RTOS_SUPPORT == ENABLED)
61  systime_t delay;
62 
63  //Debug message
64  TRACE_INFO("Resolving host name %s (LLMNR resolver)...\r\n", name);
65 #endif
66 
67  //Get exclusive access
69 
70  //Search the DNS cache for the specified host name
71  entry = dnsFindEntry(interface, name, type, HOST_NAME_RESOLVER_LLMNR);
72 
73  //Check whether a matching entry has been found
74  if(entry)
75  {
76  //Host name already resolved?
77  if(entry->state == DNS_STATE_RESOLVED ||
78  entry->state == DNS_STATE_PERMANENT)
79  {
80  //Return the corresponding IP address
81  *ipAddr = entry->ipAddr;
82  //Successful host name resolution
83  error = NO_ERROR;
84  }
85  else
86  {
87  //Host name resolution is in progress...
88  error = ERROR_IN_PROGRESS;
89  }
90  }
91  else
92  {
93  //If no entry exists, then create a new one
94  entry = dnsCreateEntry();
95 
96  //Record the host name whose IP address is unknown
97  strcpy(entry->name, name);
98 
99  //Initialize DNS cache entry
100  entry->type = type;
102  entry->interface = interface;
103 
104  //Get an ephemeral port number
105  entry->port = udpGetDynamicPort();
106 
107  //An identifier is used by the LLMNR client to match replies
108  //with corresponding requests
109  entry->id = (uint16_t) netGetRand();
110 
111  //Callback function to be called when a LLMNR response is received
112  error = udpAttachRxCallback(interface, entry->port, llmnrProcessResponse,
113  NULL);
114 
115  //Check status code
116  if(!error)
117  {
118  //Initialize retransmission counter
120  //Send LLMNR query
121  error = llmnrSendQuery(entry);
122 
123  //LLMNR message successfully sent?
124  if(!error)
125  {
126  //Save the time at which the query message was sent
127  entry->timestamp = osGetSystemTime();
128  //Set timeout value
131  //Decrement retransmission counter
132  entry->retransmitCount--;
133 
134  //Switch state
135  entry->state = DNS_STATE_IN_PROGRESS;
136  //Host name resolution is in progress
137  error = ERROR_IN_PROGRESS;
138  }
139  else
140  {
141  //Unregister callback function
142  udpDetachRxCallback(interface, entry->port);
143  }
144  }
145  }
146 
147  //Release exclusive access
149 
150 #if (NET_RTOS_SUPPORT == ENABLED)
151  //Set default polling interval
153 
154  //Wait the host name resolution to complete
155  while(error == ERROR_IN_PROGRESS)
156  {
157  //Wait until the next polling period
158  osDelayTask(delay);
159 
160  //Get exclusive access
162 
163  //Search the DNS cache for the specified host name
164  entry = dnsFindEntry(interface, name, type, HOST_NAME_RESOLVER_LLMNR);
165 
166  //Check whether a matching entry has been found
167  if(entry)
168  {
169  //Host name successfully resolved?
170  if(entry->state == DNS_STATE_RESOLVED)
171  {
172  //Return the corresponding IP address
173  *ipAddr = entry->ipAddr;
174  //Successful host name resolution
175  error = NO_ERROR;
176  }
177  }
178  else
179  {
180  //Host name resolution failed
181  error = ERROR_FAILURE;
182  }
183 
184  //Release exclusive access
186 
187  //Backoff support for less aggressive polling
188  delay = MIN(delay * 2, DNS_CACHE_MAX_POLLING_INTERVAL);
189  }
190 
191  //Check status code
192  if(error)
193  {
194  //Failed to resolve host name
195  TRACE_INFO("Host name resolution failed!\r\n");
196  }
197  else
198  {
199  //Successful host name resolution
200  TRACE_INFO("Host name resolved to %s...\r\n", ipAddrToString(ipAddr, NULL));
201  }
202 #endif
203 
204  //Return status code
205  return error;
206 }
207 
208 
209 /**
210  * @brief Send a LLMNR query message
211  * @param[in] entry Pointer to a valid DNS cache entry
212  * @return Error code
213  **/
214 
216 {
217  error_t error;
218  size_t length;
219  size_t offset;
220  NetBuffer *buffer;
222  DnsQuestion *dnsQuestion;
224 
225 #if (IPV4_SUPPORT == ENABLED)
226  //An IPv4 address is expected?
227  if(entry->type == HOST_TYPE_IPV4)
228  {
229  //The IPv4 link-scope multicast address to which a sender sends queries
230  //is 224.0.0.252
231  destIpAddr.length = sizeof(Ipv4Addr);
233  }
234  else
235 #endif
236 #if (IPV6_SUPPORT == ENABLED)
237  //An IPv6 address is expected?
238  if(entry->type == HOST_TYPE_IPV6)
239  {
240  //The IPv6 link-scope multicast address to which a sender sends queries
241  //is ff02:0:0:0:0:0:1:3
242  destIpAddr.length = sizeof(Ipv6Addr);
244  }
245  else
246 #endif
247  //Invalid host type?
248  {
249  //Report an error
251  }
252 
253  //Allocate a memory buffer to hold the LLMNR query message
254  buffer = udpAllocBuffer(DNS_MESSAGE_MAX_SIZE, &offset);
255  //Failed to allocate buffer?
256  if(buffer == NULL)
257  return ERROR_OUT_OF_MEMORY;
258 
259  //Point to the LLMNR header
260  message = netBufferAt(buffer, offset);
261 
262  //Format LLMNR query message
263  message->id = htons(entry->id);
264  message->qr = 0;
265  message->opcode = DNS_OPCODE_QUERY;
266  message->c = 0;
267  message->tc = 0;
268  message->t = 0;
269  message->z = 0;
270  message->rcode = DNS_RCODE_NO_ERROR;
271 
272  //The LLMNR query contains one question
273  message->qdcount = HTONS(1);
274  message->ancount = 0;
275  message->nscount = 0;
276  message->arcount = 0;
277 
278  //Length of the LLMNR query message
279  length = sizeof(DnsHeader);
280 
281  //Encode the host name using the DNS name notation
282  length += dnsEncodeName(entry->name, message->questions);
283 
284  //Point to the corresponding question structure
285  dnsQuestion = DNS_GET_QUESTION(message, length);
286 
287 #if (IPV4_SUPPORT == ENABLED)
288  //An IPv4 address is expected?
289  if(entry->type == HOST_TYPE_IPV4)
290  {
291  //Fill in question structure
292  dnsQuestion->qtype = HTONS(DNS_RR_TYPE_A);
293  dnsQuestion->qclass = HTONS(DNS_RR_CLASS_IN);
294  }
295 #endif
296 #if (IPV6_SUPPORT == ENABLED)
297  //An IPv6 address is expected?
298  if(entry->type == HOST_TYPE_IPV6)
299  {
300  //Fill in question structure
301  dnsQuestion->qtype = HTONS(DNS_RR_TYPE_AAAA);
302  dnsQuestion->qclass = HTONS(DNS_RR_CLASS_IN);
303  }
304 #endif
305 
306  //Update the length of the LLMNR query message
307  length += sizeof(DnsQuestion);
308 
309  //Adjust the length of the multi-part buffer
310  netBufferSetLength(buffer, offset + length);
311 
312  //Debug message
313  TRACE_INFO("Sending LLMNR message (%" PRIuSIZE " bytes)...\r\n", length);
314  //Dump message
316 
317  //LLMNR queries are sent to and received on port 5355
318  error = udpSendDatagramEx(entry->interface, NULL, entry->port,
319  &destIpAddr, LLMNR_PORT, buffer, offset, IPV4_DEFAULT_TTL);
320 
321  //Free previously allocated memory
322  netBufferFree(buffer);
323 
324  //Return status code
325  return error;
326 }
327 
328 
329 /**
330  * @brief Process LLMNR response message
331  * @param[in] interface Underlying network interface
332  * @param[in] pseudoHeader UDP pseudo header
333  * @param[in] udpHeader UDP header
334  * @param[in] buffer Multi-part buffer containing the incoming LLMNR message
335  * @param[in] offset Offset to the first byte of the LLMNR message
336  * @param[in] param Callback function parameter (not used)
337  **/
338 
339 void llmnrProcessResponse(NetInterface *interface, const IpPseudoHeader *pseudoHeader,
340  const UdpHeader *udpHeader, const NetBuffer *buffer, size_t offset, void *param)
341 {
342  uint_t i;
343  uint_t j;
344  size_t pos;
345  size_t length;
347  DnsQuestion *question;
348  DnsResourceRecord *record;
349  DnsCacheEntry *entry;
350 
351  //Retrieve the length of the LLMNR message
352  length = netBufferGetLength(buffer) - offset;
353 
354  //Ensure the LLMNR message is valid
355  if(length < sizeof(LlmnrHeader))
356  return;
358  return;
359 
360  //Point to the LLMNR message header
361  message = netBufferAt(buffer, offset);
362  //Sanity check
363  if(message == NULL)
364  return;
365 
366  //Debug message
367  TRACE_INFO("LLMNR message received (%" PRIuSIZE " bytes)...\r\n", length);
368  //Dump message
370 
371  //Discard LLMNR queries
372  if(!message->qr)
373  return;
374 
375  //LLMNR messages received with an opcode other than zero must be silently
376  //ignored
377  if(message->opcode != DNS_OPCODE_QUERY)
378  return;
379 
380  //LLMNR messages received with non-zero response codes must be silently
381  //ignored
382  if(message->rcode != DNS_RCODE_NO_ERROR)
383  return;
384 
385  //LLMNR senders must silently discard LLMNR responses with QDCOUNT not
386  //equal to one (refer to RFC 4795, section 2.1.1)
387  if(ntohs(message->qdcount) != 1)
388  return;
389 
390  //Loop through DNS cache entries
391  for(i = 0; i < DNS_CACHE_SIZE; i++)
392  {
393  //Point to the current entry
394  entry = &dnsCache[i];
395 
396  //LLMNR name resolution in progress?
397  if(entry->state == DNS_STATE_IN_PROGRESS &&
399  {
400  //Check destination port number
401  if(entry->port == ntohs(udpHeader->destPort))
402  {
403  //Compare identifier against the expected one
404  if(ntohs(message->id) != entry->id)
405  break;
406 
407  //Point to the first question
408  pos = sizeof(DnsHeader);
409  //Parse domain name
410  pos = dnsParseName((DnsHeader *) message, length, pos, NULL, 0);
411 
412  //Invalid name?
413  if(!pos)
414  break;
415  //Malformed DNS message?
416  if((pos + sizeof(DnsQuestion)) > length)
417  break;
418 
419  //Compare domain name
421  entry->name, 0))
422  {
423  break;
424  }
425 
426  //Point to the corresponding entry
427  question = DNS_GET_QUESTION(message, pos);
428 
429  //Check the class of the query
430  if(ntohs(question->qclass) != DNS_RR_CLASS_IN)
431  break;
432 
433  //Check the type of the query
434  if(entry->type == HOST_TYPE_IPV4 && ntohs(question->qtype) != DNS_RR_TYPE_A)
435  break;
436  if(entry->type == HOST_TYPE_IPV6 && ntohs(question->qtype) != DNS_RR_TYPE_AAAA)
437  break;
438 
439  //Point to the first answer
440  pos += sizeof(DnsQuestion);
441 
442  //Parse answer resource records
443  for(j = 0; j < ntohs(message->ancount); j++)
444  {
445  //Parse domain name
446  pos = dnsParseName((DnsHeader *) message, length, pos, NULL, 0);
447  //Invalid name?
448  if(!pos)
449  break;
450 
451  //Point to the associated resource record
452  record = DNS_GET_RESOURCE_RECORD(message, pos);
453  //Point to the resource data
454  pos += sizeof(DnsResourceRecord);
455 
456  //Make sure the resource record is valid
457  if(pos > length)
458  break;
459  if((pos + ntohs(record->rdlength)) > length)
460  break;
461 
462 #if (IPV4_SUPPORT == ENABLED)
463  //IPv4 address expected?
464  if(entry->type == HOST_TYPE_IPV4)
465  {
466  //A resource record found?
467  if(ntohs(record->rtype) == DNS_RR_TYPE_A &&
468  ntohs(record->rdlength) == sizeof(Ipv4Addr))
469  {
470  //Copy the IPv4 address
471  entry->ipAddr.length = sizeof(Ipv4Addr);
472  ipv4CopyAddr(&entry->ipAddr.ipv4Addr, record->rdata);
473 
474  //Save current time
475  entry->timestamp = osGetSystemTime();
476  //Save TTL value
477  entry->timeout = ntohl(record->ttl) * 1000;
478  //Limit the lifetime of the NBNS cache entries
479  entry->timeout = MIN(entry->timeout, LLMNR_MAX_LIFETIME);
480 
481  //Unregister UDP callback function
482  udpDetachRxCallback(interface, entry->port);
483  //Host name successfully resolved
484  entry->state = DNS_STATE_RESOLVED;
485  //Exit immediately
486  break;
487  }
488  }
489 #endif
490 #if (IPV6_SUPPORT == ENABLED)
491  //IPv6 address expected?
492  if(entry->type == HOST_TYPE_IPV6)
493  {
494  //AAAA resource record found?
495  if(ntohs(record->rtype) == DNS_RR_TYPE_AAAA &&
496  ntohs(record->rdlength) == sizeof(Ipv6Addr))
497  {
498  //Copy the IPv6 address
499  entry->ipAddr.length = sizeof(Ipv6Addr);
500  ipv6CopyAddr(&entry->ipAddr.ipv6Addr, record->rdata);
501 
502  //Save current time
503  entry->timestamp = osGetSystemTime();
504  //Save TTL value
505  entry->timeout = ntohl(record->ttl) * 1000;
506  //Limit the lifetime of the NBNS cache entries
507  entry->timeout = MIN(entry->timeout, LLMNR_MAX_LIFETIME);
508 
509  //Unregister UDP callback function
510  udpDetachRxCallback(interface, entry->port);
511  //Host name successfully resolved
512  entry->state = DNS_STATE_RESOLVED;
513  //Exit immediately
514  break;
515  }
516  }
517 #endif
518  //Point to the next resource record
519  pos += ntohs(record->rdlength);
520  }
521 
522  //We are done
523  break;
524  }
525  }
526  }
527 }
528 
529 #endif
#define DNS_GET_QUESTION(message, offset)
Definition: dns_common.h:63
uint32_t Ipv4Addr
IPv4 network address.
Definition: ipv4.h:235
#define DNS_GET_RESOURCE_RECORD(message, offset)
Definition: dns_common.h:64
uint32_t systime_t
Definition: compiler_port.h:46
__start_packed struct @147 DnsQuestion
Question format.
IPv6 address.
Definition: dns_common.h:133
DnsCacheEntry dnsCache[DNS_CACHE_SIZE]
Definition: dns_cache.c:51
#define ipv6CopyAddr(destIpAddr, srcIpAddr)
Definition: ipv6.h:117
char char_t
Definition: compiler_port.h:43
HostnameResolver protocol
Name resolution protocol.
Definition: dns_cache.h:100
__start_packed struct @146 DnsHeader
DNS message header.
Ipv4Addr ipv4Addr
Definition: ip.h:77
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.
Internet.
Definition: dns_common.h:110
size_t netBufferGetLength(const NetBuffer *buffer)
Get the actual length of a multi-part buffer.
Definition: net_mem.c:297
#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
Invalid parameter.
Definition: error.h:47
HostType type
IPv4 or IPv6 host?
Definition: dns_cache.h:99
IP network address.
Definition: ip.h:71
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
char_t type
#define htons(value)
Definition: cpu_endian.h:392
__start_packed struct @122 UdpHeader
UDP header.
error_t llmnrResolve(NetInterface *interface, const char_t *name, HostType type, IpAddr *ipAddr)
Resolve a host name using LLMNR.
Definition: llmnr_client.c:54
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, uint_t flags)
Send a UDP datagram (raw interface)
Definition: udp.c:457
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)
uint16_t port
Port number used by the resolver.
Definition: dns_cache.h:103
#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
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
uint32_t netGetRand(void)
Get a random value.
Definition: net.c:1540
DNS cache entry.
Definition: dns_cache.h:96
#define LLMNR_CLIENT_INIT_TIMEOUT
Definition: llmnr_client.h:58
HostType
Host types.
Definition: socket.h:171
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[]
void llmnrProcessResponse(NetInterface *interface, const IpPseudoHeader *pseudoHeader, const UdpHeader *udpHeader, const NetBuffer *buffer, size_t offset, void *param)
Process LLMNR response message.
Definition: llmnr_client.c:339
void osDelayTask(systime_t delay)
Delay routine.
error_t udpAttachRxCallback(NetInterface *interface, uint16_t port, UdpRxCallback callback, void *param)
Register user callback.
Definition: udp.c:758
int_t dnsCompareName(const DnsHeader *message, size_t length, size_t pos, const char_t *name, uint_t level)
Compare domain names.
Definition: dns_common.c:240
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 LLMNR_IPV4_MULTICAST_ADDR
Definition: llmnr_common.h:51
#define DNS_CACHE_INIT_POLLING_INTERVAL
Definition: dns_cache.h:61
error_t udpDetachRxCallback(NetInterface *interface, uint16_t port)
Unregister user callback.
Definition: udp.c:805
__start_packed struct @204 LlmnrHeader
LLMNR message header.
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:691
#define TRACE_INFO(...)
Definition: debug.h:94
size_t dnsParseName(const DnsHeader *message, size_t length, size_t pos, char_t *dest, uint_t level)
Decode a domain name that uses the DNS name encoding.
Definition: dns_common.c:130
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
__start_packed struct @148 DnsResourceRecord
Resource record format.
__start_packed struct @179 Ipv6Addr
IPv6 network address.
error_t
Error codes.
Definition: error.h:42
Ipv4Addr destIpAddr
Definition: ipcp.h:78
size_t dnsEncodeName(const char_t *src, uint8_t *dest)
Encode a domain name using the DNS name notation.
Definition: dns_common.c:56
size_t length
Definition: ip.h:73
unsigned int uint_t
Definition: compiler_port.h:45
void osReleaseMutex(OsMutex *mutex)
Release ownership of the specified mutex object.
Ipv6Addr ipv6Addr
Definition: ip.h:80
#define PRIuSIZE
Definition: compiler_port.h:78
#define NetInterface
Definition: net.h:36
uint16_t udpGetDynamicPort(void)
Get an ephemeral port number.
Definition: udp.c:89
IP pseudo header.
Definition: ip.h:90
error_t llmnrSendQuery(DnsCacheEntry *entry)
Send a LLMNR query message.
Definition: llmnr_client.c:215
Definitions common to LLMNR client and responder.
LLMNR client (Link-Local Multicast Name Resolution)
OsMutex netMutex
Definition: net.c:72
const Ipv6Addr LLMNR_IPV6_MULTICAST_ADDR
Definition: llmnr_common.c:45
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
Host address.
Definition: dns_common.h:123
void osAcquireMutex(OsMutex *mutex)
Acquire ownership of the specified mutex object.
#define ipv4CopyAddr(destIpAddr, srcIpAddr)
Definition: ipv4.h:142
#define DNS_CACHE_SIZE
Definition: dns_cache.h:47