nbns_client.c
Go to the documentation of this file.
1 /**
2  * @file nbns_client.c
3  * @brief NBNS client (NetBIOS Name Service)
4  *
5  * @section License
6  *
7  * SPDX-License-Identifier: GPL-2.0-or-later
8  *
9  * Copyright (C) 2010-2024 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 2.4.0
29  **/
30 
31 //Switch to the appropriate trace level
32 #define TRACE_LEVEL NBNS_TRACE_LEVEL
33 
34 //Dependencies
35 #include "core/net.h"
36 #include "ipv4/ipv4_misc.h"
37 #include "netbios/nbns_client.h"
38 #include "netbios/nbns_common.h"
39 #include "dns/dns_debug.h"
40 #include "debug.h"
41 
42 //Check TCP/IP stack configuration
43 #if (NBNS_CLIENT_SUPPORT == ENABLED && IPV4_SUPPORT == ENABLED)
44 
45 
46 /**
47  * @brief Resolve a host name using NBNS
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 (NBNS resolver)...\r\n", name);
63 #endif
64 
65  //Get exclusive access
67 
68  //Search the DNS cache for the specified host name
69  entry = dnsFindEntry(interface, name, HOST_TYPE_IPV4,
71 
72  //Check whether a matching entry has been found
73  if(entry != NULL)
74  {
75  //Host name already resolved?
76  if(entry->state == DNS_STATE_RESOLVED ||
77  entry->state == DNS_STATE_PERMANENT)
78  {
79  //Return the corresponding IP address
80  *ipAddr = entry->ipAddr;
81  //Successful host name resolution
82  error = NO_ERROR;
83  }
84  else
85  {
86  //Host name resolution is in progress
87  error = ERROR_IN_PROGRESS;
88  }
89  }
90  else
91  {
92  //If no entry exists, then create a new one
93  entry = dnsCreateEntry();
94 
95  //Record the host name whose IP address is unknown
96  osStrcpy(entry->name, name);
97 
98  //Initialize DNS cache entry
99  entry->type = HOST_TYPE_IPV4;
101  entry->interface = interface;
102 
103  //Initialize retransmission counter
105  //Send NBNS query
106  error = nbnsSendQuery(entry);
107 
108  //NBNS message successfully sent?
109  if(!error)
110  {
111  //Save the time at which the query message was sent
112  entry->timestamp = osGetSystemTime();
113  //Set timeout value
116  //Decrement retransmission counter
117  entry->retransmitCount--;
118 
119  //Switch state
120  entry->state = DNS_STATE_IN_PROGRESS;
121  //Host name resolution is in progress
122  error = ERROR_IN_PROGRESS;
123  }
124  }
125 
126  //Release exclusive access
128 
129 #if (NET_RTOS_SUPPORT == ENABLED)
130  //Set default polling interval
132 
133  //Wait the host name resolution to complete
134  while(error == ERROR_IN_PROGRESS)
135  {
136  //Wait until the next polling period
137  osDelayTask(delay);
138 
139  //Get exclusive access
141 
142  //Search the DNS cache for the specified host name
143  entry = dnsFindEntry(interface, name, HOST_TYPE_IPV4,
145 
146  //Check whether a matching entry has been found
147  if(entry != NULL)
148  {
149  //Host name successfully resolved?
150  if(entry->state == DNS_STATE_RESOLVED)
151  {
152  //Return the corresponding IP address
153  *ipAddr = entry->ipAddr;
154  //Successful host name resolution
155  error = NO_ERROR;
156  }
157  }
158  else
159  {
160  //Host name resolution failed
161  error = ERROR_FAILURE;
162  }
163 
164  //Release exclusive access
166 
167  //Backoff support for less aggressive polling
168  delay = MIN(delay * 2, DNS_CACHE_MAX_POLLING_INTERVAL);
169  }
170 
171  //Check status code
172  if(error)
173  {
174  //Failed to resolve host name
175  TRACE_INFO("Host name resolution failed!\r\n");
176  }
177  else
178  {
179  //Successful host name resolution
180  TRACE_INFO("Host name resolved to %s...\r\n", ipAddrToString(ipAddr, NULL));
181  }
182 #endif
183 
184  //Return status code
185  return error;
186 }
187 
188 
189 /**
190  * @brief Send a NBNS query message
191  * @param[in] entry Pointer to a valid DNS cache entry
192  * @return Error code
193  **/
194 
196 {
197  error_t error;
198  size_t length;
199  size_t offset;
200  NetBuffer *buffer;
202  DnsQuestion *dnsQuestion;
204  NetTxAncillary ancillary;
205 
206  //Allocate a memory buffer to hold the NBNS query message
207  buffer = udpAllocBuffer(DNS_MESSAGE_MAX_SIZE, &offset);
208  //Failed to allocate buffer?
209  if(buffer == NULL)
210  return ERROR_OUT_OF_MEMORY;
211 
212  //Point to the NBNS header
213  message = netBufferAt(buffer, offset);
214 
215  //Format NBNS query message
216  message->id = htons(entry->id);
217  message->qr = 0;
218  message->opcode = DNS_OPCODE_QUERY;
219  message->aa = 0;
220  message->tc = 0;
221  message->rd = 0;
222  message->ra = 0;
223  message->z = 0;
224  message->b = 1;
225  message->rcode = DNS_RCODE_NOERROR;
226 
227  //The NBNS query contains one question
228  message->qdcount = HTONS(1);
229  message->ancount = 0;
230  message->nscount = 0;
231  message->arcount = 0;
232 
233  //Length of the NBNS query message
234  length = sizeof(DnsHeader);
235 
236  //Encode the NetBIOS name
237  length += nbnsEncodeName(entry->name, message->questions);
238 
239  //Point to the corresponding question structure
240  dnsQuestion = DNS_GET_QUESTION(message, length);
241  //Fill in question structure
242  dnsQuestion->qtype = HTONS(DNS_RR_TYPE_NB);
243  dnsQuestion->qclass = HTONS(DNS_RR_CLASS_IN);
244 
245  //Update the length of the NBNS query message
246  length += sizeof(DnsQuestion);
247 
248  //Adjust the length of the multi-part buffer
249  netBufferSetLength(buffer, offset + length);
250 
251  //Debug message
252  TRACE_INFO("Sending NBNS message (%" PRIuSIZE " bytes)...\r\n", length);
253  //Dump message
255 
256  //The destination address is the broadcast address
257  destIpAddr.length = sizeof(Ipv4Addr);
258  ipv4GetBroadcastAddr(entry->interface, &destIpAddr.ipv4Addr);
259 
260  //Additional options can be passed to the stack along with the packet
261  ancillary = NET_DEFAULT_TX_ANCILLARY;
262 
263  //A request packet is always sent to the well known port 137
264  error = udpSendBuffer(entry->interface, NULL, NBNS_PORT, &destIpAddr,
265  NBNS_PORT, buffer, offset, &ancillary);
266 
267  //Free previously allocated memory
268  netBufferFree(buffer);
269 
270  //Return status code
271  return error;
272 }
273 
274 
275 /**
276  * @brief Process NBNS response message
277  * @param[in] interface Underlying network interface
278  * @param[in] pseudoHeader UDP pseudo header
279  * @param[in] udpHeader UDP header
280  * @param[in] message Pointer to the NBNS response message
281  * @param[in] length Length of the message
282  **/
283 
284 void nbnsProcessResponse(NetInterface *interface, const Ipv4PseudoHeader *pseudoHeader,
285  const UdpHeader *udpHeader, const NbnsHeader *message, size_t length)
286 {
287  uint_t i;
288  size_t pos;
289  DnsCacheEntry *entry;
290  DnsResourceRecord *record;
291  NbnsAddrEntry *addrEntry;
292 
293  //The NBNS response shall contain one answer
294  if(ntohs(message->qdcount) != 0 && ntohs(message->ancount) != 1)
295  return;
296 
297  //Parse NetBIOS name
298  pos = nbnsParseName(message, length, sizeof(DnsHeader), NULL);
299  //Invalid name?
300  if(!pos)
301  return;
302 
303  //Point to the associated resource record
304  record = DNS_GET_RESOURCE_RECORD(message, pos);
305  //Point to the resource data
306  pos += sizeof(DnsResourceRecord);
307 
308  //Make sure the resource record is valid
309  if(pos > length)
310  return;
311  if((pos + ntohs(record->rdlength)) > length)
312  return;
313 
314  //Check the class and the type of the resource record
315  if(ntohs(record->rclass) != DNS_RR_CLASS_IN)
316  return;
317  if(ntohs(record->rtype) != DNS_RR_TYPE_NB)
318  return;
319 
320  //Verify the length of the data field
321  if(ntohs(record->rdlength) < sizeof(NbnsAddrEntry))
322  return;
323 
324  //Loop through DNS cache entries
325  for(i = 0; i < DNS_CACHE_SIZE; i++)
326  {
327  //Point to the current entry
328  entry = &dnsCache[i];
329 
330  //NBNS name resolution in progress?
331  if(entry->state == DNS_STATE_IN_PROGRESS &&
332  entry->protocol == HOST_NAME_RESOLVER_NBNS &&
333  entry->type == HOST_TYPE_IPV4)
334  {
335  //Compare identifiers
336  if(entry->id == ntohs(message->id))
337  {
338  //Compare NetBIOS names
339  if(nbnsCompareName(message, length, sizeof(DnsHeader), entry->name))
340  {
341  //Point to the address entry array
342  addrEntry = (NbnsAddrEntry *) record->rdata;
343  //Copy the IPv4 address
344  entry->ipAddr.length = sizeof(Ipv4Addr);
345  entry->ipAddr.ipv4Addr = addrEntry->addr;
346 
347  //Save current time
348  entry->timestamp = osGetSystemTime();
349  //Save TTL value
350  entry->timeout = ntohl(record->ttl) * 1000;
351  //Limit the lifetime of the NBNS cache entries
352  entry->timeout = MIN(entry->timeout, NBNS_MAX_LIFETIME);
353 
354  //Host name successfully resolved
355  entry->state = DNS_STATE_RESOLVED;
356  }
357  }
358  }
359  }
360 }
361 
362 #endif
uint8_t message[]
Definition: chap.h:154
unsigned int uint_t
Definition: compiler_port.h:50
#define PRIuSIZE
char char_t
Definition: compiler_port.h:48
#define HTONS(value)
Definition: cpu_endian.h:410
#define ntohl(value)
Definition: cpu_endian.h:422
#define htons(value)
Definition: cpu_endian.h:413
#define ntohs(value)
Definition: cpu_endian.h:421
Debugging facilities.
#define TRACE_INFO(...)
Definition: debug.h:95
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:187
DnsCacheEntry dnsCache[DNS_CACHE_SIZE]
Definition: dns_cache.c:52
DnsCacheEntry * dnsCreateEntry(void)
Create a new entry in the DNS cache.
Definition: dns_cache.c:104
#define DNS_CACHE_SIZE
Definition: dns_cache.h:47
#define DNS_CACHE_INIT_POLLING_INTERVAL
Definition: dns_cache.h:61
@ DNS_STATE_RESOLVED
Definition: dns_cache.h:87
@ DNS_STATE_PERMANENT
Definition: dns_cache.h:88
@ DNS_STATE_IN_PROGRESS
Definition: dns_cache.h:86
#define DNS_CACHE_MAX_POLLING_INTERVAL
Definition: dns_cache.h:68
DnsHeader
Definition: dns_common.h:199
#define DNS_GET_RESOURCE_RECORD(message, offset)
Definition: dns_common.h:64
DnsResourceRecord
Definition: dns_common.h:224
#define DNS_GET_QUESTION(message, offset)
Definition: dns_common.h:63
@ DNS_RCODE_NOERROR
No error.
Definition: dns_common.h:95
#define DNS_MESSAGE_MAX_SIZE
Definition: dns_common.h:45
@ DNS_OPCODE_QUERY
Query.
Definition: dns_common.h:81
@ DNS_RR_TYPE_NB
NetBIOS name service.
Definition: dns_common.h:148
@ DNS_RR_CLASS_IN
Internet.
Definition: dns_common.h:124
DnsQuestion
Definition: dns_common.h:210
void dnsDumpMessage(const DnsHeader *message, size_t length)
Dump DNS message for debugging purpose.
Definition: dns_debug.c:52
Data logging functions for debugging purpose (DNS)
error_t
Error codes.
Definition: error.h:43
@ ERROR_IN_PROGRESS
Definition: error.h:213
@ NO_ERROR
Success.
Definition: error.h:44
@ ERROR_OUT_OF_MEMORY
Definition: error.h:63
@ ERROR_FAILURE
Generic error code.
Definition: error.h:45
char_t * ipAddrToString(const IpAddr *ipAddr, char_t *str)
Convert a binary IP address to a string representation.
Definition: ip.c:838
Ipv4Addr ipAddr
Definition: ipcp.h:105
Ipv4Addr destIpAddr
Definition: ipcp.h:80
#define Ipv4PseudoHeader
Definition: ipv4.h:39
uint32_t Ipv4Addr
IPv4 network address.
Definition: ipv4.h:267
error_t ipv4GetBroadcastAddr(NetInterface *interface, Ipv4Addr *addr)
Get IPv4 broadcast address.
Definition: ipv4_misc.c:747
Helper functions for IPv4.
error_t nbnsResolve(NetInterface *interface, const char_t *name, IpAddr *ipAddr)
Resolve a host name using NBNS.
Definition: nbns_client.c:53
void nbnsProcessResponse(NetInterface *interface, const Ipv4PseudoHeader *pseudoHeader, const UdpHeader *udpHeader, const NbnsHeader *message, size_t length)
Process NBNS response message.
Definition: nbns_client.c:284
error_t nbnsSendQuery(DnsCacheEntry *entry)
Send a NBNS query message.
Definition: nbns_client.c:195
NBNS client (NetBIOS Name Service)
#define NBNS_CLIENT_MAX_TIMEOUT
Definition: nbns_client.h:65
#define NBNS_MAX_LIFETIME
Definition: nbns_client.h:72
#define NBNS_CLIENT_INIT_TIMEOUT
Definition: nbns_client.h:58
#define NBNS_CLIENT_MAX_RETRIES
Definition: nbns_client.h:51
size_t nbnsEncodeName(const char_t *src, uint8_t *dest)
Encode a NetBIOS name.
Definition: nbns_common.c:150
size_t nbnsParseName(const NbnsHeader *message, size_t length, size_t pos, char_t *dest)
Decode a NetBIOS name.
Definition: nbns_common.c:202
bool_t nbnsCompareName(const NbnsHeader *message, size_t length, size_t pos, const char_t *name)
Compare NetBIOS names.
Definition: nbns_common.c:286
Definitions common to NBNS client and NBNS responder.
NbnsAddrEntry
Definition: nbns_common.h:124
NbnsHeader
Definition: nbns_common.h:113
#define NBNS_PORT
Definition: nbns_common.h:46
TCP/IP stack core.
#define NetInterface
Definition: net.h:36
#define netMutex
Definition: net_legacy.h:195
void * netBufferAt(const NetBuffer *buffer, size_t offset)
Returns a pointer to the data at the specified position.
Definition: net_mem.c:415
void netBufferFree(NetBuffer *buffer)
Dispose a multi-part buffer.
Definition: net_mem.c:282
error_t netBufferSetLength(NetBuffer *buffer, size_t length)
Adjust the length of a multi-part buffer.
Definition: net_mem.c:322
const NetTxAncillary NET_DEFAULT_TX_ANCILLARY
Definition: net_misc.c:71
#define NetTxAncillary
Definition: net_misc.h:36
#define MIN(a, b)
Definition: os_port.h:63
#define osStrcpy(s1, s2)
Definition: os_port.h:207
void osAcquireMutex(OsMutex *mutex)
Acquire ownership of the specified mutex object.
void osDelayTask(systime_t delay)
Delay routine.
void osReleaseMutex(OsMutex *mutex)
Release ownership of the specified mutex object.
systime_t osGetSystemTime(void)
Retrieve system time.
uint32_t systime_t
System time.
char_t name[]
@ HOST_TYPE_IPV4
Definition: socket.h:206
@ HOST_NAME_RESOLVER_NBNS
Definition: socket.h:220
DNS cache entry.
Definition: dns_cache.h:97
systime_t timestamp
Time stamp to manage entry lifetime.
Definition: dns_cache.h:107
uint16_t id
Identifier used to match queries and responses.
Definition: dns_cache.h:104
systime_t maxTimeout
Maximum retransmission timeout.
Definition: dns_cache.h:109
HostnameResolver protocol
Name resolution protocol.
Definition: dns_cache.h:100
HostType type
IPv4 or IPv6 host?
Definition: dns_cache.h:99
uint_t retransmitCount
Retransmission counter.
Definition: dns_cache.h:110
DnsState state
Entry state.
Definition: dns_cache.h:98
systime_t timeout
Retransmission timeout.
Definition: dns_cache.h:108
char_t name[DNS_MAX_NAME_LEN+1]
Domain name.
Definition: dns_cache.h:105
NetInterface * interface
Underlying network interface.
Definition: dns_cache.h:101
IpAddr ipAddr
IP address.
Definition: dns_cache.h:106
IP network address.
Definition: ip.h:79
Ipv4Addr ipv4Addr
Definition: ip.h:84
size_t length
Definition: ip.h:80
Structure describing a buffer that spans multiple chunks.
Definition: net_mem.h:89
uint8_t length
Definition: tcp.h:368
NetBuffer * udpAllocBuffer(size_t length, size_t *offset)
Allocate a buffer to hold a UDP packet.
Definition: udp.c:905
error_t udpSendBuffer(NetInterface *interface, const IpAddr *srcIpAddr, uint16_t srcPort, const IpAddr *destIpAddr, uint16_t destPort, NetBuffer *buffer, size_t offset, NetTxAncillary *ancillary)
Send a UDP datagram.
Definition: udp.c:627
UdpHeader
Definition: udp.h:85