]> rtime.felk.cvut.cz Git - pes-rpp/rpp-lwip.git/blob - src/netif/etharp.c
fixed bug #34684: Clear the arp table cache when netif is brought down
[pes-rpp/rpp-lwip.git] / src / netif / etharp.c
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/ip_addr.h"
51 #include "lwip/def.h"
52 #include "lwip/ip.h"
53 #include "lwip/stats.h"
54 #include "lwip/snmp.h"
55 #include "lwip/dhcp.h"
56 #include "lwip/autoip.h"
57 #include "netif/etharp.h"
58 #include "lwip/ip6.h"
59
60 #if PPPOE_SUPPORT
61 #include "netif/ppp_oe.h"
62 #endif /* PPPOE_SUPPORT */
63
64 #include <string.h>
65
66 const struct eth_addr ethbroadcast = {{0xff,0xff,0xff,0xff,0xff,0xff}};
67 const struct eth_addr ethzero = {{0,0,0,0,0,0}};
68
69 /** The 24-bit IANA multicast OUI is 01-00-5e: */
70 #define LL_MULTICAST_ADDR_0 0x01
71 #define LL_MULTICAST_ADDR_1 0x00
72 #define LL_MULTICAST_ADDR_2 0x5e
73
74 #if LWIP_ARP /* don't build if not configured for use in lwipopts.h */
75
76 /** the time an ARP entry stays valid after its last update,
77  *  for ARP_TMR_INTERVAL = 5000, this is
78  *  (240 * 5) seconds = 20 minutes.
79  */
80 #define ARP_MAXAGE              240
81 /** Re-request a used ARP entry 1 minute before it would expire to prevent
82  *  breaking a steadily used connection because the ARP entry timed out. */
83 #define ARP_AGE_REREQUEST_USED  (ARP_MAXAGE - 12)
84
85 /** the time an ARP entry stays pending after first request,
86  *  for ARP_TMR_INTERVAL = 5000, this is
87  *  (2 * 5) seconds = 10 seconds.
88  * 
89  *  @internal Keep this number at least 2, otherwise it might
90  *  run out instantly if the timeout occurs directly after a request.
91  */
92 #define ARP_MAXPENDING 2
93
94 #define HWTYPE_ETHERNET 1
95
96 enum etharp_state {
97   ETHARP_STATE_EMPTY = 0,
98   ETHARP_STATE_PENDING,
99   ETHARP_STATE_STABLE,
100   ETHARP_STATE_STABLE_REREQUESTING
101 #if ETHARP_SUPPORT_STATIC_ENTRIES
102   ,ETHARP_STATE_STATIC
103 #endif /* ETHARP_SUPPORT_STATIC_ENTRIES */
104 };
105
106 struct etharp_entry {
107 #if ARP_QUEUEING
108   /** Pointer to queue of pending outgoing packets on this ARP entry. */
109   struct etharp_q_entry *q;
110 #else /* ARP_QUEUEING */
111   /** Pointer to a single pending outgoing packet on this ARP entry. */
112   struct pbuf *q;
113 #endif /* ARP_QUEUEING */
114   ip_addr_t ipaddr;
115   struct netif *netif;
116   struct eth_addr ethaddr;
117   u8_t state;
118   u8_t ctime;
119 };
120
121 static struct etharp_entry arp_table[ARP_TABLE_SIZE];
122
123 #if !LWIP_NETIF_HWADDRHINT
124 static u8_t etharp_cached_entry;
125 #endif /* !LWIP_NETIF_HWADDRHINT */
126
127 /** Try hard to create a new entry - we want the IP address to appear in
128     the cache (even if this means removing an active entry or so). */
129 #define ETHARP_FLAG_TRY_HARD     1
130 #define ETHARP_FLAG_FIND_ONLY    2
131 #if ETHARP_SUPPORT_STATIC_ENTRIES
132 #define ETHARP_FLAG_STATIC_ENTRY 4
133 #endif /* ETHARP_SUPPORT_STATIC_ENTRIES */
134
135 #if LWIP_NETIF_HWADDRHINT
136 #define ETHARP_SET_HINT(netif, hint)  if (((netif) != NULL) && ((netif)->addr_hint != NULL))  \
137                                       *((netif)->addr_hint) = (hint);
138 #else /* LWIP_NETIF_HWADDRHINT */
139 #define ETHARP_SET_HINT(netif, hint)  (etharp_cached_entry = (hint))
140 #endif /* LWIP_NETIF_HWADDRHINT */
141
142
143 /* Some checks, instead of etharp_init(): */
144 #if (LWIP_ARP && (ARP_TABLE_SIZE > 0x7f))
145   #error "ARP_TABLE_SIZE must fit in an s8_t, you have to reduce it in your lwipopts.h"
146 #endif
147
148
149 #if ARP_QUEUEING
150 /**
151  * Free a complete queue of etharp entries
152  *
153  * @param q a qeueue of etharp_q_entry's to free
154  */
155 static void
156 free_etharp_q(struct etharp_q_entry *q)
157 {
158   struct etharp_q_entry *r;
159   LWIP_ASSERT("q != NULL", q != NULL);
160   LWIP_ASSERT("q->p != NULL", q->p != NULL);
161   while (q) {
162     r = q;
163     q = q->next;
164     LWIP_ASSERT("r->p != NULL", (r->p != NULL));
165     pbuf_free(r->p);
166     memp_free(MEMP_ARP_QUEUE, r);
167   }
168 }
169 #else /* ARP_QUEUEING */
170
171 /** Compatibility define: free the queued pbuf */
172 #define free_etharp_q(q) pbuf_free(q)
173
174 #endif /* ARP_QUEUEING */
175
176 /** Clean up ARP table entries */
177 static void
178 etharp_free_entry(int i)
179 {
180   /* remove from SNMP ARP index tree */
181   snmp_delete_arpidx_tree(arp_table[i].netif, &arp_table[i].ipaddr);
182   /* and empty packet queue */
183   if (arp_table[i].q != NULL) {
184     /* remove all queued packets */
185     LWIP_DEBUGF(ETHARP_DEBUG, ("etharp_free_entry: freeing entry %"U16_F", packet queue %p.\n", (u16_t)i, (void *)(arp_table[i].q)));
186     free_etharp_q(arp_table[i].q);
187     arp_table[i].q = NULL;
188   }
189   /* recycle entry for re-use */
190   arp_table[i].state = ETHARP_STATE_EMPTY;
191 #ifdef LWIP_DEBUG
192   /* for debugging, clean out the complete entry */
193   arp_table[i].ctime = 0;
194 #if LWIP_SNMP
195   arp_table[i].netif = NULL;
196 #endif /* LWIP_SNMP */
197   ip_addr_set_zero(&arp_table[i].ipaddr);
198   arp_table[i].ethaddr = ethzero;
199 #endif /* LWIP_DEBUG */
200 }
201
202 /**
203  * Clears expired entries in the ARP table.
204  *
205  * This function should be called every ETHARP_TMR_INTERVAL milliseconds (5 seconds),
206  * in order to expire entries in the ARP table.
207  */
208 void
209 etharp_tmr(void)
210 {
211   u8_t i;
212
213   LWIP_DEBUGF(ETHARP_DEBUG, ("etharp_timer\n"));
214   /* remove expired entries from the ARP table */
215   for (i = 0; i < ARP_TABLE_SIZE; ++i) {
216     u8_t state = arp_table[i].state;
217     if (state != ETHARP_STATE_EMPTY
218 #if ETHARP_SUPPORT_STATIC_ENTRIES
219       && (state != ETHARP_STATE_STATIC)
220 #endif /* ETHARP_SUPPORT_STATIC_ENTRIES */
221       ) {
222       arp_table[i].ctime++;
223       if ((arp_table[i].ctime >= ARP_MAXAGE) ||
224           ((arp_table[i].state == ETHARP_STATE_PENDING)  &&
225            (arp_table[i].ctime >= ARP_MAXPENDING))) {
226         /* pending or stable entry has become old! */
227         LWIP_DEBUGF(ETHARP_DEBUG, ("etharp_timer: expired %s entry %"U16_F".\n",
228              arp_table[i].state >= ETHARP_STATE_STABLE ? "stable" : "pending", (u16_t)i));
229         /* clean up entries that have just been expired */
230         etharp_free_entry(i);
231       }
232       else if (arp_table[i].state == ETHARP_STATE_STABLE_REREQUESTING) {
233         /* Reset state to stable, so that the next transmitted packet will
234            re-send an ARP request. */
235         arp_table[i].state = ETHARP_STATE_STABLE;
236       }
237 #if ARP_QUEUEING
238       /* still pending entry? (not expired) */
239       if (arp_table[i].state == ETHARP_STATE_PENDING) {
240         /* resend an ARP query here? */
241       }
242 #endif /* ARP_QUEUEING */
243     }
244   }
245 }
246
247 /**
248  * Search the ARP table for a matching or new entry.
249  * 
250  * If an IP address is given, return a pending or stable ARP entry that matches
251  * the address. If no match is found, create a new entry with this address set,
252  * but in state ETHARP_EMPTY. The caller must check and possibly change the
253  * state of the returned entry.
254  * 
255  * If ipaddr is NULL, return a initialized new entry in state ETHARP_EMPTY.
256  * 
257  * In all cases, attempt to create new entries from an empty entry. If no
258  * empty entries are available and ETHARP_FLAG_TRY_HARD flag is set, recycle
259  * old entries. Heuristic choose the least important entry for recycling.
260  *
261  * @param ipaddr IP address to find in ARP cache, or to add if not found.
262  * @param flags @see definition of ETHARP_FLAG_*
263  * @param netif netif related to this address (used for NETIF_HWADDRHINT)
264  *  
265  * @return The ARP entry index that matched or is created, ERR_MEM if no
266  * entry is found or could be recycled.
267  */
268 static s8_t
269 etharp_find_entry(ip_addr_t *ipaddr, u8_t flags)
270 {
271   s8_t old_pending = ARP_TABLE_SIZE, old_stable = ARP_TABLE_SIZE;
272   s8_t empty = ARP_TABLE_SIZE;
273   u8_t i = 0, age_pending = 0, age_stable = 0;
274   /* oldest entry with packets on queue */
275   s8_t old_queue = ARP_TABLE_SIZE;
276   /* its age */
277   u8_t age_queue = 0;
278
279   /**
280    * a) do a search through the cache, remember candidates
281    * b) select candidate entry
282    * c) create new entry
283    */
284
285   /* a) in a single search sweep, do all of this
286    * 1) remember the first empty entry (if any)
287    * 2) remember the oldest stable entry (if any)
288    * 3) remember the oldest pending entry without queued packets (if any)
289    * 4) remember the oldest pending entry with queued packets (if any)
290    * 5) search for a matching IP entry, either pending or stable
291    *    until 5 matches, or all entries are searched for.
292    */
293
294   for (i = 0; i < ARP_TABLE_SIZE; ++i) {
295     u8_t state = arp_table[i].state;
296     /* no empty entry found yet and now we do find one? */
297     if ((empty == ARP_TABLE_SIZE) && (state == ETHARP_STATE_EMPTY)) {
298       LWIP_DEBUGF(ETHARP_DEBUG, ("etharp_find_entry: found empty entry %"U16_F"\n", (u16_t)i));
299       /* remember first empty entry */
300       empty = i;
301     } else if (state != ETHARP_STATE_EMPTY) {
302       LWIP_ASSERT("state == ETHARP_STATE_PENDING || state >= ETHARP_STATE_STABLE",
303         state == ETHARP_STATE_PENDING || state >= ETHARP_STATE_STABLE);
304       /* if given, does IP address match IP address in ARP entry? */
305       if (ipaddr && ip_addr_cmp(ipaddr, &arp_table[i].ipaddr)) {
306         LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_find_entry: found matching entry %"U16_F"\n", (u16_t)i));
307         /* found exact IP address match, simply bail out */
308         return i;
309       }
310       /* pending entry? */
311       if (state == ETHARP_STATE_PENDING) {
312         /* pending with queued packets? */
313         if (arp_table[i].q != NULL) {
314           if (arp_table[i].ctime >= age_queue) {
315             old_queue = i;
316             age_queue = arp_table[i].ctime;
317           }
318         } else
319         /* pending without queued packets? */
320         {
321           if (arp_table[i].ctime >= age_pending) {
322             old_pending = i;
323             age_pending = arp_table[i].ctime;
324           }
325         }
326       /* stable entry? */
327       } else if (state >= ETHARP_STATE_STABLE) {
328 #if ETHARP_SUPPORT_STATIC_ENTRIES
329         /* don't record old_stable for static entries since they never expire */
330         if (state < ETHARP_STATE_STATIC)
331 #endif /* ETHARP_SUPPORT_STATIC_ENTRIES */
332         {
333           /* remember entry with oldest stable entry in oldest, its age in maxtime */
334           if (arp_table[i].ctime >= age_stable) {
335             old_stable = i;
336             age_stable = arp_table[i].ctime;
337           }
338         }
339       }
340     }
341   }
342   /* { we have no match } => try to create a new entry */
343    
344   /* don't create new entry, only search? */
345   if (((flags & ETHARP_FLAG_FIND_ONLY) != 0) ||
346       /* or no empty entry found and not allowed to recycle? */
347       ((empty == ARP_TABLE_SIZE) && ((flags & ETHARP_FLAG_TRY_HARD) == 0))) {
348     LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_find_entry: no empty entry found and not allowed to recycle\n"));
349     return (s8_t)ERR_MEM;
350   }
351   
352   /* b) choose the least destructive entry to recycle:
353    * 1) empty entry
354    * 2) oldest stable entry
355    * 3) oldest pending entry without queued packets
356    * 4) oldest pending entry with queued packets
357    * 
358    * { ETHARP_FLAG_TRY_HARD is set at this point }
359    */ 
360
361   /* 1) empty entry available? */
362   if (empty < ARP_TABLE_SIZE) {
363     i = empty;
364     LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_find_entry: selecting empty entry %"U16_F"\n", (u16_t)i));
365   } else {
366     /* 2) found recyclable stable entry? */
367     if (old_stable < ARP_TABLE_SIZE) {
368       /* recycle oldest stable*/
369       i = old_stable;
370       LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_find_entry: selecting oldest stable entry %"U16_F"\n", (u16_t)i));
371       /* no queued packets should exist on stable entries */
372       LWIP_ASSERT("arp_table[i].q == NULL", arp_table[i].q == NULL);
373     /* 3) found recyclable pending entry without queued packets? */
374     } else if (old_pending < ARP_TABLE_SIZE) {
375       /* recycle oldest pending */
376       i = old_pending;
377       LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_find_entry: selecting oldest pending entry %"U16_F" (without queue)\n", (u16_t)i));
378     /* 4) found recyclable pending entry with queued packets? */
379     } else if (old_queue < ARP_TABLE_SIZE) {
380       /* recycle oldest pending (queued packets are free in etharp_free_entry) */
381       i = old_queue;
382       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)));
383       /* no empty or recyclable entries found */
384     } else {
385       LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_find_entry: no empty or recyclable entries found\n"));
386       return (s8_t)ERR_MEM;
387     }
388
389     /* { empty or recyclable entry found } */
390     LWIP_ASSERT("i < ARP_TABLE_SIZE", i < ARP_TABLE_SIZE);
391     etharp_free_entry(i);
392   }
393
394   LWIP_ASSERT("i < ARP_TABLE_SIZE", i < ARP_TABLE_SIZE);
395   LWIP_ASSERT("arp_table[i].state == ETHARP_STATE_EMPTY",
396     arp_table[i].state == ETHARP_STATE_EMPTY);
397
398   /* IP address given? */
399   if (ipaddr != NULL) {
400     /* set IP address */
401     ip_addr_copy(arp_table[i].ipaddr, *ipaddr);
402   }
403   arp_table[i].ctime = 0;
404   return (err_t)i;
405 }
406
407 /**
408  * Send an IP packet on the network using netif->linkoutput
409  * The ethernet header is filled in before sending.
410  *
411  * @params netif the lwIP network interface on which to send the packet
412  * @params p the packet to send, p->payload pointing to the (uninitialized) ethernet header
413  * @params src the source MAC address to be copied into the ethernet header
414  * @params dst the destination MAC address to be copied into the ethernet header
415  * @return ERR_OK if the packet was sent, any other err_t on failure
416  */
417 static err_t
418 etharp_send_ip(struct netif *netif, struct pbuf *p, struct eth_addr *src, struct eth_addr *dst)
419 {
420   struct eth_hdr *ethhdr = (struct eth_hdr *)p->payload;
421
422   LWIP_ASSERT("netif->hwaddr_len must be the same as ETHARP_HWADDR_LEN for etharp!",
423               (netif->hwaddr_len == ETHARP_HWADDR_LEN));
424   ETHADDR32_COPY(&ethhdr->dest, dst);
425   ETHADDR16_COPY(&ethhdr->src, src);
426   ethhdr->type = PP_HTONS(ETHTYPE_IP);
427   LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_send_ip: sending packet %p\n", (void *)p));
428   /* send the packet */
429   return netif->linkoutput(netif, p);
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 definition of ETHARP_FLAG_*
442  *
443  * @return
444  * - ERR_OK Succesfully 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
451 etharp_update_arp_entry(struct netif *netif, ip_addr_t *ipaddr, struct eth_addr *ethaddr, u8_t flags)
452 {
453   s8_t i;
454   LWIP_ASSERT("netif->hwaddr_len == ETHARP_HWADDR_LEN", netif->hwaddr_len == ETHARP_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     ethaddr->addr[0], ethaddr->addr[1], ethaddr->addr[2],
458     ethaddr->addr[3], ethaddr->addr[4], ethaddr->addr[5]));
459   /* non-unicast address? */
460   if (ip_addr_isany(ipaddr) ||
461       ip_addr_isbroadcast(ipaddr, netif) ||
462       ip_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);
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
478 #endif /* ETHARP_SUPPORT_STATIC_ENTRIES */
479   {
480     /* mark it stable */
481     arp_table[i].state = ETHARP_STATE_STABLE;
482   }
483
484   /* record network interface */
485 #if LWIP_SNMP
486   arp_table[i].netif = netif;
487 #endif /* LWIP_SNMP */
488   /* insert in SNMP ARP index tree */
489   snmp_insert_arpidx_tree(netif, &arp_table[i].ipaddr);
490
491   LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_update_arp_entry: updating stable entry %"S16_F"\n", (s16_t)i));
492   /* update address */
493   ETHADDR32_COPY(&arp_table[i].ethaddr, ethaddr);
494   /* reset time stamp */
495   arp_table[i].ctime = 0;
496   /* this is where we will send out queued packets! */
497 #if ARP_QUEUEING
498   while (arp_table[i].q != NULL) {
499     struct pbuf *p;
500     /* remember remainder of queue */
501     struct etharp_q_entry *q = arp_table[i].q;
502     /* pop first item off the queue */
503     arp_table[i].q = q->next;
504     /* get the packet pointer */
505     p = q->p;
506     /* now queue entry can be freed */
507     memp_free(MEMP_ARP_QUEUE, q);
508 #else /* ARP_QUEUEING */
509   if (arp_table[i].q != NULL) {
510     struct pbuf *p = arp_table[i].q;
511     arp_table[i].q = NULL;
512 #endif /* ARP_QUEUEING */
513     /* send the queued IP packet */
514     etharp_send_ip(netif, p, (struct eth_addr*)(netif->hwaddr), ethaddr);
515     /* free the queued IP packet */
516     pbuf_free(p);
517   }
518   return ERR_OK;
519 }
520
521 #if ETHARP_SUPPORT_STATIC_ENTRIES
522 /** Add a new static entry to the ARP table. If an entry exists for the
523  * specified IP address, this entry is overwritten.
524  * If packets are queued for the specified IP address, they are sent out.
525  *
526  * @param ipaddr IP address for the new static entry
527  * @param ethaddr ethernet address for the new static entry
528  * @return @see return values of etharp_add_static_entry
529  */
530 err_t
531 etharp_add_static_entry(ip_addr_t *ipaddr, struct eth_addr *ethaddr)
532 {
533   struct netif *netif;
534   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",
535     ip4_addr1_16(ipaddr), ip4_addr2_16(ipaddr), ip4_addr3_16(ipaddr), ip4_addr4_16(ipaddr),
536     ethaddr->addr[0], ethaddr->addr[1], ethaddr->addr[2],
537     ethaddr->addr[3], ethaddr->addr[4], ethaddr->addr[5]));
538
539   netif = ip_route(ipaddr);
540   if (netif == NULL) {
541     return ERR_RTE;
542   }
543
544   return etharp_update_arp_entry(netif, ipaddr, ethaddr, ETHARP_FLAG_TRY_HARD | ETHARP_FLAG_STATIC_ENTRY);
545 }
546
547 /** Remove a static entry from the ARP table previously added with a call to
548  * etharp_add_static_entry.
549  *
550  * @param ipaddr IP address of the static entry to remove
551  * @return ERR_OK: entry removed
552  *         ERR_MEM: entry wasn't found
553  *         ERR_ARG: entry wasn't a static entry but a dynamic one
554  */
555 err_t
556 etharp_remove_static_entry(ip_addr_t *ipaddr)
557 {
558   s8_t i;
559   LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_remove_static_entry: %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n",
560     ip4_addr1_16(ipaddr), ip4_addr2_16(ipaddr), ip4_addr3_16(ipaddr), ip4_addr4_16(ipaddr)));
561
562   /* find or create ARP entry */
563   i = etharp_find_entry(ipaddr, ETHARP_FLAG_FIND_ONLY);
564   /* bail out if no entry could be found */
565   if (i < 0) {
566     return (err_t)i;
567   }
568
569   if (arp_table[i].state != ETHARP_STATE_STATIC) {
570     /* entry wasn't a static entry, cannot remove it */
571     return ERR_ARG;
572   }
573   /* entry found, free it */
574   etharp_free_entry(i);
575   return ERR_OK;
576 }
577 #endif /* ETHARP_SUPPORT_STATIC_ENTRIES */
578
579 /**
580  * Remove all ARP table entries of the specified netif.
581  *
582  * @param netif points to a network interface
583  */
584 void etharp_cleanup_netif(struct netif *netif)
585 {
586   u8_t i;
587
588   for (i = 0; i < ARP_TABLE_SIZE; ++i) {
589     u8_t state = arp_table[i].state;
590     if ((state != ETHARP_STATE_EMPTY) && (arp_table[i].netif == netif)) {
591       etharp_free_entry(i);
592     }
593   }
594 }
595
596 /**
597  * Finds (stable) ethernet/IP address pair from ARP table
598  * using interface and IP address index.
599  * @note the addresses in the ARP table are in network order!
600  *
601  * @param netif points to interface index
602  * @param ipaddr points to the (network order) IP address index
603  * @param eth_ret points to return pointer
604  * @param ip_ret points to return pointer
605  * @return table index if found, -1 otherwise
606  */
607 s8_t
608 etharp_find_addr(struct netif *netif, ip_addr_t *ipaddr,
609          struct eth_addr **eth_ret, ip_addr_t **ip_ret)
610 {
611   s8_t i;
612
613   LWIP_ASSERT("eth_ret != NULL && ip_ret != NULL",
614     eth_ret != NULL && ip_ret != NULL);
615
616   LWIP_UNUSED_ARG(netif);
617
618   i = etharp_find_entry(ipaddr, ETHARP_FLAG_FIND_ONLY);
619   if((i >= 0) && (arp_table[i].state >= ETHARP_STATE_STABLE)) {
620       *eth_ret = &arp_table[i].ethaddr;
621       *ip_ret = &arp_table[i].ipaddr;
622       return i;
623   }
624   return -1;
625 }
626
627 #if ETHARP_TRUST_IP_MAC
628 /**
629  * Updates the ARP table using the given IP packet.
630  *
631  * Uses the incoming IP packet's source address to update the
632  * ARP cache for the local network. The function does not alter
633  * or free the packet. This function must be called before the
634  * packet p is passed to the IP layer.
635  *
636  * @param netif The lwIP network interface on which the IP packet pbuf arrived.
637  * @param p The IP packet that arrived on netif.
638  *
639  * @return NULL
640  *
641  * @see pbuf_free()
642  */
643 static void
644 etharp_ip_input(struct netif *netif, struct pbuf *p)
645 {
646   struct eth_hdr *ethhdr;
647   struct ip_hdr *iphdr;
648   ip_addr_t iphdr_src;
649   LWIP_ERROR("netif != NULL", (netif != NULL), return;);
650
651   /* Only insert an entry if the source IP address of the
652      incoming IP packet comes from a host on the local network. */
653   ethhdr = (struct eth_hdr *)p->payload;
654   iphdr = (struct ip_hdr *)((u8_t*)ethhdr + SIZEOF_ETH_HDR);
655 #if ETHARP_SUPPORT_VLAN
656   if (ethhdr->type == PP_HTONS(ETHTYPE_VLAN)) {
657     iphdr = (struct ip_hdr *)((u8_t*)ethhdr + SIZEOF_ETH_HDR + SIZEOF_VLAN_HDR);
658   }
659 #endif /* ETHARP_SUPPORT_VLAN */
660
661   ip_addr_copy(iphdr_src, iphdr->src);
662
663   /* source is not on the local network? */
664   if (!ip_addr_netcmp(&iphdr_src, &(netif->ip_addr), &(netif->netmask))) {
665     /* do nothing */
666     return;
667   }
668
669   LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_ip_input: updating ETHARP table.\n"));
670   /* update the source IP address in the cache, if present */
671   /* @todo We could use ETHARP_FLAG_TRY_HARD if we think we are going to talk
672    * back soon (for example, if the destination IP address is ours. */
673   etharp_update_arp_entry(netif, &iphdr_src, &(ethhdr->src), ETHARP_FLAG_FIND_ONLY);
674 }
675 #endif /* ETHARP_TRUST_IP_MAC */
676
677 /**
678  * Responds to ARP requests to us. Upon ARP replies to us, add entry to cache  
679  * send out queued IP packets. Updates cache with snooped address pairs.
680  *
681  * Should be called for incoming ARP packets. The pbuf in the argument
682  * is freed by this function.
683  *
684  * @param netif The lwIP network interface on which the ARP packet pbuf arrived.
685  * @param ethaddr Ethernet address of netif.
686  * @param p The ARP packet that arrived on netif. Is freed by this function.
687  *
688  * @return NULL
689  *
690  * @see pbuf_free()
691  */
692 static void
693 etharp_arp_input(struct netif *netif, struct eth_addr *ethaddr, struct pbuf *p)
694 {
695   struct etharp_hdr *hdr;
696   struct eth_hdr *ethhdr;
697   /* these are aligned properly, whereas the ARP header fields might not be */
698   ip_addr_t sipaddr, dipaddr;
699   u8_t for_us;
700 #if LWIP_AUTOIP
701   const u8_t * ethdst_hwaddr;
702 #endif /* LWIP_AUTOIP */
703
704   LWIP_ERROR("netif != NULL", (netif != NULL), return;);
705
706   /* drop short ARP packets: we have to check for p->len instead of p->tot_len here
707      since a struct etharp_hdr is pointed to p->payload, so it musn't be chained! */
708   if (p->len < SIZEOF_ETHARP_PACKET) {
709     LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING,
710       ("etharp_arp_input: packet dropped, too short (%"S16_F"/%"S16_F")\n", p->tot_len,
711       (s16_t)SIZEOF_ETHARP_PACKET));
712     ETHARP_STATS_INC(etharp.lenerr);
713     ETHARP_STATS_INC(etharp.drop);
714     pbuf_free(p);
715     return;
716   }
717
718   ethhdr = (struct eth_hdr *)p->payload;
719   hdr = (struct etharp_hdr *)((u8_t*)ethhdr + SIZEOF_ETH_HDR);
720 #if ETHARP_SUPPORT_VLAN
721   if (ethhdr->type == PP_HTONS(ETHTYPE_VLAN)) {
722     hdr = (struct etharp_hdr *)(((u8_t*)ethhdr) + SIZEOF_ETH_HDR + SIZEOF_VLAN_HDR);
723   }
724 #endif /* ETHARP_SUPPORT_VLAN */
725
726   /* RFC 826 "Packet Reception": */
727   if ((hdr->hwtype != PP_HTONS(HWTYPE_ETHERNET)) ||
728       (hdr->hwlen != ETHARP_HWADDR_LEN) ||
729       (hdr->protolen != sizeof(ip_addr_t)) ||
730       (hdr->proto != PP_HTONS(ETHTYPE_IP)))  {
731     LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING,
732       ("etharp_arp_input: packet dropped, wrong hw type, hwlen, proto, protolen or ethernet type (%"U16_F"/%"U16_F"/%"U16_F"/%"U16_F")\n",
733       hdr->hwtype, hdr->hwlen, hdr->proto, hdr->protolen));
734     ETHARP_STATS_INC(etharp.proterr);
735     ETHARP_STATS_INC(etharp.drop);
736     pbuf_free(p);
737     return;
738   }
739   ETHARP_STATS_INC(etharp.recv);
740
741 #if LWIP_AUTOIP
742   /* We have to check if a host already has configured our random
743    * created link local address and continously check if there is
744    * a host with this IP-address so we can detect collisions */
745   autoip_arp_reply(netif, hdr);
746 #endif /* LWIP_AUTOIP */
747
748   /* Copy struct ip_addr2 to aligned ip_addr, to support compilers without
749    * structure packing (not using structure copy which breaks strict-aliasing rules). */
750   IPADDR2_COPY(&sipaddr, &hdr->sipaddr);
751   IPADDR2_COPY(&dipaddr, &hdr->dipaddr);
752
753   /* this interface is not configured? */
754   if (ip_addr_isany(&netif->ip_addr)) {
755     for_us = 0;
756   } else {
757     /* ARP packet directed to us? */
758     for_us = (u8_t)ip_addr_cmp(&dipaddr, &(netif->ip_addr));
759   }
760
761   /* ARP message directed to us?
762       -> add IP address in ARP cache; assume requester wants to talk to us,
763          can result in directly sending the queued packets for this host.
764      ARP message not directed to us?
765       ->  update the source IP address in the cache, if present */
766   etharp_update_arp_entry(netif, &sipaddr, &(hdr->shwaddr),
767                    for_us ? ETHARP_FLAG_TRY_HARD : ETHARP_FLAG_FIND_ONLY);
768
769   /* now act on the message itself */
770   switch (hdr->opcode) {
771   /* ARP request? */
772   case PP_HTONS(ARP_REQUEST):
773     /* ARP request. If it asked for our address, we send out a
774      * reply. In any case, we time-stamp any existing ARP entry,
775      * and possiby send out an IP packet that was queued on it. */
776
777     LWIP_DEBUGF (ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_arp_input: incoming ARP request\n"));
778     /* ARP request for our address? */
779     if (for_us) {
780
781       LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_arp_input: replying to ARP request for our IP address\n"));
782       /* Re-use pbuf to send ARP reply.
783          Since we are re-using an existing pbuf, we can't call etharp_raw since
784          that would allocate a new pbuf. */
785       hdr->opcode = htons(ARP_REPLY);
786
787       IPADDR2_COPY(&hdr->dipaddr, &hdr->sipaddr);
788       IPADDR2_COPY(&hdr->sipaddr, &netif->ip_addr);
789
790       LWIP_ASSERT("netif->hwaddr_len must be the same as ETHARP_HWADDR_LEN for etharp!",
791                   (netif->hwaddr_len == ETHARP_HWADDR_LEN));
792 #if LWIP_AUTOIP
793       /* If we are using Link-Local, all ARP packets that contain a Link-Local
794        * 'sender IP address' MUST be sent using link-layer broadcast instead of
795        * link-layer unicast. (See RFC3927 Section 2.5, last paragraph) */
796       ethdst_hwaddr = ip_addr_islinklocal(&netif->ip_addr) ? (u8_t*)(ethbroadcast.addr) : hdr->shwaddr.addr;
797 #endif /* LWIP_AUTOIP */
798
799       ETHADDR16_COPY(&hdr->dhwaddr, &hdr->shwaddr);
800 #if LWIP_AUTOIP
801       ETHADDR16_COPY(&ethhdr->dest, ethdst_hwaddr);
802 #else  /* LWIP_AUTOIP */
803       ETHADDR16_COPY(&ethhdr->dest, &hdr->shwaddr);
804 #endif /* LWIP_AUTOIP */
805       ETHADDR16_COPY(&hdr->shwaddr, ethaddr);
806       ETHADDR16_COPY(&ethhdr->src, ethaddr);
807
808       /* hwtype, hwaddr_len, proto, protolen and the type in the ethernet header
809          are already correct, we tested that before */
810
811       /* return ARP reply */
812       netif->linkoutput(netif, p);
813     /* we are not configured? */
814     } else if (ip_addr_isany(&netif->ip_addr)) {
815       /* { for_us == 0 and netif->ip_addr.addr == 0 } */
816       LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_arp_input: we are unconfigured, ARP request ignored.\n"));
817     /* request was not directed to us */
818     } else {
819       /* { for_us == 0 and netif->ip_addr.addr != 0 } */
820       LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_arp_input: ARP request was not for us.\n"));
821     }
822     break;
823   case PP_HTONS(ARP_REPLY):
824     /* ARP reply. We already updated the ARP cache earlier. */
825     LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_arp_input: incoming ARP reply\n"));
826 #if (LWIP_DHCP && DHCP_DOES_ARP_CHECK)
827     /* DHCP wants to know about ARP replies from any host with an
828      * IP address also offered to us by the DHCP server. We do not
829      * want to take a duplicate IP address on a single network.
830      * @todo How should we handle redundant (fail-over) interfaces? */
831     dhcp_arp_reply(netif, &sipaddr);
832 #endif /* (LWIP_DHCP && DHCP_DOES_ARP_CHECK) */
833     break;
834   default:
835     LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_arp_input: ARP unknown opcode type %"S16_F"\n", htons(hdr->opcode)));
836     ETHARP_STATS_INC(etharp.err);
837     break;
838   }
839   /* free ARP packet */
840   pbuf_free(p);
841 }
842
843 /** Just a small helper function that sends a pbuf to an ethernet address
844  * in the arp_table specified by the index 'arp_idx'.
845  */
846 static err_t
847 etharp_output_to_arp_index(struct netif *netif, struct pbuf *q, u8_t arp_idx)
848 {
849   LWIP_ASSERT("arp_table[arp_idx].state >= ETHARP_STATE_STABLE",
850               arp_table[arp_idx].state >= ETHARP_STATE_STABLE);
851   /* if arp table entry is about to expire: re-request it,
852      but only if its state is ETHARP_STATE_STABLE to prevent flooding the
853      network with ARP requests if this address is used frequently. */
854   if ((arp_table[arp_idx].state == ETHARP_STATE_STABLE) && 
855       (arp_table[arp_idx].ctime >= ARP_AGE_REREQUEST_USED)) {
856     if (etharp_request(netif, &arp_table[arp_idx].ipaddr) == ERR_OK) {
857       arp_table[arp_idx].state = ETHARP_STATE_STABLE_REREQUESTING;
858     }
859   }
860   
861   return etharp_send_ip(netif, q, (struct eth_addr*)(netif->hwaddr),
862     &arp_table[arp_idx].ethaddr);
863 }
864
865 /**
866  * Resolve and fill-in Ethernet address header for outgoing IP packet.
867  *
868  * For IP multicast and broadcast, corresponding Ethernet addresses
869  * are selected and the packet is transmitted on the link.
870  *
871  * For unicast addresses, the packet is submitted to etharp_query(). In
872  * case the IP address is outside the local network, the IP address of
873  * the gateway is used.
874  *
875  * @param netif The lwIP network interface which the IP packet will be sent on.
876  * @param q The pbuf(s) containing the IP packet to be sent.
877  * @param ipaddr The IP address of the packet destination.
878  *
879  * @return
880  * - ERR_RTE No route to destination (no gateway to external networks),
881  * or the return type of either etharp_query() or etharp_send_ip().
882  */
883 err_t
884 etharp_output(struct netif *netif, struct pbuf *q, ip_addr_t *ipaddr)
885 {
886   struct eth_addr *dest;
887   struct eth_addr mcastaddr;
888   ip_addr_t *dst_addr = ipaddr;
889
890   LWIP_ASSERT("netif != NULL", netif != NULL);
891   LWIP_ASSERT("q != NULL", q != NULL);
892   LWIP_ASSERT("ipaddr != NULL", ipaddr != NULL);
893
894   /* make room for Ethernet header - should not fail */
895   if (pbuf_header(q, sizeof(struct eth_hdr)) != 0) {
896     /* bail out */
897     LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS,
898       ("etharp_output: could not allocate room for header.\n"));
899     LINK_STATS_INC(link.lenerr);
900     return ERR_BUF;
901   }
902
903   /* outside local network? if so, this can neither be a global broadcast nor
904      a subnet broadcast. */
905   if (!ip_addr_netcmp(ipaddr, &(netif->ip_addr), &(netif->netmask)) &&
906       !ip_addr_islinklocal(ipaddr)) {
907 #if LWIP_AUTOIP
908     struct ip_hdr *iphdr = (struct ip_hdr*)((u8_t*)q->payload +
909       sizeof(struct eth_hdr));
910     /* According to RFC 3297, chapter 2.6.2 (Forwarding Rules), a packet with
911        a link-local source address must always be "directly to its destination
912        on the same physical link. The host MUST NOT send the packet to any
913        router for forwarding". */
914     if (!ip_addr_islinklocal(&iphdr->src))
915 #endif /* LWIP_AUTOIP */
916     {
917       /* interface has default gateway? */
918       if (!ip_addr_isany(&netif->gw)) {
919         /* send to hardware address of default gateway IP address */
920         dst_addr = &(netif->gw);
921       /* no default gateway available */
922       } else {
923         /* no route to destination error (default gateway missing) */
924         return ERR_RTE;
925       }
926     }
927   }
928 #if LWIP_NETIF_HWADDRHINT
929   if (netif->addr_hint != NULL) {
930     /* per-pcb cached entry was given */
931     u8_t etharp_cached_entry = *(netif->addr_hint);
932     if (etharp_cached_entry < ARP_TABLE_SIZE) {
933 #endif /* LWIP_NETIF_HWADDRHINT */
934       if ((arp_table[etharp_cached_entry].state >= ETHARP_STATE_STABLE) &&
935           (ip_addr_cmp(dst_addr, &arp_table[etharp_cached_entry].ipaddr))) {
936         /* the per-pcb-cached entry is stable and the right one! */
937         ETHARP_STATS_INC(etharp.cachehit);
938         return etharp_output_to_arp_index(netif, q, etharp_cached_entry);
939       }
940 #if LWIP_NETIF_HWADDRHINT
941     }
942   }
943 #endif /* LWIP_NETIF_HWADDRHINT */
944
945   /* Determine on destination hardware address. Broadcasts and multicasts
946    * are special, other IP addresses are looked up in the ARP table. */
947
948   /* broadcast destination IP address? */
949   if (ip_addr_isbroadcast(ipaddr, netif)) {
950     /* broadcast on Ethernet also */
951     dest = (struct eth_addr *)&ethbroadcast;
952   /* multicast destination IP address? */
953   } else if (ip_addr_ismulticast(ipaddr)) {
954     /* Hash IP multicast address to MAC address.*/
955     mcastaddr.addr[0] = LL_MULTICAST_ADDR_0;
956     mcastaddr.addr[1] = LL_MULTICAST_ADDR_1;
957     mcastaddr.addr[2] = LL_MULTICAST_ADDR_2;
958     mcastaddr.addr[3] = ip4_addr2(ipaddr) & 0x7f;
959     mcastaddr.addr[4] = ip4_addr3(ipaddr);
960     mcastaddr.addr[5] = ip4_addr4(ipaddr);
961     /* destination Ethernet address is multicast */
962     dest = &mcastaddr;
963   /* unicast destination IP address? */
964   } else {
965     s8_t i;
966     /* find stable entry: do this here since this is a critical path for
967        throughput and etharp_find_entry() is kind of slow */
968     for (i = 0; i < ARP_TABLE_SIZE; i++) {
969       if ((arp_table[i].state >= ETHARP_STATE_STABLE) &&
970           (ip_addr_cmp(dst_addr, &arp_table[i].ipaddr))) {
971         /* found an existing, stable entry */
972         ETHARP_SET_HINT(netif, i);
973         return etharp_output_to_arp_index(netif, q, i);
974       }
975     }
976     /* no stable entry found, use the (slower) query function:
977        queue on destination Ethernet address belonging to ipaddr */
978     return etharp_query(netif, dst_addr, q);
979   }
980
981   /* continuation for multicast/broadcast destinations */
982   /* obtain source Ethernet address of the given interface */
983   /* send packet directly on the link */
984   return etharp_send_ip(netif, q, (struct eth_addr*)(netif->hwaddr), dest);
985 }
986
987 /**
988  * Send an ARP request for the given IP address and/or queue a packet.
989  *
990  * If the IP address was not yet in the cache, a pending ARP cache entry
991  * is added and an ARP request is sent for the given address. The packet
992  * is queued on this entry.
993  *
994  * If the IP address was already pending in the cache, a new ARP request
995  * is sent for the given address. The packet is queued on this entry.
996  *
997  * If the IP address was already stable in the cache, and a packet is
998  * given, it is directly sent and no ARP request is sent out. 
999  * 
1000  * If the IP address was already stable in the cache, and no packet is
1001  * given, an ARP request is sent out.
1002  * 
1003  * @param netif The lwIP network interface on which ipaddr
1004  * must be queried for.
1005  * @param ipaddr The IP address to be resolved.
1006  * @param q If non-NULL, a pbuf that must be delivered to the IP address.
1007  * q is not freed by this function.
1008  *
1009  * @note q must only be ONE packet, not a packet queue!
1010  *
1011  * @return
1012  * - ERR_BUF Could not make room for Ethernet header.
1013  * - ERR_MEM Hardware address unknown, and no more ARP entries available
1014  *   to query for address or queue the packet.
1015  * - ERR_MEM Could not queue packet due to memory shortage.
1016  * - ERR_RTE No route to destination (no gateway to external networks).
1017  * - ERR_ARG Non-unicast address given, those will not appear in ARP cache.
1018  *
1019  */
1020 err_t
1021 etharp_query(struct netif *netif, ip_addr_t *ipaddr, struct pbuf *q)
1022 {
1023   struct eth_addr * srcaddr = (struct eth_addr *)netif->hwaddr;
1024   err_t result = ERR_MEM;
1025   s8_t i; /* ARP entry index */
1026
1027   /* non-unicast address? */
1028   if (ip_addr_isbroadcast(ipaddr, netif) ||
1029       ip_addr_ismulticast(ipaddr) ||
1030       ip_addr_isany(ipaddr)) {
1031     LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: will not add non-unicast IP address to ARP cache\n"));
1032     return ERR_ARG;
1033   }
1034
1035   /* find entry in ARP cache, ask to create entry if queueing packet */
1036   i = etharp_find_entry(ipaddr, ETHARP_FLAG_TRY_HARD);
1037
1038   /* could not find or create entry? */
1039   if (i < 0) {
1040     LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: could not create ARP entry\n"));
1041     if (q) {
1042       LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: packet dropped\n"));
1043       ETHARP_STATS_INC(etharp.memerr);
1044     }
1045     return (err_t)i;
1046   }
1047
1048   /* mark a fresh entry as pending (we just sent a request) */
1049   if (arp_table[i].state == ETHARP_STATE_EMPTY) {
1050     arp_table[i].state = ETHARP_STATE_PENDING;
1051   }
1052
1053   /* { i is either a STABLE or (new or existing) PENDING entry } */
1054   LWIP_ASSERT("arp_table[i].state == PENDING or STABLE",
1055   ((arp_table[i].state == ETHARP_STATE_PENDING) ||
1056    (arp_table[i].state >= ETHARP_STATE_STABLE)));
1057
1058   /* do we have a pending entry? or an implicit query request? */
1059   if ((arp_table[i].state == ETHARP_STATE_PENDING) || (q == NULL)) {
1060     /* try to resolve it; send out ARP request */
1061     result = etharp_request(netif, ipaddr);
1062     if (result != ERR_OK) {
1063       /* ARP request couldn't be sent */
1064       /* We don't re-send arp request in etharp_tmr, but we still queue packets,
1065          since this failure could be temporary, and the next packet calling
1066          etharp_query again could lead to sending the queued packets. */
1067     }
1068     if (q == NULL) {
1069       return result;
1070     }
1071   }
1072
1073   /* packet given? */
1074   LWIP_ASSERT("q != NULL", q != NULL);
1075   /* stable entry? */
1076   if (arp_table[i].state >= ETHARP_STATE_STABLE) {
1077     /* we have a valid IP->Ethernet address mapping */
1078     ETHARP_SET_HINT(netif, i);
1079     /* send the packet */
1080     result = etharp_send_ip(netif, q, srcaddr, &(arp_table[i].ethaddr));
1081   /* pending entry? (either just created or already pending */
1082   } else if (arp_table[i].state == ETHARP_STATE_PENDING) {
1083     /* entry is still pending, queue the given packet 'q' */
1084     struct pbuf *p;
1085     int copy_needed = 0;
1086     /* IF q includes a PBUF_REF, PBUF_POOL or PBUF_RAM, we have no choice but
1087      * to copy the whole queue into a new PBUF_RAM (see bug #11400) 
1088      * PBUF_ROMs can be left as they are, since ROM must not get changed. */
1089     p = q;
1090     while (p) {
1091       LWIP_ASSERT("no packet queues allowed!", (p->len != p->tot_len) || (p->next == 0));
1092       if(p->type != PBUF_ROM) {
1093         copy_needed = 1;
1094         break;
1095       }
1096       p = p->next;
1097     }
1098     if(copy_needed) {
1099       /* copy the whole packet into new pbufs */
1100       p = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM);
1101       if(p != NULL) {
1102         if (pbuf_copy(p, q) != ERR_OK) {
1103           pbuf_free(p);
1104           p = NULL;
1105         }
1106       }
1107     } else {
1108       /* referencing the old pbuf is enough */
1109       p = q;
1110       pbuf_ref(p);
1111     }
1112     /* packet could be taken over? */
1113     if (p != NULL) {
1114       /* queue packet ... */
1115 #if ARP_QUEUEING
1116       struct etharp_q_entry *new_entry;
1117       /* allocate a new arp queue entry */
1118       new_entry = (struct etharp_q_entry *)memp_malloc(MEMP_ARP_QUEUE);
1119       if (new_entry != NULL) {
1120         new_entry->next = 0;
1121         new_entry->p = p;
1122         if(arp_table[i].q != NULL) {
1123           /* queue was already existent, append the new entry to the end */
1124           struct etharp_q_entry *r;
1125           r = arp_table[i].q;
1126           while (r->next != NULL) {
1127             r = r->next;
1128           }
1129           r->next = new_entry;
1130         } else {
1131           /* queue did not exist, first item in queue */
1132           arp_table[i].q = new_entry;
1133         }
1134         LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: queued packet %p on ARP entry %"S16_F"\n", (void *)q, (s16_t)i));
1135         result = ERR_OK;
1136       } else {
1137         /* the pool MEMP_ARP_QUEUE is empty */
1138         pbuf_free(p);
1139         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));
1140         result = ERR_MEM;
1141       }
1142 #else /* ARP_QUEUEING */
1143       /* always queue one packet per ARP request only, freeing a previously queued packet */
1144       if (arp_table[i].q != NULL) {
1145         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));
1146         pbuf_free(arp_table[i].q);
1147       }
1148       arp_table[i].q = p;
1149       result = ERR_OK;
1150       LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: queued packet %p on ARP entry %"S16_F"\n", (void *)q, (s16_t)i));
1151 #endif /* ARP_QUEUEING */
1152     } else {
1153       ETHARP_STATS_INC(etharp.memerr);
1154       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));
1155       result = ERR_MEM;
1156     }
1157   }
1158   return result;
1159 }
1160
1161 /**
1162  * Send a raw ARP packet (opcode and all addresses can be modified)
1163  *
1164  * @param netif the lwip network interface on which to send the ARP packet
1165  * @param ethsrc_addr the source MAC address for the ethernet header
1166  * @param ethdst_addr the destination MAC address for the ethernet header
1167  * @param hwsrc_addr the source MAC address for the ARP protocol header
1168  * @param ipsrc_addr the source IP address for the ARP protocol header
1169  * @param hwdst_addr the destination MAC address for the ARP protocol header
1170  * @param ipdst_addr the destination IP address for the ARP protocol header
1171  * @param opcode the type of the ARP packet
1172  * @return ERR_OK if the ARP packet has been sent
1173  *         ERR_MEM if the ARP packet couldn't be allocated
1174  *         any other err_t on failure
1175  */
1176 #if !LWIP_AUTOIP
1177 static
1178 #endif /* LWIP_AUTOIP */
1179 err_t
1180 etharp_raw(struct netif *netif, const struct eth_addr *ethsrc_addr,
1181            const struct eth_addr *ethdst_addr,
1182            const struct eth_addr *hwsrc_addr, const ip_addr_t *ipsrc_addr,
1183            const struct eth_addr *hwdst_addr, const ip_addr_t *ipdst_addr,
1184            const u16_t opcode)
1185 {
1186   struct pbuf *p;
1187   err_t result = ERR_OK;
1188   struct eth_hdr *ethhdr;
1189   struct etharp_hdr *hdr;
1190 #if LWIP_AUTOIP
1191   const u8_t * ethdst_hwaddr;
1192 #endif /* LWIP_AUTOIP */
1193
1194   LWIP_ASSERT("netif != NULL", netif != NULL);
1195
1196   /* allocate a pbuf for the outgoing ARP request packet */
1197   p = pbuf_alloc(PBUF_RAW, SIZEOF_ETHARP_PACKET, PBUF_RAM);
1198   /* could allocate a pbuf for an ARP request? */
1199   if (p == NULL) {
1200     LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS,
1201       ("etharp_raw: could not allocate pbuf for ARP request.\n"));
1202     ETHARP_STATS_INC(etharp.memerr);
1203     return ERR_MEM;
1204   }
1205   LWIP_ASSERT("check that first pbuf can hold struct etharp_hdr",
1206               (p->len >= SIZEOF_ETHARP_PACKET));
1207
1208   ethhdr = (struct eth_hdr *)p->payload;
1209   hdr = (struct etharp_hdr *)((u8_t*)ethhdr + SIZEOF_ETH_HDR);
1210   LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_raw: sending raw ARP packet.\n"));
1211   hdr->opcode = htons(opcode);
1212
1213   LWIP_ASSERT("netif->hwaddr_len must be the same as ETHARP_HWADDR_LEN for etharp!",
1214               (netif->hwaddr_len == ETHARP_HWADDR_LEN));
1215 #if LWIP_AUTOIP
1216   /* If we are using Link-Local, all ARP packets that contain a Link-Local
1217    * 'sender IP address' MUST be sent using link-layer broadcast instead of
1218    * link-layer unicast. (See RFC3927 Section 2.5, last paragraph) */
1219   ethdst_hwaddr = ip_addr_islinklocal(ipsrc_addr) ? (u8_t*)(ethbroadcast.addr) : ethdst_addr->addr;
1220 #endif /* LWIP_AUTOIP */
1221   /* Write the ARP MAC-Addresses */
1222   ETHADDR16_COPY(&hdr->shwaddr, hwsrc_addr);
1223   ETHADDR16_COPY(&hdr->dhwaddr, hwdst_addr);
1224   /* Write the Ethernet MAC-Addresses */
1225 #if LWIP_AUTOIP
1226   ETHADDR16_COPY(&ethhdr->dest, ethdst_hwaddr);
1227 #else  /* LWIP_AUTOIP */
1228   ETHADDR16_COPY(&ethhdr->dest, ethdst_addr);
1229 #endif /* LWIP_AUTOIP */
1230   ETHADDR16_COPY(&ethhdr->src, ethsrc_addr);
1231   /* Copy struct ip_addr2 to aligned ip_addr, to support compilers without
1232    * structure packing. */ 
1233   IPADDR2_COPY(&hdr->sipaddr, ipsrc_addr);
1234   IPADDR2_COPY(&hdr->dipaddr, ipdst_addr);
1235
1236   hdr->hwtype = PP_HTONS(HWTYPE_ETHERNET);
1237   hdr->proto = PP_HTONS(ETHTYPE_IP);
1238   /* set hwlen and protolen */
1239   hdr->hwlen = ETHARP_HWADDR_LEN;
1240   hdr->protolen = sizeof(ip_addr_t);
1241
1242   ethhdr->type = PP_HTONS(ETHTYPE_ARP);
1243   /* send ARP query */
1244   result = netif->linkoutput(netif, p);
1245   ETHARP_STATS_INC(etharp.xmit);
1246   /* free ARP query packet */
1247   pbuf_free(p);
1248   p = NULL;
1249   /* could not allocate pbuf for ARP request */
1250
1251   return result;
1252 }
1253
1254 /**
1255  * Send an ARP request packet asking for ipaddr.
1256  *
1257  * @param netif the lwip network interface on which to send the request
1258  * @param ipaddr the IP address for which to ask
1259  * @return ERR_OK if the request has been sent
1260  *         ERR_MEM if the ARP packet couldn't be allocated
1261  *         any other err_t on failure
1262  */
1263 err_t
1264 etharp_request(struct netif *netif, ip_addr_t *ipaddr)
1265 {
1266   LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_request: sending ARP request.\n"));
1267   return etharp_raw(netif, (struct eth_addr *)netif->hwaddr, &ethbroadcast,
1268                     (struct eth_addr *)netif->hwaddr, &netif->ip_addr, &ethzero,
1269                     ipaddr, ARP_REQUEST);
1270 }
1271 #endif /* LWIP_ARP */
1272
1273 /**
1274  * Process received ethernet frames. Using this function instead of directly
1275  * calling ip_input and passing ARP frames through etharp in ethernetif_input,
1276  * the ARP cache is protected from concurrent access.
1277  *
1278  * @param p the recevied packet, p->payload pointing to the ethernet header
1279  * @param netif the network interface on which the packet was received
1280  */
1281 err_t
1282 ethernet_input(struct pbuf *p, struct netif *netif)
1283 {
1284   struct eth_hdr* ethhdr;
1285   u16_t type;
1286   s16_t ip_hdr_offset = SIZEOF_ETH_HDR;
1287
1288   if (p->len <= SIZEOF_ETH_HDR) {
1289     /* a packet with only an ethernet header (or less) is not valid for us */
1290     ETHARP_STATS_INC(etharp.proterr);
1291     ETHARP_STATS_INC(etharp.drop);
1292     goto free_and_return;
1293   }
1294
1295   /* points to packet payload, which starts with an Ethernet header */
1296   ethhdr = (struct eth_hdr *)p->payload;
1297   LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE,
1298     ("ethernet_input: dest:%"X8_F":%"X8_F":%"X8_F":%"X8_F":%"X8_F":%"X8_F", src:%"X8_F":%"X8_F":%"X8_F":%"X8_F":%"X8_F":%"X8_F", type:%"X16_F"\n",
1299      (unsigned)ethhdr->dest.addr[0], (unsigned)ethhdr->dest.addr[1], (unsigned)ethhdr->dest.addr[2],
1300      (unsigned)ethhdr->dest.addr[3], (unsigned)ethhdr->dest.addr[4], (unsigned)ethhdr->dest.addr[5],
1301      (unsigned)ethhdr->src.addr[0], (unsigned)ethhdr->src.addr[1], (unsigned)ethhdr->src.addr[2],
1302      (unsigned)ethhdr->src.addr[3], (unsigned)ethhdr->src.addr[4], (unsigned)ethhdr->src.addr[5],
1303      (unsigned)htons(ethhdr->type)));
1304
1305   type = ethhdr->type;
1306 #if ETHARP_SUPPORT_VLAN
1307   if (type == PP_HTONS(ETHTYPE_VLAN)) {
1308     struct eth_vlan_hdr *vlan = (struct eth_vlan_hdr*)(((char*)ethhdr) + SIZEOF_ETH_HDR);
1309     if (p->len <= SIZEOF_ETH_HDR + SIZEOF_VLAN_HDR) {
1310       /* a packet with only an ethernet/vlan header (or less) is not valid for us */
1311       ETHARP_STATS_INC(etharp.proterr);
1312       ETHARP_STATS_INC(etharp.drop);
1313       goto free_and_return;
1314     }
1315 #if defined(ETHARP_VLAN_CHECK) || defined(ETHARP_VLAN_CHECK_FN) /* if not, allow all VLANs */
1316 #ifdef ETHARP_VLAN_CHECK_FN
1317     if (!ETHARP_VLAN_CHECK_FN(ethhdr, vlan)) {
1318 #elif defined(ETHARP_VLAN_CHECK)
1319     if (VLAN_ID(vlan) != ETHARP_VLAN_CHECK) {
1320 #endif
1321       /* silently ignore this packet: not for our VLAN */
1322       pbuf_free(p);
1323       return ERR_OK;
1324     }
1325 #endif /* defined(ETHARP_VLAN_CHECK) || defined(ETHARP_VLAN_CHECK_FN) */
1326     type = vlan->tpid;
1327     ip_hdr_offset = SIZEOF_ETH_HDR + SIZEOF_VLAN_HDR;
1328   }
1329 #endif /* ETHARP_SUPPORT_VLAN */
1330
1331 #if LWIP_ARP_FILTER_NETIF
1332   netif = LWIP_ARP_FILTER_NETIF_FN(p, netif, htons(type));
1333 #endif /* LWIP_ARP_FILTER_NETIF*/
1334
1335   if (ethhdr->dest.addr[0] & 1) {
1336     /* this might be a multicast or broadcast packet */
1337     if (ethhdr->dest.addr[0] == LL_MULTICAST_ADDR_0) {
1338       if ((ethhdr->dest.addr[1] == LL_MULTICAST_ADDR_1) &&
1339           (ethhdr->dest.addr[2] == LL_MULTICAST_ADDR_2)) {
1340         /* mark the pbuf as link-layer multicast */
1341         p->flags |= PBUF_FLAG_LLMCAST;
1342       }
1343     } else if (eth_addr_cmp(&ethhdr->dest, &ethbroadcast)) {
1344       /* mark the pbuf as link-layer broadcast */
1345       p->flags |= PBUF_FLAG_LLBCAST;
1346     }
1347   }
1348
1349   switch (type) {
1350 #if LWIP_ARP
1351     /* IP packet? */
1352     case PP_HTONS(ETHTYPE_IP):
1353       if (!(netif->flags & NETIF_FLAG_ETHARP)) {
1354         goto free_and_return;
1355       }
1356 #if ETHARP_TRUST_IP_MAC
1357       /* update ARP table */
1358       etharp_ip_input(netif, p);
1359 #endif /* ETHARP_TRUST_IP_MAC */
1360       /* skip Ethernet header */
1361       if(pbuf_header(p, -ip_hdr_offset)) {
1362         LWIP_ASSERT("Can't move over header in packet", 0);
1363         goto free_and_return;
1364       } else {
1365         /* pass to IP layer */
1366         ip_input(p, netif);
1367       }
1368       break;
1369       
1370     case PP_HTONS(ETHTYPE_ARP):
1371       if (!(netif->flags & NETIF_FLAG_ETHARP)) {
1372         goto free_and_return;
1373       }
1374       /* pass p to ARP module */
1375       etharp_arp_input(netif, (struct eth_addr*)(netif->hwaddr), p);
1376       break;
1377 #endif /* LWIP_ARP */
1378 #if PPPOE_SUPPORT
1379     case PP_HTONS(ETHTYPE_PPPOEDISC): /* PPP Over Ethernet Discovery Stage */
1380       pppoe_disc_input(netif, p);
1381       break;
1382
1383     case PP_HTONS(ETHTYPE_PPPOE): /* PPP Over Ethernet Session Stage */
1384       pppoe_data_input(netif, p);
1385       break;
1386 #endif /* PPPOE_SUPPORT */
1387
1388 #if LWIP_IPV6
1389     case PP_HTONS(ETHTYPE_IPV6): /* IPv6 */
1390       /* skip Ethernet header */
1391       if(pbuf_header(p, -(s16_t)SIZEOF_ETH_HDR)) {
1392         LWIP_ASSERT("Can't move over header in packet", 0);
1393         goto free_and_return;
1394       } else {
1395         /* pass to IPv6 layer */
1396         ip6_input(p, netif);
1397       }
1398       break;
1399 #endif /* LWIP_IPV6 */
1400
1401     default:
1402       ETHARP_STATS_INC(etharp.proterr);
1403       ETHARP_STATS_INC(etharp.drop);
1404       goto free_and_return;
1405   }
1406
1407   /* This means the pbuf is freed or consumed,
1408      so the caller doesn't have to free it again */
1409   return ERR_OK;
1410
1411 free_and_return:
1412   pbuf_free(p);
1413   return ERR_OK;
1414 }
1415 #endif /* LWIP_ARP || LWIP_ETHERNET */