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