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