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-2026 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.6.2
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
66  netLock(interface->netContext);
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 if(entry->state == DNS_STATE_FAILED)
85  {
86  //The entry should be deleted since name resolution has failed
87  if(entry->refCount == 0)
88  {
89  //The entry should be deleted since name resolution has failed
90  dnsDeleteEntry(entry);
91  }
92 
93  //Report an error
94  error = ERROR_FAILURE;
95  }
96  else
97  {
98 #if (NET_RTOS_SUPPORT == ENABLED)
99  //Increment the reference count
100  entry->refCount++;
101 #endif
102  //Host name resolution is in progress
103  error = ERROR_IN_PROGRESS;
104  }
105  }
106  else
107  {
108  //If no entry exists, then create a new one
109  entry = dnsCreateEntry();
110 
111  //Record the host name whose IP address is unknown
112  osStrcpy(entry->name, name);
113 
114  //Initialize DNS cache entry
115  entry->type = HOST_TYPE_IPV4;
117  entry->interface = interface;
118 
119  //Initialize retransmission counter
121  //Send NBNS query
122  error = nbnsSendQuery(entry);
123 
124  //NBNS message successfully sent?
125  if(!error)
126  {
127  //Save the time at which the query message was sent
128  entry->timestamp = osGetSystemTime();
129  //Set timeout value
132  //Decrement retransmission counter
133  entry->retransmitCount--;
134 
135  //Switch state
136  entry->state = DNS_STATE_IN_PROGRESS;
137 
138 #if (NET_RTOS_SUPPORT == ENABLED)
139  //Initialize the reference count
140  entry->refCount = 1;
141 #endif
142  //Host name resolution is in progress
143  error = ERROR_IN_PROGRESS;
144  }
145  }
146 
147  //Release exclusive access
148  netUnlock(interface->netContext);
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
161  netLock(interface->netContext);
162 
163  //Search the DNS cache for the specified host name
164  entry = dnsFindEntry(interface, name, HOST_TYPE_IPV4,
166 
167  //Check whether a matching entry has been found
168  if(entry != NULL)
169  {
170  //Host name successfully resolved?
171  if(entry->state == DNS_STATE_RESOLVED)
172  {
173  //Return the corresponding IP address
174  *ipAddr = entry->ipAddr;
175  //Successful host name resolution
176  error = NO_ERROR;
177  }
178  else if(entry->state == DNS_STATE_FAILED)
179  {
180  //Decrement the reference count
181  if(entry->refCount > 0)
182  {
183  entry->refCount--;
184  }
185 
186  //The entry should be deleted since name resolution has failed
187  if(entry->refCount == 0)
188  {
189  dnsDeleteEntry(entry);
190  }
191 
192  //Report an error
193  error = ERROR_FAILURE;
194  }
195  else
196  {
197  //Host name resolution is in progress
198  }
199  }
200  else
201  {
202  //Host name resolution failed
203  error = ERROR_FAILURE;
204  }
205 
206  //Release exclusive access
207  netUnlock(interface->netContext);
208 
209  //Backoff support for less aggressive polling
210  delay = MIN(delay * 2, DNS_CACHE_MAX_POLLING_INTERVAL);
211  }
212 
213  //Check status code
214  if(error)
215  {
216  //Failed to resolve host name
217  TRACE_INFO("Host name resolution failed!\r\n");
218  }
219  else
220  {
221  //Successful host name resolution
222  TRACE_INFO("Host name resolved to %s...\r\n", ipAddrToString(ipAddr, NULL));
223  }
224 #endif
225 
226  //Return status code
227  return error;
228 }
229 
230 
231 /**
232  * @brief Send a NBNS query message
233  * @param[in] entry Pointer to a valid DNS cache entry
234  * @return Error code
235  **/
236 
238 {
239  error_t error;
240  size_t length;
241  size_t offset;
242  NetBuffer *buffer;
244  DnsQuestion *dnsQuestion;
246  NetTxAncillary ancillary;
247 
248  //Allocate a memory buffer to hold the NBNS query message
249  buffer = udpAllocBuffer(DNS_MESSAGE_MAX_SIZE, &offset);
250  //Failed to allocate buffer?
251  if(buffer == NULL)
252  return ERROR_OUT_OF_MEMORY;
253 
254  //Point to the NBNS header
255  message = netBufferAt(buffer, offset, 0);
256 
257  //Format NBNS query message
258  message->id = htons(entry->id);
259  message->qr = 0;
260  message->opcode = DNS_OPCODE_QUERY;
261  message->aa = 0;
262  message->tc = 0;
263  message->rd = 0;
264  message->ra = 0;
265  message->z = 0;
266  message->b = 1;
267  message->rcode = DNS_RCODE_NOERROR;
268 
269  //The NBNS query contains one question
270  message->qdcount = HTONS(1);
271  message->ancount = 0;
272  message->nscount = 0;
273  message->arcount = 0;
274 
275  //Length of the NBNS query message
276  length = sizeof(DnsHeader);
277 
278  //Encode the NetBIOS name
279  length += nbnsEncodeName(entry->name, message->questions);
280 
281  //Point to the corresponding question structure
282  dnsQuestion = DNS_GET_QUESTION(message, length);
283 
284  //Fill in question structure
285  dnsQuestion->qtype = HTONS(DNS_RR_TYPE_NB);
286  dnsQuestion->qclass = HTONS(DNS_RR_CLASS_IN);
287 
288  //Update the length of the NBNS query message
289  length += sizeof(DnsQuestion);
290 
291  //Adjust the length of the multi-part buffer
292  netBufferSetLength(buffer, offset + length);
293 
294  //Debug message
295  TRACE_INFO("Sending NBNS message (%" PRIuSIZE " bytes)...\r\n", length);
296  //Dump message
298 
299  //NBNS only supports IPv4
300  destIpAddr.length = sizeof(Ipv4Addr);
301 
302  //The destination address is the broadcast address
303  error = ipv4GetBroadcastAddr(entry->interface, &destIpAddr.ipv4Addr);
304 
305  //Check status code
306  if(!error)
307  {
308  //Additional options can be passed to the stack along with the packet
309  ancillary = NET_DEFAULT_TX_ANCILLARY;
310 
311  //A request packet is always sent to the well known port 137
312  error = udpSendBuffer(entry->interface->netContext, entry->interface,
313  NULL, NBNS_PORT, &destIpAddr, NBNS_PORT, buffer, offset, &ancillary);
314  }
315 
316  //Free previously allocated memory
317  netBufferFree(buffer);
318 
319  //Return status code
320  return error;
321 }
322 
323 
324 /**
325  * @brief Process NBNS response message
326  * @param[in] interface Underlying network interface
327  * @param[in] pseudoHeader UDP pseudo header
328  * @param[in] udpHeader UDP header
329  * @param[in] message Pointer to the NBNS response message
330  * @param[in] length Length of the message
331  **/
332 
333 void nbnsProcessResponse(NetInterface *interface, const Ipv4PseudoHeader *pseudoHeader,
334  const UdpHeader *udpHeader, const NbnsHeader *message, size_t length)
335 {
336  uint_t i;
337  size_t pos;
338  DnsCacheEntry *entry;
339  DnsResourceRecord *record;
340  NbnsAddrEntry *addrEntry;
341 
342  //The NBNS response shall contain one answer
343  if(ntohs(message->qdcount) != 0 && ntohs(message->ancount) != 1)
344  return;
345 
346  //Parse NetBIOS name
347  pos = nbnsParseName(message, length, sizeof(DnsHeader), NULL);
348  //Invalid name?
349  if(!pos)
350  return;
351 
352  //Point to the associated resource record
353  record = DNS_GET_RESOURCE_RECORD(message, pos);
354  //Point to the resource data
355  pos += sizeof(DnsResourceRecord);
356 
357  //Make sure the resource record is valid
358  if(pos > length)
359  return;
360  if((pos + ntohs(record->rdlength)) > length)
361  return;
362 
363  //Check the class and the type of the resource record
364  if(ntohs(record->rclass) != DNS_RR_CLASS_IN)
365  return;
366  if(ntohs(record->rtype) != DNS_RR_TYPE_NB)
367  return;
368 
369  //Verify the length of the data field
370  if(ntohs(record->rdlength) < sizeof(NbnsAddrEntry))
371  return;
372 
373  //Loop through DNS cache entries
374  for(i = 0; i < DNS_CACHE_SIZE; i++)
375  {
376  //Point to the current entry
377  entry = &dnsCache[i];
378 
379  //NBNS name resolution in progress?
380  if(entry->state == DNS_STATE_IN_PROGRESS &&
381  entry->protocol == HOST_NAME_RESOLVER_NBNS &&
382  entry->type == HOST_TYPE_IPV4)
383  {
384  //Compare identifiers
385  if(entry->id == ntohs(message->id))
386  {
387  //Compare NetBIOS names
388  if(nbnsCompareName(message, length, sizeof(DnsHeader), entry->name))
389  {
390  //Point to the address entry array
391  addrEntry = (NbnsAddrEntry *) record->rdata;
392  //Copy the IPv4 address
393  entry->ipAddr.length = sizeof(Ipv4Addr);
394  entry->ipAddr.ipv4Addr = addrEntry->addr;
395 
396  //Save current time
397  entry->timestamp = osGetSystemTime();
398  //Save TTL value
399  entry->timeout = ntohl(record->ttl) * 1000;
400  //Limit the lifetime of the NBNS cache entries
401  entry->timeout = MIN(entry->timeout, NBNS_MAX_LIFETIME);
402 
403  //Host name successfully resolved
404  entry->state = DNS_STATE_RESOLVED;
405  }
406  }
407  }
408  }
409 }
410 
411 #endif
#define htons(value)
Definition: cpu_endian.h:413
@ DNS_STATE_PERMANENT
Definition: dns_cache.h:89
HostType type
IPv4 or IPv6 host?
Definition: dns_cache.h:101
void netUnlock(NetContext *context)
Release exclusive access to the core of the TCP/IP stack.
Definition: net.c:319
const NetTxAncillary NET_DEFAULT_TX_ANCILLARY
Definition: net_misc.c:70
size_t nbnsParseName(const NbnsHeader *message, size_t length, size_t pos, char_t *dest)
Decode a NetBIOS name.
Definition: nbns_common.c:222
IP network address.
Definition: ip.h:90
@ DNS_OPCODE_QUERY
Query.
Definition: dns_common.h:81
Structure describing a buffer that spans multiple chunks.
Definition: net_mem.h:89
uint8_t message[]
Definition: chap.h:154
NbnsAddrEntry
Definition: nbns_common.h:142
systime_t timeout
Retransmission timeout.
Definition: dns_cache.h:110
void nbnsProcessResponse(NetInterface *interface, const Ipv4PseudoHeader *pseudoHeader, const UdpHeader *udpHeader, const NbnsHeader *message, size_t length)
Process NBNS response message.
Definition: nbns_client.c:333
char_t * ipAddrToString(const IpAddr *ipAddr, char_t *str)
Convert a binary IP address to a string representation.
Definition: ip.c:810
@ ERROR_OUT_OF_MEMORY
Definition: error.h:63
#define NBNS_MAX_LIFETIME
Definition: nbns_client.h:72
#define NBNS_CLIENT_MAX_RETRIES
Definition: nbns_client.h:51
HostnameResolver protocol
Name resolution protocol.
Definition: dns_cache.h:102
@ DNS_RR_CLASS_IN
Internet.
Definition: dns_common.h:124
char_t name[]
DnsHeader
Definition: dns_common.h:202
uint_t refCount
Reference count for the current entry.
Definition: dns_cache.h:100
#define NBNS_PORT
Definition: nbns_common.h:46
IpAddr ipAddr
IP address.
Definition: dns_cache.h:108
uint32_t Ipv4Addr
IPv4 network address.
Definition: ipv4.h:323
error_t nbnsSendQuery(DnsCacheEntry *entry)
Send a NBNS query message.
Definition: nbns_client.c:237
uint16_t id
Identifier used to match queries and responses.
Definition: dns_cache.h:106
@ DNS_RCODE_NOERROR
No error.
Definition: dns_common.h:95
@ ERROR_IN_PROGRESS
Definition: error.h:214
Helper functions for IPv4.
NbnsHeader
Definition: nbns_common.h:131
@ DNS_RR_TYPE_NB
NetBIOS name.
Definition: dns_common.h:148
error_t
Error codes.
Definition: error.h:43
#define DNS_GET_QUESTION(message, offset)
Definition: dns_common.h:63
char_t name[DNS_MAX_NAME_LEN+1]
Domain name.
Definition: dns_cache.h:107
systime_t timestamp
Timestamp to manage entry lifetime.
Definition: dns_cache.h:109
#define DNS_GET_RESOURCE_RECORD(message, offset)
Definition: dns_common.h:64
Definitions common to NBNS client and NBNS responder.
NBNS client (NetBIOS Name Service)
@ ERROR_FAILURE
Generic error code.
Definition: error.h:45
@ DNS_STATE_FAILED
Definition: dns_cache.h:88
#define NBNS_CLIENT_INIT_TIMEOUT
Definition: nbns_client.h:58
#define NetInterface
Definition: net.h:40
void netBufferFree(NetBuffer *buffer)
Dispose a multi-part buffer.
Definition: net_mem.c:282
DNS cache entry.
Definition: dns_cache.h:98
DnsCacheEntry * dnsCreateEntry(void)
Create a new entry in the DNS cache.
Definition: dns_cache.c:101
#define NetTxAncillary
Definition: net_misc.h:36
systime_t maxTimeout
Maximum retransmission timeout.
Definition: dns_cache.h:111
error_t udpSendBuffer(NetContext *context, 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:657
#define Ipv4PseudoHeader
Definition: ipv4.h:39
#define TRACE_INFO(...)
Definition: debug.h:105
uint8_t length
Definition: tcp.h:375
void dnsDumpMessage(const DnsHeader *message, size_t length)
Dump DNS message for debugging purpose.
Definition: dns_debug.c:52
#define MIN(a, b)
Definition: os_port.h:63
NetBuffer * udpAllocBuffer(size_t length, size_t *offset)
Allocate a buffer to hold a UDP packet.
Definition: udp.c:948
size_t length
Definition: ip.h:91
@ HOST_TYPE_IPV4
Definition: socket.h:217
UdpHeader
Definition: udp.h:85
size_t nbnsEncodeName(const char_t *src, uint8_t *dest)
Encode a NetBIOS name.
Definition: nbns_common.c:148
#define DNS_CACHE_INIT_POLLING_INTERVAL
Definition: dns_cache.h:61
uint32_t systime_t
System time.
#define ntohs(value)
Definition: cpu_endian.h:421
char char_t
Definition: compiler_port.h:55
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
Ipv4Addr ipv4Addr
Definition: ip.h:95
#define HTONS(value)
Definition: cpu_endian.h:410
@ DNS_STATE_IN_PROGRESS
Definition: dns_cache.h:86
NetInterface * interface
Underlying network interface.
Definition: dns_cache.h:103
#define DNS_CACHE_SIZE
Definition: dns_cache.h:47
@ DNS_STATE_RESOLVED
Definition: dns_cache.h:87
error_t ipv4GetBroadcastAddr(NetInterface *interface, Ipv4Addr *addr)
Get IPv4 broadcast address.
Definition: ipv4_misc.c:761
#define DNS_MESSAGE_MAX_SIZE
Definition: dns_common.h:45
@ HOST_NAME_RESOLVER_NBNS
Definition: socket.h:231
error_t netBufferSetLength(NetBuffer *buffer, size_t length)
Adjust the length of a multi-part buffer.
Definition: net_mem.c:322
DnsQuestion
Definition: dns_common.h:213
void dnsDeleteEntry(DnsCacheEntry *entry)
Delete the specified DNS cache entry.
Definition: dns_cache.c:151
void netLock(NetContext *context)
Get exclusive access to the core of the TCP/IP stack.
Definition: net.c:307
void osDelayTask(systime_t delay)
Delay routine.
void * netBufferAt(const NetBuffer *buffer, size_t offset, size_t length)
Returns a pointer to a data segment.
Definition: net_mem.c:418
Ipv4Addr ipAddr
Definition: ipcp.h:105
DnsCacheEntry dnsCache[DNS_CACHE_SIZE]
Definition: dns_cache.c:49
DnsState state
Entry state.
Definition: dns_cache.h:99
uint_t retransmitCount
Retransmission counter.
Definition: dns_cache.h:112
#define PRIuSIZE
unsigned int uint_t
Definition: compiler_port.h:57
TCP/IP stack core.
DnsResourceRecord
Definition: dns_common.h:227
Data logging functions for debugging purpose (DNS)
#define osStrcpy(s1, s2)
Definition: os_port.h:210
#define DNS_CACHE_MAX_POLLING_INTERVAL
Definition: dns_cache.h:68
#define ntohl(value)
Definition: cpu_endian.h:422
@ NO_ERROR
Success.
Definition: error.h:44
Debugging facilities.
error_t nbnsResolve(NetInterface *interface, const char_t *name, IpAddr *ipAddr)
Resolve a host name using NBNS.
Definition: nbns_client.c:53
bool_t nbnsCompareName(const NbnsHeader *message, size_t length, size_t pos, const char_t *name)
Compare NetBIOS names.
Definition: nbns_common.c:316
systime_t osGetSystemTime(void)
Retrieve system time.
#define NBNS_CLIENT_MAX_TIMEOUT
Definition: nbns_client.h:65
Ipv4Addr destIpAddr
Definition: ipcp.h:80