1/**
2 * @file
3 * AutoIP Automatic LinkLocal IP Configuration
4 *
5 */
6
7/*
8 *
9 * Copyright (c) 2007 Dominik Spies <kontakt@dspies.de>
10 * All rights reserved.
11 *
12 * Redistribution and use in source and binary forms, with or without modification,
13 * are permitted provided that the following conditions are met:
14 *
15 * 1. Redistributions of source code must retain the above copyright notice,
16 *    this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright notice,
18 *    this list of conditions and the following disclaimer in the documentation
19 *    and/or other materials provided with the distribution.
20 * 3. The name of the author may not be used to endorse or promote products
21 *    derived from this software without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
24 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
25 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
26 * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
27 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
28 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
31 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
32 * OF SUCH DAMAGE.
33 *
34 * Author: Dominik Spies <kontakt@dspies.de>
35 *
36 * This is a AutoIP implementation for the lwIP TCP/IP stack. It aims to conform
37 * with RFC 3927.
38 *
39 *
40 * Please coordinate changes and requests with Dominik Spies
41 * <kontakt@dspies.de>
42 */
43
44/*******************************************************************************
45 * USAGE:
46 *
47 * define LWIP_AUTOIP 1  in your lwipopts.h
48 *
49 * If you don't use tcpip.c (so, don't call, you don't call tcpip_init):
50 * - First, call autoip_init().
51 * - call autoip_tmr() all AUTOIP_TMR_INTERVAL msces,
52 *   that should be defined in autoip.h.
53 *   I recommend a value of 100. The value must divide 1000 with a remainder almost 0.
54 *   Possible values are 1000, 500, 333, 250, 200, 166, 142, 125, 111, 100 ....
55 *
56 * Without DHCP:
57 * - Call autoip_start() after netif_add().
58 *
59 * With DHCP:
60 * - define LWIP_DHCP_AUTOIP_COOP 1 in your lwipopts.h.
61 * - Configure your DHCP Client.
62 *
63 */
64
65#include "lwip/opt.h"
66
67#if LWIP_AUTOIP                 /* don't build if not configured for use in lwipopts.h */
68
69#include "lwip/mem.h"
70#include "lwip/udp.h"
71#include "lwip/ip_addr.h"
72#include "lwip/netif.h"
73#include "lwip/autoip.h"
74#include "netif/etharp.h"
75
76#include <stdlib.h>
77#include <string.h>
78
79/* 169.254.0.0 */
80#define AUTOIP_NET         0xA9FE0000
81/* 169.254.1.0 */
82#define AUTOIP_RANGE_START (AUTOIP_NET | 0x0100)
83/* 169.254.254.255 */
84#define AUTOIP_RANGE_END   (AUTOIP_NET | 0xFEFF)
85
86
87/** Pseudo random macro based on netif informations.
88 * You could use "rand()" from the C Library if you define LWIP_AUTOIP_RAND in lwipopts.h */
89#ifndef LWIP_AUTOIP_RAND
90#define LWIP_AUTOIP_RAND(netif) ( (((u32_t)((netif->hwaddr[5]) & 0xff) << 24) | \
91                                   ((u32_t)((netif->hwaddr[3]) & 0xff) << 16) | \
92                                   ((u32_t)((netif->hwaddr[2]) & 0xff) << 8) | \
93                                   ((u32_t)((netif->hwaddr[4]) & 0xff))) + \
94                                   (netif->autoip?netif->autoip->tried_llipaddr:0))
95#endif                          /* LWIP_AUTOIP_RAND */
96
97/**
98 * Macro that generates the initial IP address to be tried by AUTOIP.
99 * If you want to override this, define it to something else in lwipopts.h.
100 */
101#ifndef LWIP_AUTOIP_CREATE_SEED_ADDR
102#define LWIP_AUTOIP_CREATE_SEED_ADDR(netif) \
103  (AUTOIP_RANGE_START + ((u32_t)(((u8_t)(netif->hwaddr[4])) | \
104                 ((u32_t)((u8_t)(netif->hwaddr[5]))) << 8)))
105#endif                          /* LWIP_AUTOIP_CREATE_SEED_ADDR */
106
107/* static functions */
108static void autoip_handle_arp_conflict(struct netif *netif);
109
110/* creates a pseudo random LL IP-Address for a network interface */
111static void autoip_create_addr(struct netif *netif, struct ip_addr *IPAddr);
112
113/* sends an ARP announce */
114static err_t autoip_arp_announce(struct netif *netif);
115
116/* configure interface for use with current LL IP-Address */
117static err_t autoip_bind(struct netif *netif);
118
119/**
120 * Initialize this module
121 */
122void autoip_init(void)
123{
124    LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | 3, ("autoip_init()\n"));
125}
126
127/**
128 * Handle a IP address conflict after an ARP conflict detection
129 */
130static void autoip_handle_arp_conflict(struct netif *netif)
131{
132    /* Somehow detect if we are defending or retreating */
133    unsigned char defend = 1;   /* tbd */
134
135    if (defend) {
136        if (netif->autoip->lastconflict > 0) {
137            /* retreat, there was a conflicting ARP in the last
138             * DEFEND_INTERVAL seconds
139             */
140            LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE | 1,
141                        ("autoip_handle_arp_conflict(): we are defending, but in DEFEND_INTERVAL, retreating\n"));
142
143            /* TODO: close all TCP sessions */
144            autoip_start(netif);
145        } else {
146            LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE | 1,
147                        ("autoip_handle_arp_conflict(): we are defend, send ARP Announce\n"));
148            autoip_arp_announce(netif);
149            netif->autoip->lastconflict =
150              DEFEND_INTERVAL * AUTOIP_TICKS_PER_SECOND;
151        }
152    } else {
153        LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE | 1,
154                    ("autoip_handle_arp_conflict(): we do not defend, retreating\n"));
155        /* TODO: close all TCP sessions */
156        autoip_start(netif);
157    }
158}
159
160/**
161 * Create an IP-Address out of range 169.254.1.0 to 169.254.254.255
162 *
163 * @param netif network interface on which create the IP-Address
164 * @param IPAddr ip address to initialize
165 */
166static void autoip_create_addr(struct netif *netif, struct ip_addr *IPAddr)
167{
168    /* Here we create an IP-Address out of range 169.254.1.0 to 169.254.254.255
169     * compliant to RFC 3927 Section 2.1
170     * We have 254 * 256 possibilities */
171
172    u32_t addr = ntohl(LWIP_AUTOIP_CREATE_SEED_ADDR(netif));
173
174    addr += netif->autoip->tried_llipaddr;
175    addr = AUTOIP_NET | (addr & 0xffff);
176    /* Now, 169.254.0.0 <= addr <= 169.254.255.255 */
177
178    if (addr < AUTOIP_RANGE_START) {
179        addr += AUTOIP_RANGE_END - AUTOIP_RANGE_START + 1;
180    }
181    if (addr > AUTOIP_RANGE_END) {
182        addr -= AUTOIP_RANGE_END - AUTOIP_RANGE_START + 1;
183    }
184    LWIP_ASSERT("AUTOIP address not in range", (addr >= AUTOIP_RANGE_START) &&
185                (addr <= AUTOIP_RANGE_END));
186    IPAddr->addr = htonl(addr);
187
188    LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE | 1,
189                ("autoip_create_addr(): tried_llipaddr=%" U16_F ", 0x%08" X32_F
190                 "\n", (u16_t) (netif->autoip->tried_llipaddr),
191                 (u32_t) (IPAddr->addr)));
192}
193
194/**
195 * Sends an ARP announce from a network interface
196 *
197 * @param netif network interface used to send the announce
198 */
199static err_t autoip_arp_announce(struct netif *netif)
200{
201    return etharp_raw(netif, (struct eth_addr *) netif->hwaddr, &ethbroadcast,
202                      (struct eth_addr *) netif->hwaddr,
203                      &netif->autoip->llipaddr, &ethzero,
204                      &netif->autoip->llipaddr, ARP_REQUEST);
205}
206
207/**
208 * Configure interface for use with current LL IP-Address
209 *
210 * @param netif network interface to configure with current LL IP-Address
211 */
212static err_t autoip_bind(struct netif *netif)
213{
214    struct autoip *autoip = netif->autoip;
215    struct ip_addr sn_mask, gw_addr;
216
217    LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | 3,
218                ("autoip_bind(netif=%p) %c%c%" U16_F " 0x%08" X32_F "\n",
219                 (void *) netif, netif->name[0], netif->name[1],
220                 (u16_t) netif->num, autoip->llipaddr.addr));
221
222    IP4_ADDR(&sn_mask, 255, 255, 0, 0);
223    IP4_ADDR(&gw_addr, 0, 0, 0, 0);
224
225    netif_set_ipaddr(netif, &autoip->llipaddr);
226    netif_set_netmask(netif, &sn_mask);
227    netif_set_gw(netif, &gw_addr);
228
229    /* bring the interface up */
230    netif_set_up(netif);
231
232    return ERR_OK;
233}
234
235/**
236 * Start AutoIP client
237 *
238 * @param netif network interface on which start the AutoIP client
239 */
240err_t autoip_start(struct netif * netif)
241{
242    struct autoip *autoip = netif->autoip;
243    err_t result = ERR_OK;
244
245    if (netif_is_up(netif)) {
246        netif_set_down(netif);
247    }
248
249    /* Set IP-Address, Netmask and Gateway to 0 to make sure that
250     * ARP Packets are formed correctly
251     */
252    netif->ip_addr.addr = 0;
253    netif->netmask.addr = 0;
254    netif->gw.addr = 0;
255
256    LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
257                ("autoip_start(netif=%p) %c%c%" U16_F "\n", (void *) netif,
258                 netif->name[0], netif->name[1], (u16_t) netif->num));
259    if (autoip == NULL) {
260        /* no AutoIP client attached yet? */
261        LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE,
262                    ("autoip_start(): starting new AUTOIP client\n"));
263        autoip = mem_malloc(sizeof(struct autoip));
264        if (autoip == NULL) {
265            LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE,
266                        ("autoip_start(): could not allocate autoip\n"));
267            return ERR_MEM;
268        }
269        memset(autoip, 0, sizeof(struct autoip));
270        /* store this AutoIP client in the netif */
271        netif->autoip = autoip;
272        LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE,
273                    ("autoip_start(): allocated autoip"));
274    } else {
275        autoip->state = AUTOIP_STATE_OFF;
276        autoip->ttw = 0;
277        autoip->sent_num = 0;
278        memset(&autoip->llipaddr, 0, sizeof(struct ip_addr));
279        autoip->lastconflict = 0;
280    }
281
282    autoip_create_addr(netif, &(autoip->llipaddr));
283    autoip->tried_llipaddr++;
284    autoip->state = AUTOIP_STATE_PROBING;
285    autoip->sent_num = 0;
286
287    /* time to wait to first probe, this is randomly
288     * choosen out of 0 to PROBE_WAIT seconds.
289     * compliant to RFC 3927 Section 2.2.1
290     */
291    autoip->ttw =
292      (u16_t) (LWIP_AUTOIP_RAND(netif) %
293               (PROBE_WAIT * AUTOIP_TICKS_PER_SECOND));
294
295    /*
296     * if we tried more then MAX_CONFLICTS we must limit our rate for
297     * accquiring and probing address
298     * compliant to RFC 3927 Section 2.2.1
299     */
300
301    if (autoip->tried_llipaddr > MAX_CONFLICTS) {
302        autoip->ttw = RATE_LIMIT_INTERVAL * AUTOIP_TICKS_PER_SECOND;
303    }
304
305    return result;
306}
307
308/**
309 * Stop AutoIP client
310 *
311 * @param netif network interface on which stop the AutoIP client
312 */
313err_t autoip_stop(struct netif * netif)
314{
315    netif->autoip->state = AUTOIP_STATE_OFF;
316    netif_set_down(netif);
317    return ERR_OK;
318}
319
320/**
321 * Has to be called in loop every AUTOIP_TMR_INTERVAL milliseconds
322 */
323void autoip_tmr()
324{
325    struct netif *netif = netif_list;
326
327    /* loop through netif's */
328    while (netif != NULL) {
329        /* only act on AutoIP configured interfaces */
330        if (netif->autoip != NULL) {
331            if (netif->autoip->lastconflict > 0) {
332                netif->autoip->lastconflict--;
333            }
334
335            LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE,
336                        ("autoip_tmr() AutoIP-State: %" U16_F ", ttw=%" U16_F
337                         "\n", (u16_t) (netif->autoip->state),
338                         netif->autoip->ttw));
339
340            switch (netif->autoip->state) {
341                case AUTOIP_STATE_PROBING:
342                    if (netif->autoip->ttw > 0) {
343                        netif->autoip->ttw--;
344                    } else {
345                        if (netif->autoip->sent_num == PROBE_NUM) {
346                            netif->autoip->state = AUTOIP_STATE_ANNOUNCING;
347                            netif->autoip->sent_num = 0;
348                            netif->autoip->ttw =
349                              ANNOUNCE_WAIT * AUTOIP_TICKS_PER_SECOND;
350                        } else {
351                            etharp_request(netif, &(netif->autoip->llipaddr));
352                            LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | 3,
353                                        ("autoip_tmr() PROBING Sent Probe\n"));
354                            netif->autoip->sent_num++;
355                            /* calculate time to wait to next probe */
356                            netif->autoip->ttw =
357                              (u16_t) ((LWIP_AUTOIP_RAND(netif) %
358                                        ((PROBE_MAX -
359                                          PROBE_MIN) *
360                                         AUTOIP_TICKS_PER_SECOND)) +
361                                       PROBE_MIN * AUTOIP_TICKS_PER_SECOND);
362                        }
363                    }
364                    break;
365
366                case AUTOIP_STATE_ANNOUNCING:
367                    if (netif->autoip->ttw > 0) {
368                        netif->autoip->ttw--;
369                    } else {
370                        if (netif->autoip->sent_num == 0) {
371                            /* We are here the first time, so we waited ANNOUNCE_WAIT seconds
372                             * Now we can bind to an IP address and use it
373                             */
374                            autoip_bind(netif);
375                        }
376
377                        if (netif->autoip->sent_num == ANNOUNCE_NUM) {
378                            netif->autoip->state = AUTOIP_STATE_BOUND;
379                            netif->autoip->sent_num = 0;
380                            netif->autoip->ttw = 0;
381                        } else {
382                            autoip_arp_announce(netif);
383                            LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | 3,
384                                        ("autoip_tmr() ANNOUNCING Sent Announce\n"));
385                            netif->autoip->sent_num++;
386                            netif->autoip->ttw =
387                              ANNOUNCE_INTERVAL * AUTOIP_TICKS_PER_SECOND;
388                        }
389                    }
390                    break;
391            }
392        }
393        /* proceed to next network interface */
394        netif = netif->next;
395    }
396}
397
398/**
399 * Handles every incoming ARP Packet, called by etharp_arp_input.
400 *
401 * @param netif network interface to use for autoip processing
402 * @param hdr Incoming ARP packet
403 */
404void autoip_arp_reply(struct netif *netif, struct etharp_hdr *hdr)
405{
406    LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | 3, ("autoip_arp_reply()\n"));
407    if ((netif->autoip != NULL) && (netif->autoip->state != AUTOIP_STATE_OFF)) {
408        /* when ip.src == llipaddr && hw.src != netif->hwaddr
409         *
410         * when probing  ip.dst == llipaddr && hw.src != netif->hwaddr
411         * we have a conflict and must solve it
412         */
413        struct ip_addr sipaddr, dipaddr;
414        struct eth_addr netifaddr;
415
416        netifaddr.addr[0] = netif->hwaddr[0];
417        netifaddr.addr[1] = netif->hwaddr[1];
418        netifaddr.addr[2] = netif->hwaddr[2];
419        netifaddr.addr[3] = netif->hwaddr[3];
420        netifaddr.addr[4] = netif->hwaddr[4];
421        netifaddr.addr[5] = netif->hwaddr[5];
422
423        /* Copy struct ip_addr2 to aligned ip_addr, to support compilers without
424         * structure packing (not using structure copy which breaks strict-aliasing rules).
425         */
426        SMEMCPY(&sipaddr, &hdr->sipaddr, sizeof(sipaddr));
427        SMEMCPY(&dipaddr, &hdr->dipaddr, sizeof(dipaddr));
428
429        if ((netif->autoip->state == AUTOIP_STATE_PROBING) ||
430            ((netif->autoip->state == AUTOIP_STATE_ANNOUNCING) &&
431             (netif->autoip->sent_num == 0))) {
432            /* RFC 3927 Section 2.2.1:
433             * from beginning to after ANNOUNCE_WAIT
434             * seconds we have a conflict if
435             * ip.src == llipaddr OR
436             * ip.dst == llipaddr && hw.src != own hwaddr
437             */
438            if ((ip_addr_cmp(&sipaddr, &netif->autoip->llipaddr)) ||
439                (ip_addr_cmp(&dipaddr, &netif->autoip->llipaddr) &&
440                 !eth_addr_cmp(&netifaddr, &hdr->shwaddr))) {
441                LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE | 1,
442                            ("autoip_arp_reply(): Probe Conflict detected\n"));
443                autoip_start(netif);
444            }
445        } else {
446            /* RFC 3927 Section 2.5:
447             * in any state we have a conflict if
448             * ip.src == llipaddr && hw.src != own hwaddr
449             */
450            if (ip_addr_cmp(&sipaddr, &netif->autoip->llipaddr) &&
451                !eth_addr_cmp(&netifaddr, &hdr->shwaddr)) {
452                LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE | 1,
453                            ("autoip_arp_reply(): Conflicting ARP-Packet detected\n"));
454                autoip_handle_arp_conflict(netif);
455            }
456        }
457    }
458}
459
460#endif                          /* LWIP_AUTOIP */
461