auto_ip.c
Go to the documentation of this file.
1 /**
2  * @file auto_ip.c
3  * @brief Auto-IP (Dynamic Configuration of IPv4 Link-Local Addresses)
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  * @section Description
28  *
29  * Auto-IP describes a method by which a host may automatically configure an
30  * interface with an IPv4 address in the 169.254/16 prefix that is valid for
31  * Link-Local communication on that interface. This is especially valuable in
32  * environments where no other configuration mechanism is available. Refer to
33  * the following RFCs for complete details:
34  * - RFC 3927: Dynamic Configuration of IPv4 Link-Local Addresses
35  * - RFC 5227: IPv4 Address Conflict Detection
36  *
37  * @author Oryx Embedded SARL (www.oryx-embedded.com)
38  * @version 1.9.6
39  **/
40 
41 //Switch to the appropriate trace level
42 #define TRACE_LEVEL AUTO_IP_TRACE_LEVEL
43 
44 //Dependencies
45 #include "core/net.h"
46 #include "core/ethernet.h"
47 #include "ipv4/arp.h"
48 #include "ipv4/auto_ip.h"
49 #include "mdns/mdns_responder.h"
50 #include "debug.h"
51 
52 //Check TCP/IP stack configuration
53 #if (IPV4_SUPPORT == ENABLED && AUTO_IP_SUPPORT == ENABLED)
54 
55 //Tick counter to handle periodic operations
57 
58 
59 /**
60  * @brief Initialize settings with default values
61  * @param[out] settings Structure that contains Auto-IP settings
62  **/
63 
65 {
66  //Use default interface
67  settings->interface = netGetDefaultInterface();
68  //Index of the IP address to be configured
69  settings->ipAddrIndex = 0;
70 
71  //Initial link-local address to be used
73  //Link state change event
74  settings->linkChangeEvent = NULL;
75  //FSM state change event
76  settings->stateChangeEvent = NULL;
77 }
78 
79 
80 /**
81  * @brief Auto-IP initialization
82  * @param[in] context Pointer to the Auto-IP context
83  * @param[in] settings Auto-IP specific settings
84  * @return Error code
85  **/
86 
87 error_t autoIpInit(AutoIpContext *context, const AutoIpSettings *settings)
88 {
89  NetInterface *interface;
90 
91  //Debug message
92  TRACE_INFO("Initializing Auto-IP...\r\n");
93 
94  //Ensure the parameters are valid
95  if(context == NULL || settings == NULL)
97 
98  //A valid pointer to the interface being configured is required
99  if(settings->interface == NULL)
101 
102  //Point to the underlying network interface
103  interface = settings->interface;
104 
105  //Clear the Auto-IP context
106  memset(context, 0, sizeof(AutoIpContext));
107  //Save user settings
108  context->settings = *settings;
109 
110  //Use default link-local address
111  context->linkLocalAddr = settings->linkLocalAddr;
112  //Reset conflict counter
113  context->conflictCount = 0;
114 
115  //Auto-IP operation is currently suspended
116  context->running = FALSE;
117  //Initialize state machine
118  context->state = AUTO_IP_STATE_INIT;
119 
120  //Attach the Auto-IP context to the network interface
121  interface->autoIpContext = context;
122 
123  //Successful initialization
124  return NO_ERROR;
125 }
126 
127 
128 /**
129  * @brief Start Auto-IP process
130  * @param[in] context Pointer to the Auto-IP context
131  * @return Error code
132  **/
133 
135 {
136  uint_t i;
137  NetInterface *interface;
138 
139  //Check parameter
140  if(context == NULL)
142 
143  //Debug message
144  TRACE_INFO("Starting Auto-IP...\r\n");
145 
146  //Get exclusive access
148 
149  //Point to the underlying network interface
150  interface = context->settings.interface;
151  //Index of the IP address in the list of addresses assigned to the interface
152  i = context->settings.ipAddrIndex;
153 
154  //The host address is not longer valid
155  interface->ipv4Context.addrList[i].addr = IPV4_UNSPECIFIED_ADDR;
156  interface->ipv4Context.addrList[i].state = IPV4_ADDR_STATE_INVALID;
157 
158  //Clear subnet mask
159  interface->ipv4Context.addrList[i].subnetMask = IPV4_UNSPECIFIED_ADDR;
160 
161  //Start Auto-IP operation
162  context->running = TRUE;
163  //Initialize state machine
164  context->state = AUTO_IP_STATE_INIT;
165  //Reset conflict counter
166  context->conflictCount = 0;
167 
168  //Release exclusive access
170 
171  //Successful processing
172  return NO_ERROR;
173 }
174 
175 
176 /**
177  * @brief Stop Auto-IP process
178  * @param[in] context Pointer to the Auto-IP context
179  * @return Error code
180  **/
181 
183 {
184  //Check parameter
185  if(context == NULL)
187 
188  //Debug message
189  TRACE_INFO("Stopping Auto-IP...\r\n");
190 
191  //Get exclusive access
193 
194  //Suspend Auto-IP operation
195  context->running = FALSE;
196  //Reinitialize state machine
197  context->state = AUTO_IP_STATE_INIT;
198 
199  //Release exclusive access
201 
202  //Successful processing
203  return NO_ERROR;
204 }
205 
206 
207 /**
208  * @brief Retrieve current state
209  * @param[in] context Pointer to the Auto-IP context
210  * @return Current Auto-IP state
211  **/
212 
214 {
215  AutoIpState state;
216 
217  //Get exclusive access
219  //Get current state
220  state = context->state;
221  //Release exclusive access
223 
224  //Return current state
225  return state;
226 }
227 
228 
229 /**
230  * @brief Auto-IP timer handler
231  *
232  * This routine must be periodically called by the TCP/IP stack to
233  * manage Auto-IP operation
234  *
235  * @param[in] context Pointer to the Auto-IP context
236  **/
237 
238 void autoIpTick(AutoIpContext *context)
239 {
240  uint_t i;
241  systime_t time;
242  systime_t delay;
243  NetInterface *interface;
244 
245  //Make sure Auto-IP has been properly instantiated
246  if(context == NULL)
247  return;
248 
249  //Point to the underlying network interface
250  interface = context->settings.interface;
251  //Index of the IP address in the list of addresses assigned to the interface
252  i = context->settings.ipAddrIndex;
253 
254  //Get current time
255  time = osGetSystemTime();
256 
257  //Check current state
258  if(context->state == AUTO_IP_STATE_INIT)
259  {
260  //Wait for the link to be up before starting Auto-IP
261  if(context->running && interface->linkState)
262  {
263  //Configure subnet mask
264  interface->ipv4Context.addrList[i].subnetMask = AUTO_IP_MASK;
265 
266  //The address must be in the range from 169.54.1.0 to 169.254.254.255
267  if(ntohl(context->linkLocalAddr) < ntohl(AUTO_IP_ADDR_MIN) ||
268  ntohl(context->linkLocalAddr) > ntohl(AUTO_IP_ADDR_MAX))
269  {
270  //Generate a random link-local address
271  autoIpGenerateAddr(&context->linkLocalAddr);
272  }
273 
274  //Use the link-local address as a tentative address
275  interface->ipv4Context.addrList[i].addr = context->linkLocalAddr;
276  interface->ipv4Context.addrList[i].state = IPV4_ADDR_STATE_TENTATIVE;
277 
278  //Clear conflict flag
279  interface->ipv4Context.addrList[i].conflict = FALSE;
280 
281  //Initial random delay
283 
284  //The number of conflicts exceeds the maximum acceptable value?
285  if(context->conflictCount >= AUTO_IP_MAX_CONFLICTS)
286  {
287  //The host must limit the rate at which it probes for new addresses
289  }
290 
291  //Verify the uniqueness of the link-local address
292  autoIpChangeState(context, AUTO_IP_STATE_PROBING, delay);
293  }
294  }
295  else if(context->state == AUTO_IP_STATE_PROBING)
296  {
297  //Any conflict detected?
298  if(interface->ipv4Context.addrList[i].conflict)
299  {
300  //The address is already in use by some other host and
301  //must not be assigned to the interface
302  interface->ipv4Context.addrList[i].addr = IPV4_UNSPECIFIED_ADDR;
303  interface->ipv4Context.addrList[i].state = IPV4_ADDR_STATE_INVALID;
304 
305  //The host should maintain a counter of the number of address
306  //conflicts it has experienced
307  context->conflictCount++;
308 
309  //The host must pick a new random address...
310  autoIpGenerateAddr(&context->linkLocalAddr);
311  //...and repeat the process
313  }
314  else
315  {
316  //Check current time
317  if(timeCompare(time, context->timestamp + context->timeout) >= 0)
318  {
319  //Address Conflict Detection is on-going?
320  if(context->retransmitCount < AUTO_IP_PROBE_NUM)
321  {
322  //Conflict detection is done using ARP probes
323  arpSendProbe(interface, context->linkLocalAddr);
324 
325  //Save the time at which the packet was sent
326  context->timestamp = time;
327  //Increment retransmission counter
328  context->retransmitCount++;
329 
330  //Last probe packet sent?
331  if(context->retransmitCount == AUTO_IP_PROBE_NUM)
332  {
333  //Delay before announcing
334  context->timeout = AUTO_IP_ANNOUNCE_WAIT;
335  }
336  else
337  {
338  //Maximum delay till repeated probe
339  context->timeout = netGetRandRange(AUTO_IP_PROBE_MIN,
341  }
342  }
343  else
344  {
345  //The use of the IPv4 address is now unrestricted
346  interface->ipv4Context.addrList[i].state = IPV4_ADDR_STATE_VALID;
347 
348 #if (MDNS_RESPONDER_SUPPORT == ENABLED)
349  //Restart mDNS probing process
350  mdnsResponderStartProbing(interface->mdnsResponderContext);
351 #endif
352  //The host must then announce its claimed address
354  }
355  }
356  }
357  }
358  else if(context->state == AUTO_IP_STATE_ANNOUNCING)
359  {
360  //Check current time
361  if(timeCompare(time, context->timestamp + context->timeout) >= 0)
362  {
363  //An ARP announcement is identical to an ARP probe, except that
364  //now the sender and target IP addresses are both set to the
365  //host's newly selected IPv4 address
366  arpSendRequest(interface, context->linkLocalAddr, &MAC_BROADCAST_ADDR);
367 
368  //Save the time at which the packet was sent
369  context->timestamp = time;
370  //Time interval between announcement packets
371  context->timeout = AUTO_IP_ANNOUNCE_INTERVAL;
372  //Increment retransmission counter
373  context->retransmitCount++;
374 
375  //Announcing is complete?
376  if(context->retransmitCount >= AUTO_IP_ANNOUNCE_NUM)
377  {
378  //Successful address autoconfiguration
380  //Reset conflict counter
381  context->conflictCount = 0;
382 
383  //Dump current IPv4 configuration for debugging purpose
384  autoIpDumpConfig(context);
385  }
386  }
387  }
388  else if(context->state == AUTO_IP_STATE_CONFIGURED)
389  {
390  //Address Conflict Detection is an on-going process that is in effect
391  //for as long as a host is using an IPv4 link-local address
392  if(interface->ipv4Context.addrList[i].conflict)
393  {
394  //The host may elect to attempt to defend its address by recording
395  //the time that the conflicting ARP packet was received, and then
396  //broadcasting one single ARP announcement, giving its own IP and
397  //hardware addresses as the sender addresses of the ARP
398 #if (AUTO_IP_BCT_SUPPORT == ENABLED)
399  arpSendProbe(interface, context->linkLocalAddr);
400 #else
401  arpSendRequest(interface, context->linkLocalAddr, &MAC_BROADCAST_ADDR);
402 #endif
403  //Clear conflict flag
404  interface->ipv4Context.addrList[i].conflict = FALSE;
405 
406  //The host can then continue to use the address normally without
407  //any further special action
409  }
410  }
411  else if(context->state == AUTO_IP_STATE_DEFENDING)
412  {
413  //if this is not the first conflicting ARP packet the host has seen, and
414  //the time recorded for the previous conflicting ARP packet is recent,
415  //within DEFEND_INTERVAL seconds, then the host must immediately cease
416  //using this address
417  if(interface->ipv4Context.addrList[i].conflict)
418  {
419  //The link-local address cannot be used anymore
420  interface->ipv4Context.addrList[i].addr = IPV4_UNSPECIFIED_ADDR;
421  interface->ipv4Context.addrList[i].state = IPV4_ADDR_STATE_INVALID;
422 
423 #if (MDNS_RESPONDER_SUPPORT == ENABLED)
424  //Restart mDNS probing process
425  mdnsResponderStartProbing(interface->mdnsResponderContext);
426 #endif
427  //The host must pick a new random address...
428  autoIpGenerateAddr(&context->linkLocalAddr);
429  //...and probes/announces again
431  }
432  else
433  {
434  //Check whether the DEFEND_INTERVAL has elapsed
435  if(timeCompare(time, context->timestamp + AUTO_IP_DEFEND_INTERVAL) >= 0)
436  {
437  //The host can continue to use its link-local address
439  }
440  }
441  }
442 }
443 
444 
445 /**
446  * @brief Callback function for link change event
447  * @param[in] context Pointer to the Auto-IP context
448  **/
449 
451 {
452  uint_t i;
453  NetInterface *interface;
454 
455  //Make sure Auto-IP has been properly instantiated
456  if(context == NULL)
457  return;
458 
459  //Point to the underlying network interface
460  interface = context->settings.interface;
461  //Index of the IP address in the list of addresses assigned to the interface
462  i = context->settings.ipAddrIndex;
463 
464  //Check whether Auto-IP is enabled
465  if(context->running)
466  {
467  //The host address is not longer valid
468  interface->ipv4Context.addrList[i].addr = IPV4_UNSPECIFIED_ADDR;
469  interface->ipv4Context.addrList[i].state = IPV4_ADDR_STATE_INVALID;
470 
471  //Clear subnet mask
472  interface->ipv4Context.addrList[i].subnetMask = IPV4_UNSPECIFIED_ADDR;
473 
474 #if (MDNS_RESPONDER_SUPPORT == ENABLED)
475  //Restart mDNS probing process
476  mdnsResponderStartProbing(interface->mdnsResponderContext);
477 #endif
478  }
479 
480  //Reinitialize state machine
481  context->state = AUTO_IP_STATE_INIT;
482  //Reset conflict counter
483  context->conflictCount = 0;
484 
485  //Any registered callback?
486  if(context->settings.linkChangeEvent != NULL)
487  {
488  //Release exclusive access
490  //Invoke user callback function
491  context->settings.linkChangeEvent(context, interface, interface->linkState);
492  //Get exclusive access
494  }
495 }
496 
497 
498 /**
499  * @brief Update Auto-IP FSM state
500  * @param[in] context Pointer to the Auto-IP context
501  * @param[in] newState New Auto-IP state to switch to
502  * @param[in] delay Initial delay
503  **/
504 
506  AutoIpState newState, systime_t delay)
507 {
508  NetInterface *interface;
509 
510  //Point to the underlying network interface
511  interface = context->settings.interface;
512 
513  //Set time stamp
514  context->timestamp = osGetSystemTime();
515  //Set initial delay
516  context->timeout = delay;
517  //Reset retransmission counter
518  context->retransmitCount = 0;
519  //Switch to the new state
520  context->state = newState;
521 
522  //Any registered callback?
523  if(context->settings.stateChangeEvent != NULL)
524  {
525  //Release exclusive access
527  //Invoke user callback function
528  context->settings.stateChangeEvent(context, interface, newState);
529  //Get exclusive access
531  }
532 }
533 
534 
535 /**
536  * @brief Generate a random link-local address
537  * @param[out] ipAddr Random link-local address
538  **/
539 
541 {
542  uint32_t n;
543 
544  //Generate a random address in the range from 169.254.1.0 to 169.254.254.255
547 
548  //Convert the resulting address to network byte order
549  *ipAddr = htonl(n);
550 }
551 
552 
553 /**
554  * @brief Dump Auto-IP configuration for debugging purpose
555  * @param[in] context Pointer to the Auto-IP context
556  **/
557 
559 {
560 #if (AUTO_IP_TRACE_LEVEL >= TRACE_LEVEL_INFO)
561  uint_t i;
562  NetInterface *interface;
563  Ipv4Context *ipv4Context;
564 
565  //Point to the underlying network interface
566  interface = context->settings.interface;
567  //Point to the IPv4 context
568  ipv4Context = &interface->ipv4Context;
569 
570  //Index of the IP address in the list of addresses assigned to the interface
571  i = context->settings.ipAddrIndex;
572 
573  //Debug message
574  TRACE_INFO("\r\n");
575  TRACE_INFO("Auto-IP configuration:\r\n");
576 
577  //Link-local address
578  TRACE_INFO(" Link-local Address = %s\r\n",
579  ipv4AddrToString(ipv4Context->addrList[i].addr, NULL));
580 
581  //Subnet mask
582  TRACE_INFO(" Subnet Mask = %s\r\n",
583  ipv4AddrToString(ipv4Context->addrList[i].subnetMask, NULL));
584 
585  //Debug message
586  TRACE_INFO("\r\n");
587 #endif
588 }
589 
590 #endif
AutoIpState autoIpGetState(AutoIpContext *context)
Retrieve current state.
Definition: auto_ip.c:213
void autoIpChangeState(AutoIpContext *context, AutoIpState newState, systime_t delay)
Update Auto-IP FSM state.
Definition: auto_ip.c:505
error_t autoIpInit(AutoIpContext *context, const AutoIpSettings *settings)
Auto-IP initialization.
Definition: auto_ip.c:87
@ AUTO_IP_STATE_PROBING
Definition: auto_ip.h:154
AutoIpStateChangeCallback stateChangeEvent
FSM state change event.
Definition: auto_ip.h:187
@ AUTO_IP_STATE_DEFENDING
Definition: auto_ip.h:157
#define AUTO_IP_MAX_CONFLICTS
Definition: auto_ip.h:109
#define TRUE
Definition: os_port.h:50
#define AutoIpContext
Definition: auto_ip.h:139
#define AUTO_IP_DEFEND_INTERVAL
Definition: auto_ip.h:123
Auto-IP settings.
Definition: auto_ip.h:181
#define AUTO_IP_PROBE_NUM
Definition: auto_ip.h:67
error_t autoIpStop(AutoIpContext *context)
Stop Auto-IP process.
Definition: auto_ip.c:182
#define timeCompare(t1, t2)
Definition: os_port.h:42
void autoIpLinkChangeEvent(AutoIpContext *context)
Callback function for link change event.
Definition: auto_ip.c:450
uint32_t Ipv4Addr
IPv4 network address.
Definition: ipv4.h:239
#define AUTO_IP_PROBE_MIN
Definition: auto_ip.h:74
IPv4 context.
Definition: ipv4.h:338
Ethernet.
AutoIpLinkChangeCallback linkChangeEvent
Link state change event.
Definition: auto_ip.h:186
#define AUTO_IP_ADDR_MIN
Definition: auto_ip.h:134
#define FALSE
Definition: os_port.h:46
@ AUTO_IP_STATE_CONFIGURED
Definition: auto_ip.h:156
@ ERROR_INVALID_PARAMETER
Invalid parameter.
Definition: error.h:47
#define htonl(value)
Definition: cpu_endian.h:393
void autoIpTick(AutoIpContext *context)
Auto-IP timer handler.
Definition: auto_ip.c:238
error_t
Error codes.
Definition: error.h:42
@ IPV4_ADDR_STATE_TENTATIVE
An address whose uniqueness on a link is being verified.
Definition: ipv4.h:190
#define AUTO_IP_ANNOUNCE_NUM
Definition: auto_ip.h:95
#define AUTO_IP_ANNOUNCE_INTERVAL
Definition: auto_ip.h:102
#define AUTO_IP_MASK
Definition: auto_ip.h:131
#define NetInterface
Definition: net.h:36
NetInterface * netGetDefaultInterface(void)
Get default network interface.
Definition: net.c:1782
OsMutex netMutex
Definition: net.c:75
uint_t ipAddrIndex
Index of the IP address to be configured.
Definition: auto_ip.h:184
#define TRACE_INFO(...)
Definition: debug.h:94
void autoIpGetDefaultSettings(AutoIpSettings *settings)
Initialize settings with default values.
Definition: auto_ip.c:64
uint32_t netGetRand(void)
Get a random value.
Definition: net.c:1810
int32_t netGetRandRange(int32_t min, int32_t max)
Get a random value in the specified range.
Definition: net.c:1841
error_t arpSendRequest(NetInterface *interface, Ipv4Addr targetIpAddr, const MacAddr *destMacAddr)
Send ARP request.
Definition: arp.c:861
Ipv4Addr linkLocalAddr
Initial link-local address to be used.
Definition: auto_ip.h:185
#define AUTO_IP_ADDR_MAX
Definition: auto_ip.h:135
uint32_t time
uint8_t n
#define AUTO_IP_ANNOUNCE_WAIT
Definition: auto_ip.h:88
systime_t autoIpTickCounter
Definition: auto_ip.c:56
void osAcquireMutex(OsMutex *mutex)
Acquire ownership of the specified mutex object.
@ IPV4_ADDR_STATE_INVALID
An address that is not assigned to any interface.
Definition: ipv4.h:189
void osReleaseMutex(OsMutex *mutex)
Release ownership of the specified mutex object.
@ AUTO_IP_STATE_INIT
Definition: auto_ip.h:153
#define AUTO_IP_RATE_LIMIT_INTERVAL
Definition: auto_ip.h:116
#define AUTO_IP_PROBE_WAIT
Definition: auto_ip.h:60
@ IPV4_ADDR_STATE_VALID
An address assigned to an interface whose use is unrestricted.
Definition: ipv4.h:191
NetInterface * interface
Network interface to configure.
Definition: auto_ip.h:183
void autoIpGenerateAddr(Ipv4Addr *ipAddr)
Generate a random link-local address.
Definition: auto_ip.c:540
unsigned int uint_t
Definition: compiler_port.h:45
TCP/IP stack core.
char_t * ipv4AddrToString(Ipv4Addr ipAddr, char_t *str)
Convert a binary IPv4 address to dot-decimal notation.
Definition: ipv4.c:1466
AutoIpState
Auto-IP FSM states.
Definition: auto_ip.h:151
void autoIpDumpConfig(AutoIpContext *context)
Dump Auto-IP configuration for debugging purpose.
Definition: auto_ip.c:558
ARP (Address Resolution Protocol)
error_t autoIpStart(AutoIpContext *context)
Start Auto-IP process.
Definition: auto_ip.c:134
uint32_t systime_t
Definition: compiler_port.h:46
uint8_t ipAddr[4]
Definition: mib_common.h:187
#define ntohl(value)
Definition: cpu_endian.h:399
error_t mdnsResponderStartProbing(MdnsResponderContext *context)
Restart probing process.
@ AUTO_IP_STATE_ANNOUNCING
Definition: auto_ip.h:155
@ NO_ERROR
Success.
Definition: error.h:44
#define AUTO_IP_PROBE_MAX
Definition: auto_ip.h:81
Debugging facilities.
error_t arpSendProbe(NetInterface *interface, Ipv4Addr targetIpAddr)
Send ARP probe.
Definition: arp.c:806
const MacAddr MAC_BROADCAST_ADDR
Definition: ethernet.c:58
#define IPV4_UNSPECIFIED_ADDR
Definition: ipv4.h:104
mDNS responder (Multicast DNS)
Auto-IP (Dynamic Configuration of IPv4 Link-Local Addresses)
systime_t osGetSystemTime(void)
Retrieve system time.