1 /**
2  * @file
3  * Address Resolution Protocol module for IP over Ethernet
4  *
5  * Functionally, ARP is divided into two parts. The first maps an IP address
6  * to a physical address when sending a packet, and the second part answers
7  * requests from other machines for our physical address.
8  *
9  * This implementation complies with RFC 826 (Ethernet ARP). It supports
10  * Gratuitious ARP from RFC3220 (IP Mobility Support for IPv4) section 4.6
11  * if an interface calls etharp_gratuitous(our_netif) upon address change.
12  */
13 
14 /*
15  * Copyright (c) 2001-2003 Swedish Institute of Computer Science.
16  * Copyright (c) 2003-2004 Leon Woestenberg <leon.woestenberg@axon.tv>
17  * Copyright (c) 2003-2004 Axon Digital Design B.V., The Netherlands.
18  * All rights reserved.
19  *
20  * Redistribution and use in source and binary forms, with or without modification,
21  * are permitted provided that the following conditions are met:
22  *
23  * 1. Redistributions of source code must retain the above copyright notice,
24  *    this list of conditions and the following disclaimer.
25  * 2. Redistributions in binary form must reproduce the above copyright notice,
26  *    this list of conditions and the following disclaimer in the documentation
27  *    and/or other materials provided with the distribution.
28  * 3. The name of the author may not be used to endorse or promote products
29  *    derived from this software without specific prior written permission.
30  *
31  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
32  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
33  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
34  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
35  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
36  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
37  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
38  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
39  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
40  * OF SUCH DAMAGE.
41  *
42  * This file is part of the lwIP TCP/IP stack.
43  *
44  */
45 
46 #include "lwip/opt.h"
47 
48 #if LWIP_ARP || LWIP_ETHERNET
49 
50 #include "lwip/etharp.h"
51 #include "lwip/stats.h"
52 #include "lwip/snmp.h"
53 #include "lwip/dhcp.h"
54 #include "lwip/autoip.h"
55 #include "netif/ethernet.h"
56 
57 #include <string.h>
58 
59 #if LWIP_IPV4 && LWIP_ARP /* don't build if not configured for use in lwipopts.h */
60 
61 /** Re-request a used ARP entry 1 minute before it would expire to prevent
62  *  breaking a steadily used connection because the ARP entry timed out. */
63 #define ARP_AGE_REREQUEST_USED_UNICAST   (ARP_MAXAGE - 30)
64 #define ARP_AGE_REREQUEST_USED_BROADCAST (ARP_MAXAGE - 15)
65 
66 /** the time an ARP entry stays pending after first request,
67  *  for ARP_TMR_INTERVAL = 1000, this is
68  *  10 seconds.
69  *
70  *  @internal Keep this number at least 2, otherwise it might
71  *  run out instantly if the timeout occurs directly after a request.
72  */
73 #define ARP_MAXPENDING 5
74 
75 /** ARP states */
76 enum etharp_state {
77   ETHARP_STATE_EMPTY = 0,
78   ETHARP_STATE_PENDING,
79   ETHARP_STATE_STABLE,
80   ETHARP_STATE_STABLE_REREQUESTING_1,
81   ETHARP_STATE_STABLE_REREQUESTING_2
82 #if ETHARP_SUPPORT_STATIC_ENTRIES
83   ,ETHARP_STATE_STATIC
84 #endif /* ETHARP_SUPPORT_STATIC_ENTRIES */
85 };
86 
87 struct etharp_entry {
88 #if ARP_QUEUEING
89   /** Pointer to queue of pending outgoing packets on this ARP entry. */
90   struct etharp_q_entry *q;
91 #else /* ARP_QUEUEING */
92   /** Pointer to a single pending outgoing packet on this ARP entry. */
93   struct pbuf *q;
94 #endif /* ARP_QUEUEING */
95   ip4_addr_t ipaddr;
96   struct netif *netif;
97   struct eth_addr ethaddr;
98   u16_t ctime;
99   u8_t state;
100 };
101 
102 static struct etharp_entry arp_table[ARP_TABLE_SIZE];
103 
104 #if !LWIP_NETIF_HWADDRHINT
105 static u8_t etharp_cached_entry;
106 #endif /* !LWIP_NETIF_HWADDRHINT */
107 
108 /** Try hard to create a new entry - we want the IP address to appear in
109     the cache (even if this means removing an active entry or so). */
110 #define ETHARP_FLAG_TRY_HARD     1
111 #define ETHARP_FLAG_FIND_ONLY    2
112 #if ETHARP_SUPPORT_STATIC_ENTRIES
113 #define ETHARP_FLAG_STATIC_ENTRY 4
114 #endif /* ETHARP_SUPPORT_STATIC_ENTRIES */
115 
116 #if LWIP_NETIF_HWADDRHINT
117 #define ETHARP_SET_HINT(netif, hint)  if (((netif) != NULL) && ((netif)->addr_hint != NULL))  \
118                                       *((netif)->addr_hint) = (hint);
119 #else /* LWIP_NETIF_HWADDRHINT */
120 #define ETHARP_SET_HINT(netif, hint)  (etharp_cached_entry = (hint))
121 #endif /* LWIP_NETIF_HWADDRHINT */
122 
123 
124 /* Some checks, instead of etharp_init(): */
125 #if (LWIP_ARP && (ARP_TABLE_SIZE > 0x7f))
126   #error "ARP_TABLE_SIZE must fit in an s8_t, you have to reduce it in your lwipopts.h"
127 #endif
128 
129 
130 static err_t etharp_request_dst(struct netif *netif, const ip4_addr_t *ipaddr, const struct eth_addr* hw_dst_addr);
131 
etharp_info_print(void)132 int etharp_info_print(void)
133 {
134   int i;
135   int empty = 1;
136 
137   for (i = 0; i < ARP_TABLE_SIZE; ++i) {
138     u8_t state = arp_table[i].state;
139 
140     if (state != ETHARP_STATE_EMPTY) {
141       empty = 0;
142       printf("IP\t\tMAC\t\t\tTime\tState\n");
143       printf("%u.%u.%u.%u\t",
144              ip4_addr1_16(&arp_table[i].ipaddr), ip4_addr2_16(&arp_table[i].ipaddr),
145              ip4_addr3_16(&arp_table[i].ipaddr), ip4_addr4_16(&arp_table[i].ipaddr));
146       printf("%02x:%02x:%02x:%02x:%02x:%02x\t",
147              (u16_t)arp_table[i].ethaddr.addr[0], (u16_t)arp_table[i].ethaddr.addr[1], (u16_t)arp_table[i].ethaddr.addr[2],
148              (u16_t)arp_table[i].ethaddr.addr[3], (u16_t)arp_table[i].ethaddr.addr[4], (u16_t)arp_table[i].ethaddr.addr[5]);
149       printf("%u\t", arp_table[i].ctime);
150       printf("%s\n", (arp_table[i].state >= ETHARP_STATE_STABLE ? "stable" : "pending"));
151     }
152   }
153 
154   if (empty)
155     return -1;
156 
157   return 0;
158 }
159 
160 #if ARP_QUEUEING
161 /**
162  * Free a complete queue of etharp entries
163  *
164  * @param q a qeueue of etharp_q_entry's to free
165  */
166 static void
free_etharp_q(struct etharp_q_entry * q)167 free_etharp_q(struct etharp_q_entry *q)
168 {
169   struct etharp_q_entry *r;
170   LWIP_ASSERT("q != NULL", q != NULL);
171   LWIP_ASSERT("q->p != NULL", q->p != NULL);
172   while (q) {
173     r = q;
174     q = q->next;
175     LWIP_ASSERT("r->p != NULL", (r->p != NULL));
176     pbuf_free(r->p);
177     memp_free(MEMP_ARP_QUEUE, r);
178   }
179 }
180 #else /* ARP_QUEUEING */
181 
182 /** Compatibility define: free the queued pbuf */
183 #define free_etharp_q(q) pbuf_free(q)
184 
185 #endif /* ARP_QUEUEING */
186 
187 /** Clean up ARP table entries */
188 static void
etharp_free_entry(int i)189 etharp_free_entry(int i)
190 {
191   /* remove from SNMP ARP index tree */
192   mib2_remove_arp_entry(arp_table[i].netif, &arp_table[i].ipaddr);
193   /* and empty packet queue */
194   if (arp_table[i].q != NULL) {
195     /* remove all queued packets */
196     LWIP_DEBUGF(ETHARP_DEBUG, ("etharp_free_entry: freeing entry %"U16_F", packet queue %p.\n", (u16_t)i, (void *)(arp_table[i].q)));
197     free_etharp_q(arp_table[i].q);
198     arp_table[i].q = NULL;
199   }
200   /* recycle entry for re-use */
201   arp_table[i].state = ETHARP_STATE_EMPTY;
202 #ifdef LWIP_DEBUG
203   /* for debugging, clean out the complete entry */
204   arp_table[i].ctime = 0;
205   arp_table[i].netif = NULL;
206   ip4_addr_set_zero(&arp_table[i].ipaddr);
207   arp_table[i].ethaddr = ethzero;
208 #endif /* LWIP_DEBUG */
209 }
210 
211 /**
212  * Clears expired entries in the ARP table.
213  *
214  * This function should be called every ARP_TMR_INTERVAL milliseconds (1 second),
215  * in order to expire entries in the ARP table.
216  */
217 void
etharp_tmr(void)218 etharp_tmr(void)
219 {
220   u8_t i;
221 
222   LWIP_DEBUGF(ETHARP_DEBUG, ("etharp_timer\n"));
223   /* remove expired entries from the ARP table */
224   for (i = 0; i < ARP_TABLE_SIZE; ++i) {
225     u8_t state = arp_table[i].state;
226     if (state != ETHARP_STATE_EMPTY
227 #if ETHARP_SUPPORT_STATIC_ENTRIES
228       && (state != ETHARP_STATE_STATIC)
229 #endif /* ETHARP_SUPPORT_STATIC_ENTRIES */
230       ) {
231       arp_table[i].ctime++;
232       if ((arp_table[i].ctime >= ARP_MAXAGE) ||
233           ((arp_table[i].state == ETHARP_STATE_PENDING)  &&
234            (arp_table[i].ctime >= ARP_MAXPENDING))) {
235         /* pending or stable entry has become old! */
236         LWIP_DEBUGF(ETHARP_DEBUG, ("etharp_timer: expired %s entry %"U16_F".\n",
237              arp_table[i].state >= ETHARP_STATE_STABLE ? "stable" : "pending", (u16_t)i));
238         /* clean up entries that have just been expired */
239         etharp_free_entry(i);
240       } else if (arp_table[i].state == ETHARP_STATE_STABLE_REREQUESTING_1) {
241         /* Don't send more than one request every 2 seconds. */
242         arp_table[i].state = ETHARP_STATE_STABLE_REREQUESTING_2;
243       } else if (arp_table[i].state == ETHARP_STATE_STABLE_REREQUESTING_2) {
244         /* Reset state to stable, so that the next transmitted packet will
245            re-send an ARP request. */
246         arp_table[i].state = ETHARP_STATE_STABLE;
247       } else if (arp_table[i].state == ETHARP_STATE_PENDING) {
248         /* still pending, resend an ARP query */
249         etharp_request(arp_table[i].netif, &arp_table[i].ipaddr);
250       }
251     }
252   }
253 }
254 
255 /**
256  * Search the ARP table for a matching or new entry.
257  *
258  * If an IP address is given, return a pending or stable ARP entry that matches
259  * the address. If no match is found, create a new entry with this address set,
260  * but in state ETHARP_EMPTY. The caller must check and possibly change the
261  * state of the returned entry.
262  *
263  * If ipaddr is NULL, return a initialized new entry in state ETHARP_EMPTY.
264  *
265  * In all cases, attempt to create new entries from an empty entry. If no
266  * empty entries are available and ETHARP_FLAG_TRY_HARD flag is set, recycle
267  * old entries. Heuristic choose the least important entry for recycling.
268  *
269  * @param ipaddr IP address to find in ARP cache, or to add if not found.
270  * @param flags See @ref etharp_state
271  * @param netif netif related to this address (used for NETIF_HWADDRHINT)
272  *
273  * @return The ARP entry index that matched or is created, ERR_MEM if no
274  * entry is found or could be recycled.
275  */
276 static s8_t
etharp_find_entry(const ip4_addr_t * ipaddr,u8_t flags,struct netif * netif)277 etharp_find_entry(const ip4_addr_t *ipaddr, u8_t flags, struct netif* netif)
278 {
279   s8_t old_pending = ARP_TABLE_SIZE, old_stable = ARP_TABLE_SIZE;
280   s8_t empty = ARP_TABLE_SIZE;
281   u8_t i = 0;
282   /* oldest entry with packets on queue */
283   s8_t old_queue = ARP_TABLE_SIZE;
284   /* its age */
285   u16_t age_queue = 0, age_pending = 0, age_stable = 0;
286 
287   LWIP_UNUSED_ARG(netif);
288 
289   /**
290    * a) do a search through the cache, remember candidates
291    * b) select candidate entry
292    * c) create new entry
293    */
294 
295   /* a) in a single search sweep, do all of this
296    * 1) remember the first empty entry (if any)
297    * 2) remember the oldest stable entry (if any)
298    * 3) remember the oldest pending entry without queued packets (if any)
299    * 4) remember the oldest pending entry with queued packets (if any)
300    * 5) search for a matching IP entry, either pending or stable
301    *    until 5 matches, or all entries are searched for.
302    */
303 
304   for (i = 0; i < ARP_TABLE_SIZE; ++i) {
305     u8_t state = arp_table[i].state;
306     /* no empty entry found yet and now we do find one? */
307     if ((empty == ARP_TABLE_SIZE) && (state == ETHARP_STATE_EMPTY)) {
308       LWIP_DEBUGF(ETHARP_DEBUG, ("etharp_find_entry: found empty entry %"U16_F"\n", (u16_t)i));
309       /* remember first empty entry */
310       empty = i;
311     } else if (state != ETHARP_STATE_EMPTY) {
312       LWIP_ASSERT("state == ETHARP_STATE_PENDING || state >= ETHARP_STATE_STABLE",
313         state == ETHARP_STATE_PENDING || state >= ETHARP_STATE_STABLE);
314       /* if given, does IP address match IP address in ARP entry? */
315       if (ipaddr && ip4_addr_cmp(ipaddr, &arp_table[i].ipaddr)
316 #if ETHARP_TABLE_MATCH_NETIF
317           && ((netif == NULL) || (netif == arp_table[i].netif))
318 #endif /* ETHARP_TABLE_MATCH_NETIF */
319         ) {
320         LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_find_entry: found matching entry %"U16_F"\n", (u16_t)i));
321         /* found exact IP address match, simply bail out */
322         return i;
323       }
324       /* pending entry? */
325       if (state == ETHARP_STATE_PENDING) {
326         /* pending with queued packets? */
327         if (arp_table[i].q != NULL) {
328           if (arp_table[i].ctime >= age_queue) {
329             old_queue = i;
330             age_queue = arp_table[i].ctime;
331           }
332         } else
333         /* pending without queued packets? */
334         {
335           if (arp_table[i].ctime >= age_pending) {
336             old_pending = i;
337             age_pending = arp_table[i].ctime;
338           }
339         }
340       /* stable entry? */
341       } else if (state >= ETHARP_STATE_STABLE) {
342 #if ETHARP_SUPPORT_STATIC_ENTRIES
343         /* don't record old_stable for static entries since they never expire */
344         if (state < ETHARP_STATE_STATIC)
345 #endif /* ETHARP_SUPPORT_STATIC_ENTRIES */
346         {
347           /* remember entry with oldest stable entry in oldest, its age in maxtime */
348           if (arp_table[i].ctime >= age_stable) {
349             old_stable = i;
350             age_stable = arp_table[i].ctime;
351           }
352         }
353       }
354     }
355   }
356   /* { we have no match } => try to create a new entry */
357 
358   /* don't create new entry, only search? */
359   if (((flags & ETHARP_FLAG_FIND_ONLY) != 0) ||
360       /* or no empty entry found and not allowed to recycle? */
361       ((empty == ARP_TABLE_SIZE) && ((flags & ETHARP_FLAG_TRY_HARD) == 0))) {
362     LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_find_entry: no empty entry found and not allowed to recycle\n"));
363     return (s8_t)ERR_MEM;
364   }
365 
366   /* b) choose the least destructive entry to recycle:
367    * 1) empty entry
368    * 2) oldest stable entry
369    * 3) oldest pending entry without queued packets
370    * 4) oldest pending entry with queued packets
371    *
372    * { ETHARP_FLAG_TRY_HARD is set at this point }
373    */
374 
375   /* 1) empty entry available? */
376   if (empty < ARP_TABLE_SIZE) {
377     i = empty;
378     LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_find_entry: selecting empty entry %"U16_F"\n", (u16_t)i));
379   } else {
380     /* 2) found recyclable stable entry? */
381     if (old_stable < ARP_TABLE_SIZE) {
382       /* recycle oldest stable*/
383       i = old_stable;
384       LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_find_entry: selecting oldest stable entry %"U16_F"\n", (u16_t)i));
385       /* no queued packets should exist on stable entries */
386       LWIP_ASSERT("arp_table[i].q == NULL", arp_table[i].q == NULL);
387     /* 3) found recyclable pending entry without queued packets? */
388     } else if (old_pending < ARP_TABLE_SIZE) {
389       /* recycle oldest pending */
390       i = old_pending;
391       LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_find_entry: selecting oldest pending entry %"U16_F" (without queue)\n", (u16_t)i));
392     /* 4) found recyclable pending entry with queued packets? */
393     } else if (old_queue < ARP_TABLE_SIZE) {
394       /* recycle oldest pending (queued packets are free in etharp_free_entry) */
395       i = old_queue;
396       LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_find_entry: selecting oldest pending entry %"U16_F", freeing packet queue %p\n", (u16_t)i, (void *)(arp_table[i].q)));
397       /* no empty or recyclable entries found */
398     } else {
399       LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_find_entry: no empty or recyclable entries found\n"));
400       return (s8_t)ERR_MEM;
401     }
402 
403     /* { empty or recyclable entry found } */
404     LWIP_ASSERT("i < ARP_TABLE_SIZE", i < ARP_TABLE_SIZE);
405     etharp_free_entry(i);
406   }
407 
408   LWIP_ASSERT("i < ARP_TABLE_SIZE", i < ARP_TABLE_SIZE);
409   LWIP_ASSERT("arp_table[i].state == ETHARP_STATE_EMPTY",
410     arp_table[i].state == ETHARP_STATE_EMPTY);
411 
412   /* IP address given? */
413   if (ipaddr != NULL) {
414     /* set IP address */
415     ip4_addr_copy(arp_table[i].ipaddr, *ipaddr);
416   }
417   arp_table[i].ctime = 0;
418 #if ETHARP_TABLE_MATCH_NETIF
419   arp_table[i].netif = netif;
420 #endif /* ETHARP_TABLE_MATCH_NETIF*/
421   return (err_t)i;
422 }
423 
424 /**
425  * Update (or insert) a IP/MAC address pair in the ARP cache.
426  *
427  * If a pending entry is resolved, any queued packets will be sent
428  * at this point.
429  *
430  * @param netif netif related to this entry (used for NETIF_ADDRHINT)
431  * @param ipaddr IP address of the inserted ARP entry.
432  * @param ethaddr Ethernet address of the inserted ARP entry.
433  * @param flags See @ref etharp_state
434  *
435  * @return
436  * - ERR_OK Successfully updated ARP cache.
437  * - ERR_MEM If we could not add a new ARP entry when ETHARP_FLAG_TRY_HARD was set.
438  * - ERR_ARG Non-unicast address given, those will not appear in ARP cache.
439  *
440  * @see pbuf_free()
441  */
442 static err_t
etharp_update_arp_entry(struct netif * netif,const ip4_addr_t * ipaddr,struct eth_addr * ethaddr,u8_t flags)443 etharp_update_arp_entry(struct netif *netif, const ip4_addr_t *ipaddr, struct eth_addr *ethaddr, u8_t flags)
444 {
445   s8_t i;
446   LWIP_ASSERT("netif->hwaddr_len == ETH_HWADDR_LEN", netif->hwaddr_len == ETH_HWADDR_LEN);
447   LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_update_arp_entry: %"U16_F".%"U16_F".%"U16_F".%"U16_F" - %02"X16_F":%02"X16_F":%02"X16_F":%02"X16_F":%02"X16_F":%02"X16_F"\n",
448     ip4_addr1_16(ipaddr), ip4_addr2_16(ipaddr), ip4_addr3_16(ipaddr), ip4_addr4_16(ipaddr),
449     (u16_t)ethaddr->addr[0], (u16_t)ethaddr->addr[1], (u16_t)ethaddr->addr[2],
450     (u16_t)ethaddr->addr[3], (u16_t)ethaddr->addr[4], (u16_t)ethaddr->addr[5]));
451   /* non-unicast address? */
452   if (ip4_addr_isany(ipaddr) ||
453       ip4_addr_isbroadcast(ipaddr, netif) ||
454       ip4_addr_ismulticast(ipaddr)) {
455     LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_update_arp_entry: will not add non-unicast IP address to ARP cache\n"));
456     return ERR_ARG;
457   }
458   /* find or create ARP entry */
459   i = etharp_find_entry(ipaddr, flags, netif);
460   /* bail out if no entry could be found */
461   if (i < 0) {
462     return (err_t)i;
463   }
464 
465 #if ETHARP_SUPPORT_STATIC_ENTRIES
466   if (flags & ETHARP_FLAG_STATIC_ENTRY) {
467     /* record static type */
468     arp_table[i].state = ETHARP_STATE_STATIC;
469   } else if (arp_table[i].state == ETHARP_STATE_STATIC) {
470     /* found entry is a static type, don't overwrite it */
471     return ERR_VAL;
472   } else
473 #endif /* ETHARP_SUPPORT_STATIC_ENTRIES */
474   {
475     /* mark it stable */
476     arp_table[i].state = ETHARP_STATE_STABLE;
477   }
478 
479   /* record network interface */
480   arp_table[i].netif = netif;
481   /* insert in SNMP ARP index tree */
482   mib2_add_arp_entry(netif, &arp_table[i].ipaddr);
483 
484   LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_update_arp_entry: updating stable entry %"S16_F"\n", (s16_t)i));
485   /* update address */
486   ETHADDR32_COPY(&arp_table[i].ethaddr, ethaddr);
487   /* reset time stamp */
488   arp_table[i].ctime = 0;
489   /* this is where we will send out queued packets! */
490 #if ARP_QUEUEING
491   while (arp_table[i].q != NULL) {
492     struct pbuf *p;
493     /* remember remainder of queue */
494     struct etharp_q_entry *q = arp_table[i].q;
495     /* pop first item off the queue */
496     arp_table[i].q = q->next;
497     /* get the packet pointer */
498     p = q->p;
499     /* now queue entry can be freed */
500     memp_free(MEMP_ARP_QUEUE, q);
501 #else /* ARP_QUEUEING */
502   if (arp_table[i].q != NULL) {
503     struct pbuf *p = arp_table[i].q;
504     arp_table[i].q = NULL;
505 #endif /* ARP_QUEUEING */
506     /* send the queued IP packet */
507     ethernet_output(netif, p, (struct eth_addr*)(netif->hwaddr), ethaddr, ETHTYPE_IP);
508     /* free the queued IP packet */
509     pbuf_free(p);
510   }
511   return ERR_OK;
512 }
513 
514 #if ETHARP_SUPPORT_STATIC_ENTRIES
515 /** Add a new static entry to the ARP table. If an entry exists for the
516  * specified IP address, this entry is overwritten.
517  * If packets are queued for the specified IP address, they are sent out.
518  *
519  * @param ipaddr IP address for the new static entry
520  * @param ethaddr ethernet address for the new static entry
521  * @return See return values of etharp_add_static_entry
522  */
523 err_t
524 etharp_add_static_entry(const ip4_addr_t *ipaddr, struct eth_addr *ethaddr)
525 {
526   struct netif *netif;
527   LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_add_static_entry: %"U16_F".%"U16_F".%"U16_F".%"U16_F" - %02"X16_F":%02"X16_F":%02"X16_F":%02"X16_F":%02"X16_F":%02"X16_F"\n",
528     ip4_addr1_16(ipaddr), ip4_addr2_16(ipaddr), ip4_addr3_16(ipaddr), ip4_addr4_16(ipaddr),
529     (u16_t)ethaddr->addr[0], (u16_t)ethaddr->addr[1], (u16_t)ethaddr->addr[2],
530     (u16_t)ethaddr->addr[3], (u16_t)ethaddr->addr[4], (u16_t)ethaddr->addr[5]));
531 
532   netif = ip4_route(ipaddr);
533   if (netif == NULL) {
534     return ERR_RTE;
535   }
536 
537   return etharp_update_arp_entry(netif, ipaddr, ethaddr, ETHARP_FLAG_TRY_HARD | ETHARP_FLAG_STATIC_ENTRY);
538 }
539 
540 /** Remove a static entry from the ARP table previously added with a call to
541  * etharp_add_static_entry.
542  *
543  * @param ipaddr IP address of the static entry to remove
544  * @return ERR_OK: entry removed
545  *         ERR_MEM: entry wasn't found
546  *         ERR_ARG: entry wasn't a static entry but a dynamic one
547  */
548 err_t
549 etharp_remove_static_entry(const ip4_addr_t *ipaddr)
550 {
551   s8_t i;
552   LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_remove_static_entry: %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n",
553     ip4_addr1_16(ipaddr), ip4_addr2_16(ipaddr), ip4_addr3_16(ipaddr), ip4_addr4_16(ipaddr)));
554 
555   /* find or create ARP entry */
556   i = etharp_find_entry(ipaddr, ETHARP_FLAG_FIND_ONLY, NULL);
557   /* bail out if no entry could be found */
558   if (i < 0) {
559     return (err_t)i;
560   }
561 
562   if (arp_table[i].state != ETHARP_STATE_STATIC) {
563     /* entry wasn't a static entry, cannot remove it */
564     return ERR_ARG;
565   }
566   /* entry found, free it */
567   etharp_free_entry(i);
568   return ERR_OK;
569 }
570 #endif /* ETHARP_SUPPORT_STATIC_ENTRIES */
571 
572 /**
573  * Remove all ARP table entries of the specified netif.
574  *
575  * @param netif points to a network interface
576  */
577 void
578 etharp_cleanup_netif(struct netif *netif)
579 {
580   u8_t i;
581 
582   for (i = 0; i < ARP_TABLE_SIZE; ++i) {
583     u8_t state = arp_table[i].state;
584     if ((state != ETHARP_STATE_EMPTY) && (arp_table[i].netif == netif)) {
585       etharp_free_entry(i);
586     }
587   }
588 }
589 
590 /**
591  * Finds (stable) ethernet/IP address pair from ARP table
592  * using interface and IP address index.
593  * @note the addresses in the ARP table are in network order!
594  *
595  * @param netif points to interface index
596  * @param ipaddr points to the (network order) IP address index
597  * @param eth_ret points to return pointer
598  * @param ip_ret points to return pointer
599  * @return table index if found, -1 otherwise
600  */
601 s8_t
602 etharp_find_addr(struct netif *netif, const ip4_addr_t *ipaddr,
603          struct eth_addr **eth_ret, const ip4_addr_t **ip_ret)
604 {
605   s8_t i;
606 
607   LWIP_ASSERT("eth_ret != NULL && ip_ret != NULL",
608     eth_ret != NULL && ip_ret != NULL);
609 
610   LWIP_UNUSED_ARG(netif);
611 
612   i = etharp_find_entry(ipaddr, ETHARP_FLAG_FIND_ONLY, netif);
613   if ((i >= 0) && (arp_table[i].state >= ETHARP_STATE_STABLE)) {
614       *eth_ret = &arp_table[i].ethaddr;
615       *ip_ret = &arp_table[i].ipaddr;
616       return i;
617   }
618   return -1;
619 }
620 
621 /**
622  * Possibility to iterate over stable ARP table entries
623  *
624  * @param i entry number, 0 to ARP_TABLE_SIZE
625  * @param ipaddr return value: IP address
626  * @param netif return value: points to interface
627  * @param eth_ret return value: ETH address
628  * @return 1 on valid index, 0 otherwise
629  */
630 u8_t
631 etharp_get_entry(u8_t i, ip4_addr_t **ipaddr, struct netif **netif, struct eth_addr **eth_ret)
632 {
633   LWIP_ASSERT("ipaddr != NULL", ipaddr != NULL);
634   LWIP_ASSERT("netif != NULL", netif != NULL);
635   LWIP_ASSERT("eth_ret != NULL", eth_ret != NULL);
636 
637   if((i < ARP_TABLE_SIZE) && (arp_table[i].state >= ETHARP_STATE_STABLE)) {
638     *ipaddr  = &arp_table[i].ipaddr;
639     *netif   = arp_table[i].netif;
640     *eth_ret = &arp_table[i].ethaddr;
641     return 1;
642   } else {
643     return 0;
644   }
645 }
646 
647 /**
648  * Responds to ARP requests to us. Upon ARP replies to us, add entry to cache
649  * send out queued IP packets. Updates cache with snooped address pairs.
650  *
651  * Should be called for incoming ARP packets. The pbuf in the argument
652  * is freed by this function.
653  *
654  * @param p The ARP packet that arrived on netif. Is freed by this function.
655  * @param netif The lwIP network interface on which the ARP packet pbuf arrived.
656  *
657  * @see pbuf_free()
658  */
659 void
660 etharp_input(struct pbuf *p, struct netif *netif)
661 {
662   struct etharp_hdr *hdr;
663   /* these are aligned properly, whereas the ARP header fields might not be */
664   ip4_addr_t sipaddr, dipaddr;
665   u8_t for_us;
666 
667   LWIP_ERROR("netif != NULL", (netif != NULL), return;);
668 
669   hdr = (struct etharp_hdr *)p->payload;
670 
671   /* RFC 826 "Packet Reception": */
672   if ((hdr->hwtype != PP_HTONS(HWTYPE_ETHERNET)) ||
673       (hdr->hwlen != ETH_HWADDR_LEN) ||
674       (hdr->protolen != sizeof(ip4_addr_t)) ||
675       (hdr->proto != PP_HTONS(ETHTYPE_IP)))  {
676     LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING,
677       ("etharp_input: packet dropped, wrong hw type, hwlen, proto, protolen or ethernet type (%"U16_F"/%"U16_F"/%"U16_F"/%"U16_F")\n",
678       hdr->hwtype, (u16_t)hdr->hwlen, hdr->proto, (u16_t)hdr->protolen));
679     ETHARP_STATS_INC(etharp.proterr);
680     ETHARP_STATS_INC(etharp.drop);
681     pbuf_free(p);
682     return;
683   }
684   ETHARP_STATS_INC(etharp.recv);
685 
686 #if LWIP_AUTOIP
687   /* We have to check if a host already has configured our random
688    * created link local address and continuously check if there is
689    * a host with this IP-address so we can detect collisions */
690   autoip_arp_reply(netif, hdr);
691 #endif /* LWIP_AUTOIP */
692 
693   /* Copy struct ip4_addr2 to aligned ip4_addr, to support compilers without
694    * structure packing (not using structure copy which breaks strict-aliasing rules). */
695   IPADDR2_COPY(&sipaddr, &hdr->sipaddr);
696   IPADDR2_COPY(&dipaddr, &hdr->dipaddr);
697 
698   /* this interface is not configured? */
699   if (ip4_addr_isany_val(*netif_ip4_addr(netif))) {
700     for_us = 0;
701   } else {
702     /* ARP packet directed to us? */
703     for_us = (u8_t)ip4_addr_cmp(&dipaddr, netif_ip4_addr(netif));
704   }
705 
706   /* ARP message directed to us?
707       -> add IP address in ARP cache; assume requester wants to talk to us,
708          can result in directly sending the queued packets for this host.
709      ARP message not directed to us?
710       ->  update the source IP address in the cache, if present */
711   etharp_update_arp_entry(netif, &sipaddr, &(hdr->shwaddr),
712                    for_us ? ETHARP_FLAG_TRY_HARD : ETHARP_FLAG_FIND_ONLY);
713 
714   /* now act on the message itself */
715   switch (hdr->opcode) {
716   /* ARP request? */
717   case PP_HTONS(ARP_REQUEST):
718     /* ARP request. If it asked for our address, we send out a
719      * reply. In any case, we time-stamp any existing ARP entry,
720      * and possibly send out an IP packet that was queued on it. */
721 
722     LWIP_DEBUGF (ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_input: incoming ARP request\n"));
723     /* ARP request for our address? */
724     if (for_us) {
725 
726       LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_input: replying to ARP request for our IP address\n"));
727       /* Re-use pbuf to send ARP reply.
728          Since we are re-using an existing pbuf, we can't call etharp_raw since
729          that would allocate a new pbuf. */
730       hdr->opcode = lwip_htons(ARP_REPLY);
731 
732       IPADDR2_COPY(&hdr->dipaddr, &hdr->sipaddr);
733       IPADDR2_COPY(&hdr->sipaddr, netif_ip4_addr(netif));
734 
735       LWIP_ASSERT("netif->hwaddr_len must be the same as ETH_HWADDR_LEN for etharp!",
736                   (netif->hwaddr_len == ETH_HWADDR_LEN));
737 
738       /* hwtype, hwaddr_len, proto, protolen and the type in the ethernet header
739          are already correct, we tested that before */
740 
741       ETHADDR16_COPY(&hdr->dhwaddr, &hdr->shwaddr);
742       ETHADDR16_COPY(&hdr->shwaddr, netif->hwaddr);
743 
744       /* return ARP reply */
745 #if LWIP_AUTOIP
746       /* If we are using Link-Local, all ARP packets that contain a Link-Local
747        * 'sender IP address' MUST be sent using link-layer broadcast instead of
748        * link-layer unicast. (See RFC3927 Section 2.5, last paragraph) */
749       if (ip4_addr_islinklocal(netif_ip4_addr(netif))) {
750         ethernet_output(netif, p, &hdr->shwaddr, &ethbroadcast, ETHTYPE_ARP);
751       } else
752 #endif /* LWIP_AUTOIP */
753       {
754         ethernet_output(netif, p, &hdr->shwaddr, &hdr->dhwaddr, ETHTYPE_ARP);
755       }
756 
757     /* we are not configured? */
758     } else if (ip4_addr_isany_val(*netif_ip4_addr(netif))) {
759       /* { for_us == 0 and netif->ip_addr.addr == 0 } */
760       LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_input: we are unconfigured, ARP request ignored.\n"));
761     /* request was not directed to us */
762     } else {
763       /* { for_us == 0 and netif->ip_addr.addr != 0 } */
764       LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_input: ARP request was not for us.\n"));
765     }
766     break;
767   case PP_HTONS(ARP_REPLY):
768     /* ARP reply. We already updated the ARP cache earlier. */
769     LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_input: incoming ARP reply\n"));
770 #if (LWIP_DHCP && DHCP_DOES_ARP_CHECK)
771     /* DHCP wants to know about ARP replies from any host with an
772      * IP address also offered to us by the DHCP server. We do not
773      * want to take a duplicate IP address on a single network.
774      * @todo How should we handle redundant (fail-over) interfaces? */
775     dhcp_arp_reply(netif, &sipaddr);
776 #endif /* (LWIP_DHCP && DHCP_DOES_ARP_CHECK) */
777     break;
778   default:
779     LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_input: ARP unknown opcode type %"S16_F"\n", lwip_htons(hdr->opcode)));
780     ETHARP_STATS_INC(etharp.err);
781     break;
782   }
783   /* free ARP packet */
784   pbuf_free(p);
785 }
786 
787 /** Just a small helper function that sends a pbuf to an ethernet address
788  * in the arp_table specified by the index 'arp_idx'.
789  */
790 static err_t
791 etharp_output_to_arp_index(struct netif *netif, struct pbuf *q, u8_t arp_idx)
792 {
793   LWIP_ASSERT("arp_table[arp_idx].state >= ETHARP_STATE_STABLE",
794               arp_table[arp_idx].state >= ETHARP_STATE_STABLE);
795   /* if arp table entry is about to expire: re-request it,
796      but only if its state is ETHARP_STATE_STABLE to prevent flooding the
797      network with ARP requests if this address is used frequently. */
798   if (arp_table[arp_idx].state == ETHARP_STATE_STABLE) {
799     if (arp_table[arp_idx].ctime >= ARP_AGE_REREQUEST_USED_BROADCAST) {
800       /* issue a standard request using broadcast */
801       if (etharp_request(netif, &arp_table[arp_idx].ipaddr) == ERR_OK) {
802         arp_table[arp_idx].state = ETHARP_STATE_STABLE_REREQUESTING_1;
803       }
804     } else if (arp_table[arp_idx].ctime >= ARP_AGE_REREQUEST_USED_UNICAST) {
805       /* issue a unicast request (for 15 seconds) to prevent unnecessary broadcast */
806       if (etharp_request_dst(netif, &arp_table[arp_idx].ipaddr, &arp_table[arp_idx].ethaddr) == ERR_OK) {
807         arp_table[arp_idx].state = ETHARP_STATE_STABLE_REREQUESTING_1;
808       }
809     }
810   }
811 
812   return ethernet_output(netif, q, (struct eth_addr*)(netif->hwaddr), &arp_table[arp_idx].ethaddr, ETHTYPE_IP);
813 }
814 
815 /**
816  * Resolve and fill-in Ethernet address header for outgoing IP packet.
817  *
818  * For IP multicast and broadcast, corresponding Ethernet addresses
819  * are selected and the packet is transmitted on the link.
820  *
821  * For unicast addresses, the packet is submitted to etharp_query(). In
822  * case the IP address is outside the local network, the IP address of
823  * the gateway is used.
824  *
825  * @param netif The lwIP network interface which the IP packet will be sent on.
826  * @param q The pbuf(s) containing the IP packet to be sent.
827  * @param ipaddr The IP address of the packet destination.
828  *
829  * @return
830  * - ERR_RTE No route to destination (no gateway to external networks),
831  * or the return type of either etharp_query() or ethernet_output().
832  */
833 err_t
834 etharp_output(struct netif *netif, struct pbuf *q, const ip4_addr_t *ipaddr)
835 {
836   const struct eth_addr *dest;
837   struct eth_addr mcastaddr;
838   const ip4_addr_t *dst_addr = ipaddr;
839 
840   LWIP_ASSERT("netif != NULL", netif != NULL);
841   LWIP_ASSERT("q != NULL", q != NULL);
842   LWIP_ASSERT("ipaddr != NULL", ipaddr != NULL);
843 
844   /* Determine on destination hardware address. Broadcasts and multicasts
845    * are special, other IP addresses are looked up in the ARP table. */
846 
847   /* broadcast destination IP address? */
848   if (ip4_addr_isbroadcast(ipaddr, netif)) {
849     /* broadcast on Ethernet also */
850     dest = (const struct eth_addr *)&ethbroadcast;
851   /* multicast destination IP address? */
852   } else if (ip4_addr_ismulticast(ipaddr)) {
853     /* Hash IP multicast address to MAC address.*/
854     mcastaddr.addr[0] = LL_IP4_MULTICAST_ADDR_0;
855     mcastaddr.addr[1] = LL_IP4_MULTICAST_ADDR_1;
856     mcastaddr.addr[2] = LL_IP4_MULTICAST_ADDR_2;
857     mcastaddr.addr[3] = ip4_addr2(ipaddr) & 0x7f;
858     mcastaddr.addr[4] = ip4_addr3(ipaddr);
859     mcastaddr.addr[5] = ip4_addr4(ipaddr);
860     /* destination Ethernet address is multicast */
861     dest = &mcastaddr;
862   /* unicast destination IP address? */
863   } else {
864     s8_t i;
865     /* outside local network? if so, this can neither be a global broadcast nor
866        a subnet broadcast. */
867     if (!ip4_addr_netcmp(ipaddr, netif_ip4_addr(netif), netif_ip4_netmask(netif)) &&
868         !ip4_addr_islinklocal(ipaddr)) {
869 #if LWIP_AUTOIP
870       struct ip_hdr *iphdr = (struct ip_hdr*)(size_t)q->payload;
871       /* According to RFC 3297, chapter 2.6.2 (Forwarding Rules), a packet with
872          a link-local source address must always be "directly to its destination
873          on the same physical link. The host MUST NOT send the packet to any
874          router for forwarding". */
875       if (!ip4_addr_islinklocal(&iphdr->src))
876 #endif /* LWIP_AUTOIP */
877       {
878 #ifdef LWIP_HOOK_ETHARP_GET_GW
879         /* For advanced routing, a single default gateway might not be enough, so get
880            the IP address of the gateway to handle the current destination address. */
881         dst_addr = LWIP_HOOK_ETHARP_GET_GW(netif, ipaddr);
882         if (dst_addr == NULL)
883 #endif /* LWIP_HOOK_ETHARP_GET_GW */
884         {
885           /* interface has default gateway? */
886           if (!ip4_addr_isany_val(*netif_ip4_gw(netif))) {
887             /* send to hardware address of default gateway IP address */
888             dst_addr = netif_ip4_gw(netif);
889           /* no default gateway available */
890           } else {
891             /* no route to destination error (default gateway missing) */
892             return ERR_RTE;
893           }
894         }
895       }
896     }
897 #if LWIP_NETIF_HWADDRHINT
898     if (netif->addr_hint != NULL) {
899       /* per-pcb cached entry was given */
900       u8_t etharp_cached_entry = *(netif->addr_hint);
901       if (etharp_cached_entry < ARP_TABLE_SIZE) {
902 #endif /* LWIP_NETIF_HWADDRHINT */
903         if ((arp_table[etharp_cached_entry].state >= ETHARP_STATE_STABLE) &&
904 #if ETHARP_TABLE_MATCH_NETIF
905             (arp_table[etharp_cached_entry].netif == netif) &&
906 #endif
907             (ip4_addr_cmp(dst_addr, &arp_table[etharp_cached_entry].ipaddr))) {
908           /* the per-pcb-cached entry is stable and the right one! */
909           ETHARP_STATS_INC(etharp.cachehit);
910           return etharp_output_to_arp_index(netif, q, etharp_cached_entry);
911         }
912 #if LWIP_NETIF_HWADDRHINT
913       }
914     }
915 #endif /* LWIP_NETIF_HWADDRHINT */
916 
917     /* find stable entry: do this here since this is a critical path for
918        throughput and etharp_find_entry() is kind of slow */
919     for (i = 0; i < ARP_TABLE_SIZE; i++) {
920       if ((arp_table[i].state >= ETHARP_STATE_STABLE) &&
921 #if ETHARP_TABLE_MATCH_NETIF
922           (arp_table[i].netif == netif) &&
923 #endif
924           (ip4_addr_cmp(dst_addr, &arp_table[i].ipaddr))) {
925         /* found an existing, stable entry */
926         ETHARP_SET_HINT(netif, i);
927         return etharp_output_to_arp_index(netif, q, i);
928       }
929     }
930     /* no stable entry found, use the (slower) query function:
931        queue on destination Ethernet address belonging to ipaddr */
932     return etharp_query(netif, dst_addr, q);
933   }
934 
935   /* continuation for multicast/broadcast destinations */
936   /* obtain source Ethernet address of the given interface */
937   /* send packet directly on the link */
938   return ethernet_output(netif, q, (struct eth_addr*)(netif->hwaddr), dest, ETHTYPE_IP);
939 }
940 
941 /**
942  * Send an ARP request for the given IP address and/or queue a packet.
943  *
944  * If the IP address was not yet in the cache, a pending ARP cache entry
945  * is added and an ARP request is sent for the given address. The packet
946  * is queued on this entry.
947  *
948  * If the IP address was already pending in the cache, a new ARP request
949  * is sent for the given address. The packet is queued on this entry.
950  *
951  * If the IP address was already stable in the cache, and a packet is
952  * given, it is directly sent and no ARP request is sent out.
953  *
954  * If the IP address was already stable in the cache, and no packet is
955  * given, an ARP request is sent out.
956  *
957  * @param netif The lwIP network interface on which ipaddr
958  * must be queried for.
959  * @param ipaddr The IP address to be resolved.
960  * @param q If non-NULL, a pbuf that must be delivered to the IP address.
961  * q is not freed by this function.
962  *
963  * @note q must only be ONE packet, not a packet queue!
964  *
965  * @return
966  * - ERR_BUF Could not make room for Ethernet header.
967  * - ERR_MEM Hardware address unknown, and no more ARP entries available
968  *   to query for address or queue the packet.
969  * - ERR_MEM Could not queue packet due to memory shortage.
970  * - ERR_RTE No route to destination (no gateway to external networks).
971  * - ERR_ARG Non-unicast address given, those will not appear in ARP cache.
972  *
973  */
974 err_t
975 etharp_query(struct netif *netif, const ip4_addr_t *ipaddr, struct pbuf *q)
976 {
977   struct eth_addr * srcaddr = (struct eth_addr *)netif->hwaddr;
978   err_t result = ERR_MEM;
979   int is_new_entry = 0;
980   s8_t i; /* ARP entry index */
981 
982   /* non-unicast address? */
983   if (ip4_addr_isbroadcast(ipaddr, netif) ||
984       ip4_addr_ismulticast(ipaddr) ||
985       ip4_addr_isany(ipaddr)) {
986     LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: will not add non-unicast IP address to ARP cache\n"));
987     return ERR_ARG;
988   }
989 
990   /* find entry in ARP cache, ask to create entry if queueing packet */
991   i = etharp_find_entry(ipaddr, ETHARP_FLAG_TRY_HARD, netif);
992 
993   /* could not find or create entry? */
994   if (i < 0) {
995     LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: could not create ARP entry\n"));
996     if (q) {
997       LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: packet dropped\n"));
998       ETHARP_STATS_INC(etharp.memerr);
999     }
1000     return (err_t)i;
1001   }
1002 
1003   /* mark a fresh entry as pending (we just sent a request) */
1004   if (arp_table[i].state == ETHARP_STATE_EMPTY) {
1005     is_new_entry = 1;
1006     arp_table[i].state = ETHARP_STATE_PENDING;
1007     /* record network interface for re-sending arp request in etharp_tmr */
1008     arp_table[i].netif = netif;
1009   }
1010 
1011   /* { i is either a STABLE or (new or existing) PENDING entry } */
1012   LWIP_ASSERT("arp_table[i].state == PENDING or STABLE",
1013   ((arp_table[i].state == ETHARP_STATE_PENDING) ||
1014    (arp_table[i].state >= ETHARP_STATE_STABLE)));
1015 
1016   /* do we have a new entry? or an implicit query request? */
1017   if (is_new_entry || (q == NULL)) {
1018     /* try to resolve it; send out ARP request */
1019     result = etharp_request(netif, ipaddr);
1020     if (result != ERR_OK) {
1021       /* ARP request couldn't be sent */
1022       /* We don't re-send arp request in etharp_tmr, but we still queue packets,
1023          since this failure could be temporary, and the next packet calling
1024          etharp_query again could lead to sending the queued packets. */
1025     }
1026     if (q == NULL) {
1027       return result;
1028     }
1029   }
1030 
1031   /* packet given? */
1032   LWIP_ASSERT("q != NULL", q != NULL);
1033   /* stable entry? */
1034   if (arp_table[i].state >= ETHARP_STATE_STABLE) {
1035     /* we have a valid IP->Ethernet address mapping */
1036     ETHARP_SET_HINT(netif, i);
1037     /* send the packet */
1038     result = ethernet_output(netif, q, srcaddr, &(arp_table[i].ethaddr), ETHTYPE_IP);
1039   /* pending entry? (either just created or already pending */
1040   } else if (arp_table[i].state == ETHARP_STATE_PENDING) {
1041     /* entry is still pending, queue the given packet 'q' */
1042     struct pbuf *p;
1043     int copy_needed = 0;
1044     /* IF q includes a PBUF_REF, PBUF_POOL or PBUF_RAM, we have no choice but
1045      * to copy the whole queue into a new PBUF_RAM (see bug #11400)
1046      * PBUF_ROMs can be left as they are, since ROM must not get changed. */
1047     p = q;
1048     while (p) {
1049       LWIP_ASSERT("no packet queues allowed!", (p->len != p->tot_len) || (p->next == 0));
1050       if (p->type != PBUF_ROM) {
1051         copy_needed = 1;
1052         break;
1053       }
1054       p = p->next;
1055     }
1056     if (copy_needed) {
1057       /* copy the whole packet into new pbufs */
1058       p = pbuf_alloc(PBUF_LINK, p->tot_len, PBUF_RAM);
1059       if (p != NULL) {
1060         if (pbuf_copy(p, q) != ERR_OK) {
1061           pbuf_free(p);
1062           p = NULL;
1063         }
1064       }
1065     } else {
1066       /* referencing the old pbuf is enough */
1067       p = q;
1068       pbuf_ref(p);
1069     }
1070     /* packet could be taken over? */
1071     if (p != NULL) {
1072       /* queue packet ... */
1073 #if ARP_QUEUEING
1074       struct etharp_q_entry *new_entry;
1075       /* allocate a new arp queue entry */
1076       new_entry = (struct etharp_q_entry *)memp_malloc(MEMP_ARP_QUEUE);
1077       if (new_entry != NULL) {
1078         unsigned int qlen = 0;
1079         new_entry->next = 0;
1080         new_entry->p = p;
1081         if (arp_table[i].q != NULL) {
1082           /* queue was already existent, append the new entry to the end */
1083           struct etharp_q_entry *r;
1084           r = arp_table[i].q;
1085           qlen++;
1086           while (r->next != NULL) {
1087             r = r->next;
1088             qlen++;
1089           }
1090           r->next = new_entry;
1091         } else {
1092           /* queue did not exist, first item in queue */
1093           arp_table[i].q = new_entry;
1094         }
1095 #if ARP_QUEUE_LEN
1096         if (qlen >= ARP_QUEUE_LEN) {
1097           struct etharp_q_entry *old;
1098           old = arp_table[i].q;
1099           arp_table[i].q = arp_table[i].q->next;
1100           pbuf_free(old->p);
1101           memp_free(MEMP_ARP_QUEUE, old);
1102         }
1103 #endif
1104         LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: queued packet %p on ARP entry %"S16_F"\n", (void *)q, (s16_t)i));
1105         result = ERR_OK;
1106       } else {
1107         /* the pool MEMP_ARP_QUEUE is empty */
1108         pbuf_free(p);
1109         LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: could not queue a copy of PBUF_REF packet %p (out of memory)\n", (void *)q));
1110         result = ERR_MEM;
1111       }
1112 #else /* ARP_QUEUEING */
1113       /* always queue one packet per ARP request only, freeing a previously queued packet */
1114       if (arp_table[i].q != NULL) {
1115         LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: dropped previously queued packet %p for ARP entry %"S16_F"\n", (void *)q, (s16_t)i));
1116         pbuf_free(arp_table[i].q);
1117       }
1118       arp_table[i].q = p;
1119       result = ERR_OK;
1120       LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: queued packet %p on ARP entry %"S16_F"\n", (void *)q, (s16_t)i));
1121 #endif /* ARP_QUEUEING */
1122     } else {
1123       ETHARP_STATS_INC(etharp.memerr);
1124       LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: could not queue a copy of PBUF_REF packet %p (out of memory)\n", (void *)q));
1125       result = ERR_MEM;
1126     }
1127   }
1128   return result;
1129 }
1130 
1131 /**
1132  * Send a raw ARP packet (opcode and all addresses can be modified)
1133  *
1134  * @param netif the lwip network interface on which to send the ARP packet
1135  * @param ethsrc_addr the source MAC address for the ethernet header
1136  * @param ethdst_addr the destination MAC address for the ethernet header
1137  * @param hwsrc_addr the source MAC address for the ARP protocol header
1138  * @param ipsrc_addr the source IP address for the ARP protocol header
1139  * @param hwdst_addr the destination MAC address for the ARP protocol header
1140  * @param ipdst_addr the destination IP address for the ARP protocol header
1141  * @param opcode the type of the ARP packet
1142  * @return ERR_OK if the ARP packet has been sent
1143  *         ERR_MEM if the ARP packet couldn't be allocated
1144  *         any other err_t on failure
1145  */
1146 static err_t
1147 etharp_raw(struct netif *netif, const struct eth_addr *ethsrc_addr,
1148            const struct eth_addr *ethdst_addr,
1149            const struct eth_addr *hwsrc_addr, const ip4_addr_t *ipsrc_addr,
1150            const struct eth_addr *hwdst_addr, const ip4_addr_t *ipdst_addr,
1151            const u16_t opcode)
1152 {
1153   struct pbuf *p;
1154   err_t result = ERR_OK;
1155   struct etharp_hdr *hdr;
1156 
1157   LWIP_ASSERT("netif != NULL", netif != NULL);
1158 
1159   /* allocate a pbuf for the outgoing ARP request packet */
1160   p = pbuf_alloc(PBUF_LINK, SIZEOF_ETHARP_HDR, PBUF_RAM);
1161   /* could allocate a pbuf for an ARP request? */
1162   if (p == NULL) {
1163     LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS,
1164       ("etharp_raw: could not allocate pbuf for ARP request.\n"));
1165     ETHARP_STATS_INC(etharp.memerr);
1166     return ERR_MEM;
1167   }
1168   LWIP_ASSERT("check that first pbuf can hold struct etharp_hdr",
1169               (p->len >= SIZEOF_ETHARP_HDR));
1170 
1171   hdr = (struct etharp_hdr *)p->payload;
1172   LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_raw: sending raw ARP packet.\n"));
1173   hdr->opcode = lwip_htons(opcode);
1174 
1175   LWIP_ASSERT("netif->hwaddr_len must be the same as ETH_HWADDR_LEN for etharp!",
1176               (netif->hwaddr_len == ETH_HWADDR_LEN));
1177 
1178   /* Write the ARP MAC-Addresses */
1179   ETHADDR16_COPY(&hdr->shwaddr, hwsrc_addr);
1180   ETHADDR16_COPY(&hdr->dhwaddr, hwdst_addr);
1181   /* Copy struct ip4_addr2 to aligned ip4_addr, to support compilers without
1182    * structure packing. */
1183   IPADDR2_COPY(&hdr->sipaddr, ipsrc_addr);
1184   IPADDR2_COPY(&hdr->dipaddr, ipdst_addr);
1185 
1186   hdr->hwtype = PP_HTONS(HWTYPE_ETHERNET);
1187   hdr->proto = PP_HTONS(ETHTYPE_IP);
1188   /* set hwlen and protolen */
1189   hdr->hwlen = ETH_HWADDR_LEN;
1190   hdr->protolen = sizeof(ip4_addr_t);
1191 
1192   /* send ARP query */
1193 #if LWIP_AUTOIP
1194   /* If we are using Link-Local, all ARP packets that contain a Link-Local
1195    * 'sender IP address' MUST be sent using link-layer broadcast instead of
1196    * link-layer unicast. (See RFC3927 Section 2.5, last paragraph) */
1197   if(ip4_addr_islinklocal(ipsrc_addr)) {
1198     ethernet_output(netif, p, ethsrc_addr, &ethbroadcast, ETHTYPE_ARP);
1199   } else
1200 #endif /* LWIP_AUTOIP */
1201   {
1202     ethernet_output(netif, p, ethsrc_addr, ethdst_addr, ETHTYPE_ARP);
1203   }
1204 
1205   ETHARP_STATS_INC(etharp.xmit);
1206   /* free ARP query packet */
1207   pbuf_free(p);
1208   p = NULL;
1209   /* could not allocate pbuf for ARP request */
1210 
1211   return result;
1212 }
1213 
1214 /**
1215  * Send an ARP request packet asking for ipaddr to a specific eth address.
1216  * Used to send unicast request to refresh the ARP table just before an entry
1217  * times out
1218  *
1219  * @param netif the lwip network interface on which to send the request
1220  * @param ipaddr the IP address for which to ask
1221  * @param hw_dst_addr the ethernet address to send this packet to
1222  * @return ERR_OK if the request has been sent
1223  *         ERR_MEM if the ARP packet couldn't be allocated
1224  *         any other err_t on failure
1225  */
1226 static err_t
1227 etharp_request_dst(struct netif *netif, const ip4_addr_t *ipaddr, const struct eth_addr* hw_dst_addr)
1228 {
1229   return etharp_raw(netif, (struct eth_addr *)netif->hwaddr, hw_dst_addr,
1230                     (struct eth_addr *)netif->hwaddr, netif_ip4_addr(netif), &ethzero,
1231                     ipaddr, ARP_REQUEST);
1232 }
1233 
1234 /**
1235  * Send an ARP request packet asking for ipaddr.
1236  *
1237  * @param netif the lwip network interface on which to send the request
1238  * @param ipaddr the IP address for which to ask
1239  * @return ERR_OK if the request has been sent
1240  *         ERR_MEM if the ARP packet couldn't be allocated
1241  *         any other err_t on failure
1242  */
1243 err_t
1244 etharp_request(struct netif *netif, const ip4_addr_t *ipaddr)
1245 {
1246   LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_request: sending ARP request.\n"));
1247   return etharp_request_dst(netif, ipaddr, &ethbroadcast);
1248 }
1249 #endif /* LWIP_IPV4 && LWIP_ARP */
1250 
1251 #endif /* LWIP_ARP || LWIP_ETHERNET */
1252