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