]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/in.c
Import atf 0.22 snapshot 55c21b2c5fb189bbdfccb2b297bfa89236502542
[FreeBSD/FreeBSD.git] / sys / netinet / in.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1991, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  * Copyright (C) 2001 WIDE Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *      @(#)in.c        8.4 (Berkeley) 1/9/95
33  */
34
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
38 #include <sys/param.h>
39 #include <sys/eventhandler.h>
40 #include <sys/systm.h>
41 #include <sys/sockio.h>
42 #include <sys/malloc.h>
43 #include <sys/priv.h>
44 #include <sys/socket.h>
45 #include <sys/jail.h>
46 #include <sys/kernel.h>
47 #include <sys/lock.h>
48 #include <sys/proc.h>
49 #include <sys/rmlock.h>
50 #include <sys/sysctl.h>
51 #include <sys/syslog.h>
52 #include <sys/sx.h>
53
54 #include <net/if.h>
55 #include <net/if_var.h>
56 #include <net/if_arp.h>
57 #include <net/if_dl.h>
58 #include <net/if_llatbl.h>
59 #include <net/if_types.h>
60 #include <net/route.h>
61 #include <net/route/nhop.h>
62 #include <net/route/route_ctl.h>
63 #include <net/vnet.h>
64
65 #include <netinet/if_ether.h>
66 #include <netinet/in.h>
67 #include <netinet/in_fib.h>
68 #include <netinet/in_var.h>
69 #include <netinet/in_pcb.h>
70 #include <netinet/ip_var.h>
71 #include <netinet/ip_carp.h>
72 #include <netinet/igmp_var.h>
73 #include <netinet/udp.h>
74 #include <netinet/udp_var.h>
75
76 static int in_aifaddr_ioctl(u_long, caddr_t, struct ifnet *, struct thread *);
77 static int in_difaddr_ioctl(u_long, caddr_t, struct ifnet *, struct thread *);
78 static int in_gifaddr_ioctl(u_long, caddr_t, struct ifnet *, struct thread *);
79
80 static void     in_socktrim(struct sockaddr_in *);
81 static void     in_purgemaddrs(struct ifnet *);
82
83 static bool     ia_need_loopback_route(const struct in_ifaddr *);
84
85 VNET_DEFINE_STATIC(int, nosameprefix);
86 #define V_nosameprefix                  VNET(nosameprefix)
87 SYSCTL_INT(_net_inet_ip, OID_AUTO, no_same_prefix, CTLFLAG_VNET | CTLFLAG_RW,
88         &VNET_NAME(nosameprefix), 0,
89         "Refuse to create same prefixes on different interfaces");
90
91 VNET_DECLARE(struct inpcbinfo, ripcbinfo);
92 #define V_ripcbinfo                     VNET(ripcbinfo)
93
94 static struct sx in_control_sx;
95 SX_SYSINIT(in_control_sx, &in_control_sx, "in_control");
96
97 /*
98  * Return 1 if an internet address is for a ``local'' host
99  * (one to which we have a connection).
100  */
101 int
102 in_localaddr(struct in_addr in)
103 {
104         struct rm_priotracker in_ifa_tracker;
105         u_long i = ntohl(in.s_addr);
106         struct in_ifaddr *ia;
107
108         IN_IFADDR_RLOCK(&in_ifa_tracker);
109         CK_STAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
110                 if ((i & ia->ia_subnetmask) == ia->ia_subnet) {
111                         IN_IFADDR_RUNLOCK(&in_ifa_tracker);
112                         return (1);
113                 }
114         }
115         IN_IFADDR_RUNLOCK(&in_ifa_tracker);
116         return (0);
117 }
118
119 /*
120  * Return 1 if an internet address is for the local host and configured
121  * on one of its interfaces.
122  */
123 int
124 in_localip(struct in_addr in)
125 {
126         struct rm_priotracker in_ifa_tracker;
127         struct in_ifaddr *ia;
128
129         IN_IFADDR_RLOCK(&in_ifa_tracker);
130         LIST_FOREACH(ia, INADDR_HASH(in.s_addr), ia_hash) {
131                 if (IA_SIN(ia)->sin_addr.s_addr == in.s_addr) {
132                         IN_IFADDR_RUNLOCK(&in_ifa_tracker);
133                         return (1);
134                 }
135         }
136         IN_IFADDR_RUNLOCK(&in_ifa_tracker);
137         return (0);
138 }
139
140 /*
141  * Return 1 if an internet address is configured on an interface.
142  */
143 int
144 in_ifhasaddr(struct ifnet *ifp, struct in_addr in)
145 {
146         struct ifaddr *ifa;
147         struct in_ifaddr *ia;
148
149         NET_EPOCH_ASSERT();
150
151         CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
152                 if (ifa->ifa_addr->sa_family != AF_INET)
153                         continue;
154                 ia = (struct in_ifaddr *)ifa;
155                 if (ia->ia_addr.sin_addr.s_addr == in.s_addr)
156                         return (1);
157         }
158
159         return (0);
160 }
161
162 /*
163  * Return a reference to the interface address which is different to
164  * the supplied one but with same IP address value.
165  */
166 static struct in_ifaddr *
167 in_localip_more(struct in_ifaddr *original_ia)
168 {
169         struct rm_priotracker in_ifa_tracker;
170         in_addr_t original_addr = IA_SIN(original_ia)->sin_addr.s_addr;
171         uint32_t original_fib = original_ia->ia_ifa.ifa_ifp->if_fib;
172         struct in_ifaddr *ia;
173
174         IN_IFADDR_RLOCK(&in_ifa_tracker);
175         LIST_FOREACH(ia, INADDR_HASH(original_addr), ia_hash) {
176                 in_addr_t addr = IA_SIN(ia)->sin_addr.s_addr;
177                 uint32_t fib = ia->ia_ifa.ifa_ifp->if_fib;
178                 if (!V_rt_add_addr_allfibs && (original_fib != fib))
179                         continue;
180                 if ((original_ia != ia) && (original_addr == addr)) {
181                         ifa_ref(&ia->ia_ifa);
182                         IN_IFADDR_RUNLOCK(&in_ifa_tracker);
183                         return (ia);
184                 }
185         }
186         IN_IFADDR_RUNLOCK(&in_ifa_tracker);
187
188         return (NULL);
189 }
190
191 /*
192  * Tries to find first IPv4 address in the provided fib.
193  * Prefers non-loopback addresses and return loopback IFF
194  * @loopback_ok is set.
195  *
196  * Returns ifa or NULL.
197  */
198 struct in_ifaddr *
199 in_findlocal(uint32_t fibnum, bool loopback_ok)
200 {
201         struct rm_priotracker in_ifa_tracker;
202         struct in_ifaddr *ia = NULL, *ia_lo = NULL;
203
204         NET_EPOCH_ASSERT();
205
206         IN_IFADDR_RLOCK(&in_ifa_tracker);
207         CK_STAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
208                 uint32_t ia_fib = ia->ia_ifa.ifa_ifp->if_fib;
209                 if (!V_rt_add_addr_allfibs && (fibnum != ia_fib))
210                         continue;
211
212                 if (!IN_LOOPBACK(ntohl(IA_SIN(ia)->sin_addr.s_addr)))
213                         break;
214                 if (loopback_ok)
215                         ia_lo = ia;
216         }
217         IN_IFADDR_RUNLOCK(&in_ifa_tracker);
218
219         if (ia == NULL)
220                 ia = ia_lo;
221
222         return (ia);
223 }
224
225 /*
226  * Determine whether an IP address is in a reserved set of addresses
227  * that may not be forwarded, or whether datagrams to that destination
228  * may be forwarded.
229  */
230 int
231 in_canforward(struct in_addr in)
232 {
233         u_long i = ntohl(in.s_addr);
234
235         if (IN_EXPERIMENTAL(i) || IN_MULTICAST(i) || IN_LINKLOCAL(i) ||
236             IN_ZERONET(i) || IN_LOOPBACK(i))
237                 return (0);
238         return (1);
239 }
240
241 /*
242  * Trim a mask in a sockaddr
243  */
244 static void
245 in_socktrim(struct sockaddr_in *ap)
246 {
247     char *cplim = (char *) &ap->sin_addr;
248     char *cp = (char *) (&ap->sin_addr + 1);
249
250     ap->sin_len = 0;
251     while (--cp >= cplim)
252         if (*cp) {
253             (ap)->sin_len = cp - (char *) (ap) + 1;
254             break;
255         }
256 }
257
258 /*
259  * Generic internet control operations (ioctl's).
260  */
261 int
262 in_control(struct socket *so, u_long cmd, caddr_t data, struct ifnet *ifp,
263     struct thread *td)
264 {
265         struct ifreq *ifr = (struct ifreq *)data;
266         struct sockaddr_in *addr = (struct sockaddr_in *)&ifr->ifr_addr;
267         struct epoch_tracker et;
268         struct ifaddr *ifa;
269         struct in_ifaddr *ia;
270         int error;
271
272         if (ifp == NULL)
273                 return (EADDRNOTAVAIL);
274
275         /*
276          * Filter out 4 ioctls we implement directly.  Forward the rest
277          * to specific functions and ifp->if_ioctl().
278          */
279         switch (cmd) {
280         case SIOCGIFADDR:
281         case SIOCGIFBRDADDR:
282         case SIOCGIFDSTADDR:
283         case SIOCGIFNETMASK:
284                 break;
285         case SIOCGIFALIAS:
286                 sx_xlock(&in_control_sx);
287                 error = in_gifaddr_ioctl(cmd, data, ifp, td);
288                 sx_xunlock(&in_control_sx);
289                 return (error);
290         case SIOCDIFADDR:
291                 sx_xlock(&in_control_sx);
292                 error = in_difaddr_ioctl(cmd, data, ifp, td);
293                 sx_xunlock(&in_control_sx);
294                 return (error);
295         case OSIOCAIFADDR:      /* 9.x compat */
296         case SIOCAIFADDR:
297                 sx_xlock(&in_control_sx);
298                 error = in_aifaddr_ioctl(cmd, data, ifp, td);
299                 sx_xunlock(&in_control_sx);
300                 return (error);
301         case SIOCSIFADDR:
302         case SIOCSIFBRDADDR:
303         case SIOCSIFDSTADDR:
304         case SIOCSIFNETMASK:
305                 /* We no longer support that old commands. */
306                 return (EINVAL);
307         default:
308                 if (ifp->if_ioctl == NULL)
309                         return (EOPNOTSUPP);
310                 return ((*ifp->if_ioctl)(ifp, cmd, data));
311         }
312
313         if (addr->sin_addr.s_addr != INADDR_ANY &&
314             prison_check_ip4(td->td_ucred, &addr->sin_addr) != 0)
315                 return (EADDRNOTAVAIL);
316
317         /*
318          * Find address for this interface, if it exists.  If an
319          * address was specified, find that one instead of the
320          * first one on the interface, if possible.
321          */
322         NET_EPOCH_ENTER(et);
323         CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
324                 if (ifa->ifa_addr->sa_family != AF_INET)
325                         continue;
326                 ia = (struct in_ifaddr *)ifa;
327                 if (ia->ia_addr.sin_addr.s_addr == addr->sin_addr.s_addr)
328                         break;
329         }
330         if (ifa == NULL)
331                 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
332                         if (ifa->ifa_addr->sa_family == AF_INET) {
333                                 ia = (struct in_ifaddr *)ifa;
334                                 if (prison_check_ip4(td->td_ucred,
335                                     &ia->ia_addr.sin_addr) == 0)
336                                         break;
337                         }
338
339         if (ifa == NULL) {
340                 NET_EPOCH_EXIT(et);
341                 return (EADDRNOTAVAIL);
342         }
343
344         error = 0;
345         switch (cmd) {
346         case SIOCGIFADDR:
347                 *addr = ia->ia_addr;
348                 break;
349
350         case SIOCGIFBRDADDR:
351                 if ((ifp->if_flags & IFF_BROADCAST) == 0) {
352                         error = EINVAL;
353                         break;
354                 }
355                 *addr = ia->ia_broadaddr;
356                 break;
357
358         case SIOCGIFDSTADDR:
359                 if ((ifp->if_flags & IFF_POINTOPOINT) == 0) {
360                         error = EINVAL;
361                         break;
362                 }
363                 *addr = ia->ia_dstaddr;
364                 break;
365
366         case SIOCGIFNETMASK:
367                 *addr = ia->ia_sockmask;
368                 break;
369         }
370
371         NET_EPOCH_EXIT(et);
372
373         return (error);
374 }
375
376 static int
377 in_aifaddr_ioctl(u_long cmd, caddr_t data, struct ifnet *ifp, struct thread *td)
378 {
379         const struct in_aliasreq *ifra = (struct in_aliasreq *)data;
380         const struct sockaddr_in *addr = &ifra->ifra_addr;
381         const struct sockaddr_in *broadaddr = &ifra->ifra_broadaddr;
382         const struct sockaddr_in *mask = &ifra->ifra_mask;
383         const struct sockaddr_in *dstaddr = &ifra->ifra_dstaddr;
384         const int vhid = (cmd == SIOCAIFADDR) ? ifra->ifra_vhid : 0;
385         struct epoch_tracker et;
386         struct ifaddr *ifa;
387         struct in_ifaddr *ia;
388         bool iaIsFirst;
389         int error = 0;
390
391         error = priv_check(td, PRIV_NET_ADDIFADDR);
392         if (error)
393                 return (error);
394
395         /*
396          * ifra_addr must be present and be of INET family.
397          * ifra_broadaddr/ifra_dstaddr and ifra_mask are optional.
398          */
399         if (addr->sin_len != sizeof(struct sockaddr_in) ||
400             addr->sin_family != AF_INET)
401                 return (EINVAL);
402         if (broadaddr->sin_len != 0 &&
403             (broadaddr->sin_len != sizeof(struct sockaddr_in) ||
404             broadaddr->sin_family != AF_INET))
405                 return (EINVAL);
406         if (mask->sin_len != 0 &&
407             (mask->sin_len != sizeof(struct sockaddr_in) ||
408             mask->sin_family != AF_INET))
409                 return (EINVAL);
410         if ((ifp->if_flags & IFF_POINTOPOINT) &&
411             (dstaddr->sin_len != sizeof(struct sockaddr_in) ||
412              dstaddr->sin_addr.s_addr == INADDR_ANY))
413                 return (EDESTADDRREQ);
414         if (vhid != 0 && carp_attach_p == NULL)
415                 return (EPROTONOSUPPORT);
416
417         /*
418          * See whether address already exist.
419          */
420         iaIsFirst = true;
421         ia = NULL;
422         NET_EPOCH_ENTER(et);
423         CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
424                 struct in_ifaddr *it;
425
426                 if (ifa->ifa_addr->sa_family != AF_INET)
427                         continue;
428
429                 it = (struct in_ifaddr *)ifa;
430                 if (it->ia_addr.sin_addr.s_addr == addr->sin_addr.s_addr &&
431                     prison_check_ip4(td->td_ucred, &addr->sin_addr) == 0)
432                         ia = it;
433                 else
434                         iaIsFirst = false;
435         }
436         NET_EPOCH_EXIT(et);
437
438         if (ia != NULL)
439                 (void )in_difaddr_ioctl(cmd, data, ifp, td);
440
441         ifa = ifa_alloc(sizeof(struct in_ifaddr), M_WAITOK);
442         ia = (struct in_ifaddr *)ifa;
443         ifa->ifa_addr = (struct sockaddr *)&ia->ia_addr;
444         ifa->ifa_dstaddr = (struct sockaddr *)&ia->ia_dstaddr;
445         ifa->ifa_netmask = (struct sockaddr *)&ia->ia_sockmask;
446         callout_init_rw(&ia->ia_garp_timer, &ifp->if_addr_lock,
447             CALLOUT_RETURNUNLOCKED);
448
449         ia->ia_ifp = ifp;
450         ia->ia_addr = *addr;
451         if (mask->sin_len != 0) {
452                 ia->ia_sockmask = *mask;
453                 ia->ia_subnetmask = ntohl(ia->ia_sockmask.sin_addr.s_addr);
454         } else {
455                 in_addr_t i = ntohl(addr->sin_addr.s_addr);
456
457                 /*
458                  * Be compatible with network classes, if netmask isn't
459                  * supplied, guess it based on classes.
460                  */
461                 if (IN_CLASSA(i))
462                         ia->ia_subnetmask = IN_CLASSA_NET;
463                 else if (IN_CLASSB(i))
464                         ia->ia_subnetmask = IN_CLASSB_NET;
465                 else
466                         ia->ia_subnetmask = IN_CLASSC_NET;
467                 ia->ia_sockmask.sin_addr.s_addr = htonl(ia->ia_subnetmask);
468         }
469         ia->ia_subnet = ntohl(addr->sin_addr.s_addr) & ia->ia_subnetmask;
470         in_socktrim(&ia->ia_sockmask);
471
472         if (ifp->if_flags & IFF_BROADCAST) {
473                 if (broadaddr->sin_len != 0) {
474                         ia->ia_broadaddr = *broadaddr;
475                 } else if (ia->ia_subnetmask == IN_RFC3021_MASK) {
476                         ia->ia_broadaddr.sin_addr.s_addr = INADDR_BROADCAST;
477                         ia->ia_broadaddr.sin_len = sizeof(struct sockaddr_in);
478                         ia->ia_broadaddr.sin_family = AF_INET;
479                 } else {
480                         ia->ia_broadaddr.sin_addr.s_addr =
481                             htonl(ia->ia_subnet | ~ia->ia_subnetmask);
482                         ia->ia_broadaddr.sin_len = sizeof(struct sockaddr_in);
483                         ia->ia_broadaddr.sin_family = AF_INET;
484                 }
485         }
486
487         if (ifp->if_flags & IFF_POINTOPOINT)
488                 ia->ia_dstaddr = *dstaddr;
489
490         if (vhid != 0) {
491                 error = (*carp_attach_p)(&ia->ia_ifa, vhid);
492                 if (error)
493                         return (error);
494         }
495
496         /* if_addrhead is already referenced by ifa_alloc() */
497         IF_ADDR_WLOCK(ifp);
498         CK_STAILQ_INSERT_TAIL(&ifp->if_addrhead, ifa, ifa_link);
499         IF_ADDR_WUNLOCK(ifp);
500
501         ifa_ref(ifa);                   /* in_ifaddrhead */
502         IN_IFADDR_WLOCK();
503         CK_STAILQ_INSERT_TAIL(&V_in_ifaddrhead, ia, ia_link);
504         LIST_INSERT_HEAD(INADDR_HASH(ia->ia_addr.sin_addr.s_addr), ia, ia_hash);
505         IN_IFADDR_WUNLOCK();
506
507         /*
508          * Give the interface a chance to initialize
509          * if this is its first address,
510          * and to validate the address if necessary.
511          */
512         if (ifp->if_ioctl != NULL) {
513                 error = (*ifp->if_ioctl)(ifp, SIOCSIFADDR, (caddr_t)ia);
514                 if (error)
515                         goto fail1;
516         }
517
518         /*
519          * Add route for the network.
520          */
521         if (vhid == 0) {
522                 error = in_addprefix(ia);
523                 if (error)
524                         goto fail1;
525         }
526
527         /*
528          * Add a loopback route to self.
529          */
530         if (vhid == 0 && ia_need_loopback_route(ia)) {
531                 struct in_ifaddr *eia;
532
533                 eia = in_localip_more(ia);
534
535                 if (eia == NULL) {
536                         error = ifa_add_loopback_route((struct ifaddr *)ia,
537                             (struct sockaddr *)&ia->ia_addr);
538                         if (error)
539                                 goto fail2;
540                 } else
541                         ifa_free(&eia->ia_ifa);
542         }
543
544         if (iaIsFirst && (ifp->if_flags & IFF_MULTICAST)) {
545                 struct in_addr allhosts_addr;
546                 struct in_ifinfo *ii;
547
548                 ii = ((struct in_ifinfo *)ifp->if_afdata[AF_INET]);
549                 allhosts_addr.s_addr = htonl(INADDR_ALLHOSTS_GROUP);
550
551                 error = in_joingroup(ifp, &allhosts_addr, NULL,
552                         &ii->ii_allhosts);
553         }
554
555         /*
556          * Note: we don't need extra reference for ifa, since we called
557          * with sx lock held, and ifaddr can not be deleted in concurrent
558          * thread.
559          */
560         EVENTHANDLER_INVOKE(ifaddr_event_ext, ifp, ifa, IFADDR_EVENT_ADD);
561
562         return (error);
563
564 fail2:
565         if (vhid == 0)
566                 (void )in_scrubprefix(ia, LLE_STATIC);
567
568 fail1:
569         if (ia->ia_ifa.ifa_carp)
570                 (*carp_detach_p)(&ia->ia_ifa, false);
571
572         IF_ADDR_WLOCK(ifp);
573         CK_STAILQ_REMOVE(&ifp->if_addrhead, &ia->ia_ifa, ifaddr, ifa_link);
574         IF_ADDR_WUNLOCK(ifp);
575         ifa_free(&ia->ia_ifa);          /* if_addrhead */
576
577         IN_IFADDR_WLOCK();
578         CK_STAILQ_REMOVE(&V_in_ifaddrhead, ia, in_ifaddr, ia_link);
579         LIST_REMOVE(ia, ia_hash);
580         IN_IFADDR_WUNLOCK();
581         ifa_free(&ia->ia_ifa);          /* in_ifaddrhead */
582
583         return (error);
584 }
585
586 static int
587 in_difaddr_ioctl(u_long cmd, caddr_t data, struct ifnet *ifp, struct thread *td)
588 {
589         const struct ifreq *ifr = (struct ifreq *)data;
590         const struct sockaddr_in *addr = (const struct sockaddr_in *)
591             &ifr->ifr_addr;
592         struct ifaddr *ifa;
593         struct in_ifaddr *ia;
594         bool deleteAny, iaIsLast;
595         int error;
596
597         if (td != NULL) {
598                 error = priv_check(td, PRIV_NET_DELIFADDR);
599                 if (error)
600                         return (error);
601         }
602
603         if (addr->sin_len != sizeof(struct sockaddr_in) ||
604             addr->sin_family != AF_INET)
605                 deleteAny = true;
606         else
607                 deleteAny = false;
608
609         iaIsLast = true;
610         ia = NULL;
611         IF_ADDR_WLOCK(ifp);
612         CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
613                 struct in_ifaddr *it;
614
615                 if (ifa->ifa_addr->sa_family != AF_INET)
616                         continue;
617
618                 it = (struct in_ifaddr *)ifa;
619                 if (deleteAny && ia == NULL && (td == NULL ||
620                     prison_check_ip4(td->td_ucred, &it->ia_addr.sin_addr) == 0))
621                         ia = it;
622
623                 if (it->ia_addr.sin_addr.s_addr == addr->sin_addr.s_addr &&
624                     (td == NULL || prison_check_ip4(td->td_ucred,
625                     &addr->sin_addr) == 0))
626                         ia = it;
627
628                 if (it != ia)
629                         iaIsLast = false;
630         }
631
632         if (ia == NULL) {
633                 IF_ADDR_WUNLOCK(ifp);
634                 return (EADDRNOTAVAIL);
635         }
636
637         CK_STAILQ_REMOVE(&ifp->if_addrhead, &ia->ia_ifa, ifaddr, ifa_link);
638         IF_ADDR_WUNLOCK(ifp);
639         ifa_free(&ia->ia_ifa);          /* if_addrhead */
640
641         IN_IFADDR_WLOCK();
642         CK_STAILQ_REMOVE(&V_in_ifaddrhead, ia, in_ifaddr, ia_link);
643         LIST_REMOVE(ia, ia_hash);
644         IN_IFADDR_WUNLOCK();
645
646         /*
647          * in_scrubprefix() kills the interface route.
648          */
649         in_scrubprefix(ia, LLE_STATIC);
650
651         /*
652          * in_ifadown gets rid of all the rest of
653          * the routes.  This is not quite the right
654          * thing to do, but at least if we are running
655          * a routing process they will come back.
656          */
657         in_ifadown(&ia->ia_ifa, 1);
658
659         if (ia->ia_ifa.ifa_carp)
660                 (*carp_detach_p)(&ia->ia_ifa, cmd == SIOCAIFADDR);
661
662         /*
663          * If this is the last IPv4 address configured on this
664          * interface, leave the all-hosts group.
665          * No state-change report need be transmitted.
666          */
667         if (iaIsLast && (ifp->if_flags & IFF_MULTICAST)) {
668                 struct in_ifinfo *ii;
669
670                 ii = ((struct in_ifinfo *)ifp->if_afdata[AF_INET]);
671                 if (ii->ii_allhosts) {
672                         (void)in_leavegroup(ii->ii_allhosts, NULL);
673                         ii->ii_allhosts = NULL;
674                 }
675         }
676
677         IF_ADDR_WLOCK(ifp);
678         if (callout_stop(&ia->ia_garp_timer) == 1) {
679                 ifa_free(&ia->ia_ifa);
680         }
681         IF_ADDR_WUNLOCK(ifp);
682
683         EVENTHANDLER_INVOKE(ifaddr_event_ext, ifp, &ia->ia_ifa,
684             IFADDR_EVENT_DEL);
685         ifa_free(&ia->ia_ifa);          /* in_ifaddrhead */
686
687         return (0);
688 }
689
690 static int
691 in_gifaddr_ioctl(u_long cmd, caddr_t data, struct ifnet *ifp, struct thread *td)
692 {
693         struct in_aliasreq *ifra = (struct in_aliasreq *)data;
694         const struct sockaddr_in *addr = &ifra->ifra_addr;
695         struct epoch_tracker et;
696         struct ifaddr *ifa;
697         struct in_ifaddr *ia;
698
699         /*
700          * ifra_addr must be present and be of INET family.
701          */
702         if (addr->sin_len != sizeof(struct sockaddr_in) ||
703             addr->sin_family != AF_INET)
704                 return (EINVAL);
705
706         /*
707          * See whether address exist.
708          */
709         ia = NULL;
710         NET_EPOCH_ENTER(et);
711         CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
712                 struct in_ifaddr *it;
713
714                 if (ifa->ifa_addr->sa_family != AF_INET)
715                         continue;
716
717                 it = (struct in_ifaddr *)ifa;
718                 if (it->ia_addr.sin_addr.s_addr == addr->sin_addr.s_addr &&
719                     prison_check_ip4(td->td_ucred, &addr->sin_addr) == 0) {
720                         ia = it;
721                         break;
722                 }
723         }
724         if (ia == NULL) {
725                 NET_EPOCH_EXIT(et);
726                 return (EADDRNOTAVAIL);
727         }
728
729         ifra->ifra_mask = ia->ia_sockmask;
730         if ((ifp->if_flags & IFF_POINTOPOINT) &&
731             ia->ia_dstaddr.sin_family == AF_INET)
732                 ifra->ifra_dstaddr = ia->ia_dstaddr;
733         else if ((ifp->if_flags & IFF_BROADCAST) &&
734             ia->ia_broadaddr.sin_family == AF_INET)
735                 ifra->ifra_broadaddr = ia->ia_broadaddr;
736         else
737                 memset(&ifra->ifra_broadaddr, 0,
738                     sizeof(ifra->ifra_broadaddr));
739
740         NET_EPOCH_EXIT(et);
741         return (0);
742 }
743
744 static int
745 in_match_ifaddr(const struct rtentry *rt, const struct nhop_object *nh, void *arg)
746 {
747
748         if (nh->nh_ifa == (struct ifaddr *)arg)
749                 return (1);
750
751         return (0);
752 }
753
754 static int
755 in_handle_prefix_route(uint32_t fibnum, int cmd,
756     struct sockaddr_in *dst, struct sockaddr_in *netmask, struct ifaddr *ifa,
757     struct ifnet *ifp)
758 {
759
760         NET_EPOCH_ASSERT();
761
762         /* Prepare gateway */
763         struct sockaddr_dl_short sdl = {
764                 .sdl_family = AF_LINK,
765                 .sdl_len = sizeof(struct sockaddr_dl_short),
766                 .sdl_type = ifa->ifa_ifp->if_type,
767                 .sdl_index = ifa->ifa_ifp->if_index,
768         };
769
770         struct rt_addrinfo info = {
771                 .rti_ifa = ifa,
772                 .rti_ifp = ifp,
773                 .rti_flags = RTF_PINNED | ((netmask != NULL) ? 0 : RTF_HOST),
774                 .rti_info = {
775                         [RTAX_DST] = (struct sockaddr *)dst,
776                         [RTAX_NETMASK] = (struct sockaddr *)netmask,
777                         [RTAX_GATEWAY] = (struct sockaddr *)&sdl,
778                 },
779                 /* Ensure we delete the prefix IFF prefix ifa matches */
780                 .rti_filter = in_match_ifaddr,
781                 .rti_filterdata = ifa,
782         };
783
784         return (rib_handle_ifaddr_info(fibnum, cmd, &info));
785 }
786
787 /*
788  * Routing table interaction with interface addresses.
789  *
790  * In general, two types of routes needs to be installed:
791  * a) "interface" or "prefix" route, telling user that the addresses
792  *   behind the ifa prefix are reached directly.
793  * b) "loopback" route installed for the ifa address, telling user that
794  *   the address belongs to local system.
795  *
796  * Handling for (a) and (b) differs in multi-fib aspects, hence they
797  *  are implemented in different functions below.
798  *
799  * The cases above may intersect - /32 interface aliases results in
800  *  the same prefix produced by (a) and (b). This blurs the definition
801  *  of the "loopback" route and complicate interactions. The interaction
802  *  table is defined below. The case numbers are used in the multiple
803  *  functions below to refer to the particular test case.
804  *
805  * There can be multiple options:
806  * 1) Adding address with prefix on non-p2p/non-loopback interface.
807  *  Example: 192.0.2.1/24. Action:
808  *  * add "prefix" route towards 192.0.2.0/24 via @ia interface,
809  *    using @ia as an address source.
810  *  * add "loopback" route towards 192.0.2.1 via V_loif, saving
811  *   @ia ifp in the gateway and using @ia as an address source.
812  *
813  * 2) Adding address with /32 mask to non-p2p/non-loopback interface.
814  *  Example: 192.0.2.2/32. Action:
815  *  * add "prefix" host route via V_loif, using @ia as an address source.
816  *
817  * 3) Adding address with or without prefix to p2p interface.
818  *  Example: 10.0.0.1/24->10.0.0.2. Action:
819  *  * add "prefix" host route towards 10.0.0.2 via this interface, using @ia
820  *    as an address source. Note: no sense in installing full /24 as the interface
821  *    is point-to-point.
822  *  * add "loopback" route towards 10.0.9.1 via V_loif, saving
823  *   @ia ifp in the gateway and using @ia as an address source.
824  *
825  * 4) Adding address with or without prefix to loopback interface.
826  *  Example: 192.0.2.1/24. Action:
827  *  * add "prefix" host route via @ia interface, using @ia as an address source.
828  *    Note: Skip installing /24 prefix as it would introduce TTL loop
829  *    for the traffic destined to these addresses.
830  */
831
832 /*
833  * Checks if @ia needs to install loopback route to @ia address via
834  *  ifa_maintain_loopback_route().
835  *
836  * Return true on success.
837  */
838 static bool
839 ia_need_loopback_route(const struct in_ifaddr *ia)
840 {
841         struct ifnet *ifp = ia->ia_ifp;
842
843         /* Case 4: Skip loopback interfaces */
844         if ((ifp->if_flags & IFF_LOOPBACK) ||
845             (ia->ia_addr.sin_addr.s_addr == INADDR_ANY))
846                 return (false);
847
848         /* Clash avoidance: Skip p2p interfaces with both addresses are equal */
849         if ((ifp->if_flags & IFF_POINTOPOINT) &&
850             ia->ia_dstaddr.sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
851                 return (false);
852
853         /* Case 2: skip /32 prefixes */
854         if (!(ifp->if_flags & IFF_POINTOPOINT) &&
855             (ia->ia_sockmask.sin_addr.s_addr == INADDR_BROADCAST))
856                 return (false);
857
858         return (true);
859 }
860
861 /*
862  * Calculate "prefix" route corresponding to @ia.
863  */
864 static void
865 ia_getrtprefix(const struct in_ifaddr *ia, struct in_addr *prefix, struct in_addr *mask)
866 {
867
868         if (ia->ia_ifp->if_flags & IFF_POINTOPOINT) {
869                 /* Case 3: return host route for dstaddr */
870                 *prefix = ia->ia_dstaddr.sin_addr;
871                 mask->s_addr = INADDR_BROADCAST;
872         } else if (ia->ia_ifp->if_flags & IFF_LOOPBACK) {
873                 /* Case 4: return host route for ifaddr */
874                 *prefix = ia->ia_addr.sin_addr;
875                 mask->s_addr = INADDR_BROADCAST;
876         } else {
877                 /* Cases 1,2: return actual ia prefix */
878                 *prefix = ia->ia_addr.sin_addr;
879                 *mask = ia->ia_sockmask.sin_addr;
880                 prefix->s_addr &= mask->s_addr;
881         }
882 }
883
884 /*
885  * Adds or delete interface "prefix" route corresponding to @ifa.
886  *  Returns 0 on success or errno.
887  */
888 int
889 in_handle_ifaddr_route(int cmd, struct in_ifaddr *ia)
890 {
891         struct ifaddr *ifa = &ia->ia_ifa;
892         struct in_addr daddr, maddr;
893         struct sockaddr_in *pmask;
894         struct epoch_tracker et;
895         int error;
896
897         ia_getrtprefix(ia, &daddr, &maddr);
898
899         struct sockaddr_in mask = {
900                 .sin_family = AF_INET,
901                 .sin_len = sizeof(struct sockaddr_in),
902                 .sin_addr = maddr,
903         };
904
905         pmask = (maddr.s_addr != INADDR_BROADCAST) ? &mask : NULL;
906
907         struct sockaddr_in dst = {
908                 .sin_family = AF_INET,
909                 .sin_len = sizeof(struct sockaddr_in),
910                 .sin_addr.s_addr = daddr.s_addr & maddr.s_addr,
911         };
912
913         struct ifnet *ifp = ia->ia_ifp;
914
915         if ((maddr.s_addr == INADDR_BROADCAST) &&
916             (!(ia->ia_ifp->if_flags & (IFF_POINTOPOINT|IFF_LOOPBACK)))) {
917                 /* Case 2: host route on broadcast interface */
918                 ifp = V_loif;
919         }
920
921         uint32_t fibnum = ifa->ifa_ifp->if_fib;
922         NET_EPOCH_ENTER(et);
923         error = in_handle_prefix_route(fibnum, cmd, &dst, pmask, ifa, ifp);
924         NET_EPOCH_EXIT(et);
925
926         return (error);
927 }
928
929 /*
930  * Check if we have a route for the given prefix already.
931  */
932 static bool
933 in_hasrtprefix(struct in_ifaddr *target)
934 {
935         struct rm_priotracker in_ifa_tracker;
936         struct in_ifaddr *ia;
937         struct in_addr prefix, mask, p, m;
938         bool result = false;
939
940         ia_getrtprefix(target, &prefix, &mask);
941
942         IN_IFADDR_RLOCK(&in_ifa_tracker);
943         /* Look for an existing address with the same prefix, mask, and fib */
944         CK_STAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
945                 ia_getrtprefix(ia, &p, &m);
946
947                 if (prefix.s_addr != p.s_addr ||
948                     mask.s_addr != m.s_addr)
949                         continue;
950
951                 if (target->ia_ifp->if_fib != ia->ia_ifp->if_fib)
952                         continue;
953
954                 /*
955                  * If we got a matching prefix route inserted by other
956                  * interface address, we are done here.
957                  */
958                 if (ia->ia_flags & IFA_ROUTE) {
959                         result = true;
960                         break;
961                 }
962         }
963         IN_IFADDR_RUNLOCK(&in_ifa_tracker);
964
965         return (result);
966 }
967
968 int
969 in_addprefix(struct in_ifaddr *target)
970 {
971         int error;
972
973         if (in_hasrtprefix(target)) {
974                 if (V_nosameprefix)
975                         return (EEXIST);
976                 else {
977                         rt_addrmsg(RTM_ADD, &target->ia_ifa,
978                             target->ia_ifp->if_fib);
979                         return (0);
980                 }
981         }
982
983         /*
984          * No-one seem to have this prefix route, so we try to insert it.
985          */
986         rt_addrmsg(RTM_ADD, &target->ia_ifa, target->ia_ifp->if_fib);
987         error = in_handle_ifaddr_route(RTM_ADD, target);
988         if (!error)
989                 target->ia_flags |= IFA_ROUTE;
990         return (error);
991 }
992
993 /*
994  * Removes either all lle entries for given @ia, or lle
995  * corresponding to @ia address.
996  */
997 static void
998 in_scrubprefixlle(struct in_ifaddr *ia, int all, u_int flags)
999 {
1000         struct sockaddr_in addr, mask;
1001         struct sockaddr *saddr, *smask;
1002         struct ifnet *ifp;
1003
1004         saddr = (struct sockaddr *)&addr;
1005         bzero(&addr, sizeof(addr));
1006         addr.sin_len = sizeof(addr);
1007         addr.sin_family = AF_INET;
1008         smask = (struct sockaddr *)&mask;
1009         bzero(&mask, sizeof(mask));
1010         mask.sin_len = sizeof(mask);
1011         mask.sin_family = AF_INET;
1012         mask.sin_addr.s_addr = ia->ia_subnetmask;
1013         ifp = ia->ia_ifp;
1014
1015         if (all) {
1016                 /*
1017                  * Remove all L2 entries matching given prefix.
1018                  * Convert address to host representation to avoid
1019                  * doing this on every callback. ia_subnetmask is already
1020                  * stored in host representation.
1021                  */
1022                 addr.sin_addr.s_addr = ntohl(ia->ia_addr.sin_addr.s_addr);
1023                 lltable_prefix_free(AF_INET, saddr, smask, flags);
1024         } else {
1025                 /* Remove interface address only */
1026                 addr.sin_addr.s_addr = ia->ia_addr.sin_addr.s_addr;
1027                 lltable_delete_addr(LLTABLE(ifp), LLE_IFADDR, saddr);
1028         }
1029 }
1030
1031 /*
1032  * If there is no other address in the system that can serve a route to the
1033  * same prefix, remove the route.  Hand over the route to the new address
1034  * otherwise.
1035  */
1036 int
1037 in_scrubprefix(struct in_ifaddr *target, u_int flags)
1038 {
1039         struct rm_priotracker in_ifa_tracker;
1040         struct in_ifaddr *ia;
1041         struct in_addr prefix, mask, p, m;
1042         int error = 0;
1043
1044         /*
1045          * Remove the loopback route to the interface address.
1046          */
1047         if (ia_need_loopback_route(target) && (flags & LLE_STATIC)) {
1048                 struct in_ifaddr *eia;
1049
1050                 eia = in_localip_more(target);
1051
1052                 if (eia != NULL) {
1053                         error = ifa_switch_loopback_route((struct ifaddr *)eia,
1054                             (struct sockaddr *)&target->ia_addr);
1055                         ifa_free(&eia->ia_ifa);
1056                 } else {
1057                         error = ifa_del_loopback_route((struct ifaddr *)target,
1058                             (struct sockaddr *)&target->ia_addr);
1059                 }
1060         }
1061
1062         ia_getrtprefix(target, &prefix, &mask);
1063
1064         if ((target->ia_flags & IFA_ROUTE) == 0) {
1065                 rt_addrmsg(RTM_DELETE, &target->ia_ifa, target->ia_ifp->if_fib);
1066
1067                 /*
1068                  * Removing address from !IFF_UP interface or
1069                  * prefix which exists on other interface (along with route).
1070                  * No entries should exist here except target addr.
1071                  * Given that, delete this entry only.
1072                  */
1073                 in_scrubprefixlle(target, 0, flags);
1074                 return (0);
1075         }
1076
1077         IN_IFADDR_RLOCK(&in_ifa_tracker);
1078         CK_STAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
1079                 ia_getrtprefix(ia, &p, &m);
1080
1081                 if (prefix.s_addr != p.s_addr ||
1082                     mask.s_addr != m.s_addr)
1083                         continue;
1084
1085                 if ((ia->ia_ifp->if_flags & IFF_UP) == 0)
1086                         continue;
1087
1088                 /*
1089                  * If we got a matching prefix address, move IFA_ROUTE and
1090                  * the route itself to it.  Make sure that routing daemons
1091                  * get a heads-up.
1092                  */
1093                 if ((ia->ia_flags & IFA_ROUTE) == 0) {
1094                         ifa_ref(&ia->ia_ifa);
1095                         IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1096                         error = in_handle_ifaddr_route(RTM_DELETE, target);
1097                         if (error == 0)
1098                                 target->ia_flags &= ~IFA_ROUTE;
1099                         else
1100                                 log(LOG_INFO, "in_scrubprefix: err=%d, old prefix delete failed\n",
1101                                         error);
1102                         /* Scrub all entries IFF interface is different */
1103                         in_scrubprefixlle(target, target->ia_ifp != ia->ia_ifp,
1104                             flags);
1105                         error = in_handle_ifaddr_route(RTM_ADD, ia);
1106                         if (error == 0)
1107                                 ia->ia_flags |= IFA_ROUTE;
1108                         else
1109                                 log(LOG_INFO, "in_scrubprefix: err=%d, new prefix add failed\n",
1110                                         error);
1111                         ifa_free(&ia->ia_ifa);
1112                         return (error);
1113                 }
1114         }
1115         IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1116
1117         /*
1118          * remove all L2 entries on the given prefix
1119          */
1120         in_scrubprefixlle(target, 1, flags);
1121
1122         /*
1123          * As no-one seem to have this prefix, we can remove the route.
1124          */
1125         rt_addrmsg(RTM_DELETE, &target->ia_ifa, target->ia_ifp->if_fib);
1126         error = in_handle_ifaddr_route(RTM_DELETE, target);
1127         if (error == 0)
1128                 target->ia_flags &= ~IFA_ROUTE;
1129         else
1130                 log(LOG_INFO, "in_scrubprefix: err=%d, prefix delete failed\n", error);
1131         return (error);
1132 }
1133
1134 void
1135 in_ifscrub_all(void)
1136 {
1137         struct ifnet *ifp;
1138         struct ifaddr *ifa, *nifa;
1139         struct ifaliasreq ifr;
1140
1141         IFNET_RLOCK();
1142         CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1143                 /* Cannot lock here - lock recursion. */
1144                 /* NET_EPOCH_ENTER(et); */
1145                 CK_STAILQ_FOREACH_SAFE(ifa, &ifp->if_addrhead, ifa_link, nifa) {
1146                         if (ifa->ifa_addr->sa_family != AF_INET)
1147                                 continue;
1148
1149                         /*
1150                          * This is ugly but the only way for legacy IP to
1151                          * cleanly remove addresses and everything attached.
1152                          */
1153                         bzero(&ifr, sizeof(ifr));
1154                         ifr.ifra_addr = *ifa->ifa_addr;
1155                         if (ifa->ifa_dstaddr)
1156                         ifr.ifra_broadaddr = *ifa->ifa_dstaddr;
1157                         (void)in_control(NULL, SIOCDIFADDR, (caddr_t)&ifr,
1158                             ifp, NULL);
1159                 }
1160                 /* NET_EPOCH_EXIT(et); */
1161                 in_purgemaddrs(ifp);
1162                 igmp_domifdetach(ifp);
1163         }
1164         IFNET_RUNLOCK();
1165 }
1166
1167 int
1168 in_ifaddr_broadcast(struct in_addr in, struct in_ifaddr *ia)
1169 {
1170
1171         return ((in.s_addr == ia->ia_broadaddr.sin_addr.s_addr ||
1172              /*
1173               * Check for old-style (host 0) broadcast, but
1174               * taking into account that RFC 3021 obsoletes it.
1175               */
1176             (ia->ia_subnetmask != IN_RFC3021_MASK &&
1177             ntohl(in.s_addr) == ia->ia_subnet)) &&
1178              /*
1179               * Check for an all one subnetmask. These
1180               * only exist when an interface gets a secondary
1181               * address.
1182               */
1183             ia->ia_subnetmask != (u_long)0xffffffff);
1184 }
1185
1186 /*
1187  * Return 1 if the address might be a local broadcast address.
1188  */
1189 int
1190 in_broadcast(struct in_addr in, struct ifnet *ifp)
1191 {
1192         struct ifaddr *ifa;
1193         int found;
1194
1195         NET_EPOCH_ASSERT();
1196
1197         if (in.s_addr == INADDR_BROADCAST ||
1198             in.s_addr == INADDR_ANY)
1199                 return (1);
1200         if ((ifp->if_flags & IFF_BROADCAST) == 0)
1201                 return (0);
1202         found = 0;
1203         /*
1204          * Look through the list of addresses for a match
1205          * with a broadcast address.
1206          */
1207         CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
1208                 if (ifa->ifa_addr->sa_family == AF_INET &&
1209                     in_ifaddr_broadcast(in, (struct in_ifaddr *)ifa)) {
1210                         found = 1;
1211                         break;
1212                 }
1213         return (found);
1214 }
1215
1216 /*
1217  * On interface removal, clean up IPv4 data structures hung off of the ifnet.
1218  */
1219 void
1220 in_ifdetach(struct ifnet *ifp)
1221 {
1222         IN_MULTI_LOCK();
1223         in_pcbpurgeif0(&V_ripcbinfo, ifp);
1224         in_pcbpurgeif0(&V_udbinfo, ifp);
1225         in_pcbpurgeif0(&V_ulitecbinfo, ifp);
1226         in_purgemaddrs(ifp);
1227         IN_MULTI_UNLOCK();
1228
1229         /*
1230          * Make sure all multicast deletions invoking if_ioctl() are
1231          * completed before returning. Else we risk accessing a freed
1232          * ifnet structure pointer.
1233          */
1234         inm_release_wait(NULL);
1235 }
1236
1237 /*
1238  * Delete all IPv4 multicast address records, and associated link-layer
1239  * multicast address records, associated with ifp.
1240  * XXX It looks like domifdetach runs AFTER the link layer cleanup.
1241  * XXX This should not race with ifma_protospec being set during
1242  * a new allocation, if it does, we have bigger problems.
1243  */
1244 static void
1245 in_purgemaddrs(struct ifnet *ifp)
1246 {
1247         struct in_multi_head purgeinms;
1248         struct in_multi         *inm;
1249         struct ifmultiaddr      *ifma, *next;
1250
1251         SLIST_INIT(&purgeinms);
1252         IN_MULTI_LIST_LOCK();
1253
1254         /*
1255          * Extract list of in_multi associated with the detaching ifp
1256          * which the PF_INET layer is about to release.
1257          * We need to do this as IF_ADDR_LOCK() may be re-acquired
1258          * by code further down.
1259          */
1260         IF_ADDR_WLOCK(ifp);
1261  restart:
1262         CK_STAILQ_FOREACH_SAFE(ifma, &ifp->if_multiaddrs, ifma_link, next) {
1263                 if (ifma->ifma_addr->sa_family != AF_INET ||
1264                     ifma->ifma_protospec == NULL)
1265                         continue;
1266                 inm = (struct in_multi *)ifma->ifma_protospec;
1267                 inm_rele_locked(&purgeinms, inm);
1268                 if (__predict_false(ifma_restart)) {
1269                         ifma_restart = true;
1270                         goto restart;
1271                 }
1272         }
1273         IF_ADDR_WUNLOCK(ifp);
1274
1275         inm_release_list_deferred(&purgeinms);
1276         igmp_ifdetach(ifp);
1277         IN_MULTI_LIST_UNLOCK();
1278 }
1279
1280 struct in_llentry {
1281         struct llentry          base;
1282 };
1283
1284 #define IN_LLTBL_DEFAULT_HSIZE  32
1285 #define IN_LLTBL_HASH(k, h) \
1286         (((((((k >> 8) ^ k) >> 8) ^ k) >> 8) ^ k) & ((h) - 1))
1287
1288 /*
1289  * Do actual deallocation of @lle.
1290  */
1291 static void
1292 in_lltable_destroy_lle_unlocked(epoch_context_t ctx)
1293 {
1294         struct llentry *lle;
1295
1296         lle = __containerof(ctx, struct llentry, lle_epoch_ctx);
1297         LLE_LOCK_DESTROY(lle);
1298         LLE_REQ_DESTROY(lle);
1299         free(lle, M_LLTABLE);
1300 }
1301
1302 /*
1303  * Called by LLE_FREE_LOCKED when number of references
1304  * drops to zero.
1305  */
1306 static void
1307 in_lltable_destroy_lle(struct llentry *lle)
1308 {
1309
1310         LLE_WUNLOCK(lle);
1311         NET_EPOCH_CALL(in_lltable_destroy_lle_unlocked, &lle->lle_epoch_ctx);
1312 }
1313
1314 static struct llentry *
1315 in_lltable_new(struct in_addr addr4, u_int flags)
1316 {
1317         struct in_llentry *lle;
1318
1319         lle = malloc(sizeof(struct in_llentry), M_LLTABLE, M_NOWAIT | M_ZERO);
1320         if (lle == NULL)                /* NB: caller generates msg */
1321                 return NULL;
1322
1323         /*
1324          * For IPv4 this will trigger "arpresolve" to generate
1325          * an ARP request.
1326          */
1327         lle->base.la_expire = time_uptime; /* mark expired */
1328         lle->base.r_l3addr.addr4 = addr4;
1329         lle->base.lle_refcnt = 1;
1330         lle->base.lle_free = in_lltable_destroy_lle;
1331         LLE_LOCK_INIT(&lle->base);
1332         LLE_REQ_INIT(&lle->base);
1333         callout_init(&lle->base.lle_timer, 1);
1334
1335         return (&lle->base);
1336 }
1337
1338 #define IN_ARE_MASKED_ADDR_EQUAL(d, a, m)       (               \
1339         ((((d).s_addr ^ (a).s_addr) & (m).s_addr)) == 0 )
1340
1341 static int
1342 in_lltable_match_prefix(const struct sockaddr *saddr,
1343     const struct sockaddr *smask, u_int flags, struct llentry *lle)
1344 {
1345         struct in_addr addr, mask, lle_addr;
1346
1347         addr = ((const struct sockaddr_in *)saddr)->sin_addr;
1348         mask = ((const struct sockaddr_in *)smask)->sin_addr;
1349         lle_addr.s_addr = ntohl(lle->r_l3addr.addr4.s_addr);
1350
1351         if (IN_ARE_MASKED_ADDR_EQUAL(lle_addr, addr, mask) == 0)
1352                 return (0);
1353
1354         if (lle->la_flags & LLE_IFADDR) {
1355                 /*
1356                  * Delete LLE_IFADDR records IFF address & flag matches.
1357                  * Note that addr is the interface address within prefix
1358                  * being matched.
1359                  * Note also we should handle 'ifdown' cases without removing
1360                  * ifaddr macs.
1361                  */
1362                 if (addr.s_addr == lle_addr.s_addr && (flags & LLE_STATIC) != 0)
1363                         return (1);
1364                 return (0);
1365         }
1366
1367         /* flags & LLE_STATIC means deleting both dynamic and static entries */
1368         if ((flags & LLE_STATIC) || !(lle->la_flags & LLE_STATIC))
1369                 return (1);
1370
1371         return (0);
1372 }
1373
1374 static void
1375 in_lltable_free_entry(struct lltable *llt, struct llentry *lle)
1376 {
1377         size_t pkts_dropped;
1378
1379         LLE_WLOCK_ASSERT(lle);
1380         KASSERT(llt != NULL, ("lltable is NULL"));
1381
1382         /* Unlink entry from table if not already */
1383         if ((lle->la_flags & LLE_LINKED) != 0) {
1384                 IF_AFDATA_WLOCK_ASSERT(llt->llt_ifp);
1385                 lltable_unlink_entry(llt, lle);
1386         }
1387
1388         /* Drop hold queue */
1389         pkts_dropped = llentry_free(lle);
1390         ARPSTAT_ADD(dropped, pkts_dropped);
1391 }
1392
1393 static int
1394 in_lltable_rtcheck(struct ifnet *ifp, u_int flags, const struct sockaddr *l3addr)
1395 {
1396         struct nhop_object *nh;
1397         struct in_addr addr;
1398
1399         KASSERT(l3addr->sa_family == AF_INET,
1400             ("sin_family %d", l3addr->sa_family));
1401
1402         addr = ((const struct sockaddr_in *)l3addr)->sin_addr;
1403
1404         nh = fib4_lookup(ifp->if_fib, addr, 0, NHR_NONE, 0);
1405         if (nh == NULL)
1406                 return (EINVAL);
1407
1408         /*
1409          * If the gateway for an existing host route matches the target L3
1410          * address, which is a special route inserted by some implementation
1411          * such as MANET, and the interface is of the correct type, then
1412          * allow for ARP to proceed.
1413          */
1414         if (nh->nh_flags & NHF_GATEWAY) {
1415                 if (!(nh->nh_flags & NHF_HOST) || nh->nh_ifp->if_type != IFT_ETHER ||
1416                     (nh->nh_ifp->if_flags & (IFF_NOARP | IFF_STATICARP)) != 0 ||
1417                     memcmp(nh->gw_sa.sa_data, l3addr->sa_data,
1418                     sizeof(in_addr_t)) != 0) {
1419                         return (EINVAL);
1420                 }
1421         }
1422
1423         /*
1424          * Make sure that at least the destination address is covered
1425          * by the route. This is for handling the case where 2 or more
1426          * interfaces have the same prefix. An incoming packet arrives
1427          * on one interface and the corresponding outgoing packet leaves
1428          * another interface.
1429          */
1430         if ((nh->nh_ifp != ifp) && (nh->nh_flags & NHF_HOST) == 0) {
1431                 struct in_ifaddr *ia = (struct in_ifaddr *)ifaof_ifpforaddr(l3addr, ifp);
1432                 struct in_addr dst_addr, mask_addr;
1433
1434                 if (ia == NULL)
1435                         return (EINVAL);
1436
1437                 /*
1438                  * ifaof_ifpforaddr() returns _best matching_ IFA.
1439                  * It is possible that ifa prefix does not cover our address.
1440                  * Explicitly verify and fail if that's the case.
1441                  */
1442                 dst_addr = IA_SIN(ia)->sin_addr;
1443                 mask_addr.s_addr = htonl(ia->ia_subnetmask);
1444
1445                 if (!IN_ARE_MASKED_ADDR_EQUAL(dst_addr, addr, mask_addr))
1446                         return (EINVAL);
1447         }
1448
1449         return (0);
1450 }
1451
1452 static inline uint32_t
1453 in_lltable_hash_dst(const struct in_addr dst, uint32_t hsize)
1454 {
1455
1456         return (IN_LLTBL_HASH(dst.s_addr, hsize));
1457 }
1458
1459 static uint32_t
1460 in_lltable_hash(const struct llentry *lle, uint32_t hsize)
1461 {
1462
1463         return (in_lltable_hash_dst(lle->r_l3addr.addr4, hsize));
1464 }
1465
1466 static void
1467 in_lltable_fill_sa_entry(const struct llentry *lle, struct sockaddr *sa)
1468 {
1469         struct sockaddr_in *sin;
1470
1471         sin = (struct sockaddr_in *)sa;
1472         bzero(sin, sizeof(*sin));
1473         sin->sin_family = AF_INET;
1474         sin->sin_len = sizeof(*sin);
1475         sin->sin_addr = lle->r_l3addr.addr4;
1476 }
1477
1478 static inline struct llentry *
1479 in_lltable_find_dst(struct lltable *llt, struct in_addr dst)
1480 {
1481         struct llentry *lle;
1482         struct llentries *lleh;
1483         u_int hashidx;
1484
1485         hashidx = in_lltable_hash_dst(dst, llt->llt_hsize);
1486         lleh = &llt->lle_head[hashidx];
1487         CK_LIST_FOREACH(lle, lleh, lle_next) {
1488                 if (lle->la_flags & LLE_DELETED)
1489                         continue;
1490                 if (lle->r_l3addr.addr4.s_addr == dst.s_addr)
1491                         break;
1492         }
1493
1494         return (lle);
1495 }
1496
1497 static void
1498 in_lltable_delete_entry(struct lltable *llt, struct llentry *lle)
1499 {
1500
1501         lle->la_flags |= LLE_DELETED;
1502         EVENTHANDLER_INVOKE(lle_event, lle, LLENTRY_DELETED);
1503 #ifdef DIAGNOSTIC
1504         log(LOG_INFO, "ifaddr cache = %p is deleted\n", lle);
1505 #endif
1506         llentry_free(lle);
1507 }
1508
1509 static struct llentry *
1510 in_lltable_alloc(struct lltable *llt, u_int flags, const struct sockaddr *l3addr)
1511 {
1512         const struct sockaddr_in *sin = (const struct sockaddr_in *)l3addr;
1513         struct ifnet *ifp = llt->llt_ifp;
1514         struct llentry *lle;
1515         char linkhdr[LLE_MAX_LINKHDR];
1516         size_t linkhdrsize;
1517         int lladdr_off;
1518
1519         KASSERT(l3addr->sa_family == AF_INET,
1520             ("sin_family %d", l3addr->sa_family));
1521
1522         /*
1523          * A route that covers the given address must have
1524          * been installed 1st because we are doing a resolution,
1525          * verify this.
1526          */
1527         if (!(flags & LLE_IFADDR) &&
1528             in_lltable_rtcheck(ifp, flags, l3addr) != 0)
1529                 return (NULL);
1530
1531         lle = in_lltable_new(sin->sin_addr, flags);
1532         if (lle == NULL) {
1533                 log(LOG_INFO, "lla_lookup: new lle malloc failed\n");
1534                 return (NULL);
1535         }
1536         lle->la_flags = flags;
1537         if (flags & LLE_STATIC)
1538                 lle->r_flags |= RLLE_VALID;
1539         if ((flags & LLE_IFADDR) == LLE_IFADDR) {
1540                 linkhdrsize = LLE_MAX_LINKHDR;
1541                 if (lltable_calc_llheader(ifp, AF_INET, IF_LLADDR(ifp),
1542                     linkhdr, &linkhdrsize, &lladdr_off) != 0) {
1543                         NET_EPOCH_CALL(in_lltable_destroy_lle_unlocked, &lle->lle_epoch_ctx);
1544                         return (NULL);
1545                 }
1546                 lltable_set_entry_addr(ifp, lle, linkhdr, linkhdrsize,
1547                     lladdr_off);
1548                 lle->la_flags |= LLE_STATIC;
1549                 lle->r_flags |= (RLLE_VALID | RLLE_IFADDR);
1550         }
1551
1552         return (lle);
1553 }
1554
1555 /*
1556  * Return NULL if not found or marked for deletion.
1557  * If found return lle read locked.
1558  */
1559 static struct llentry *
1560 in_lltable_lookup(struct lltable *llt, u_int flags, const struct sockaddr *l3addr)
1561 {
1562         const struct sockaddr_in *sin = (const struct sockaddr_in *)l3addr;
1563         struct llentry *lle;
1564
1565         IF_AFDATA_LOCK_ASSERT(llt->llt_ifp);
1566         KASSERT(l3addr->sa_family == AF_INET,
1567             ("sin_family %d", l3addr->sa_family));
1568         KASSERT((flags & (LLE_UNLOCKED | LLE_EXCLUSIVE)) !=
1569             (LLE_UNLOCKED | LLE_EXCLUSIVE),
1570             ("wrong lle request flags: %#x", flags));
1571
1572         lle = in_lltable_find_dst(llt, sin->sin_addr);
1573         if (lle == NULL)
1574                 return (NULL);
1575         if (flags & LLE_UNLOCKED)
1576                 return (lle);
1577
1578         if (flags & LLE_EXCLUSIVE)
1579                 LLE_WLOCK(lle);
1580         else
1581                 LLE_RLOCK(lle);
1582
1583         /*
1584          * If the afdata lock is not held, the LLE may have been unlinked while
1585          * we were blocked on the LLE lock.  Check for this case.
1586          */
1587         if (__predict_false((lle->la_flags & LLE_LINKED) == 0)) {
1588                 if (flags & LLE_EXCLUSIVE)
1589                         LLE_WUNLOCK(lle);
1590                 else
1591                         LLE_RUNLOCK(lle);
1592                 return (NULL);
1593         }
1594         return (lle);
1595 }
1596
1597 static int
1598 in_lltable_dump_entry(struct lltable *llt, struct llentry *lle,
1599     struct sysctl_req *wr)
1600 {
1601         struct ifnet *ifp = llt->llt_ifp;
1602         /* XXX stack use */
1603         struct {
1604                 struct rt_msghdr        rtm;
1605                 struct sockaddr_in      sin;
1606                 struct sockaddr_dl      sdl;
1607         } arpc;
1608         struct sockaddr_dl *sdl;
1609         int error;
1610
1611         bzero(&arpc, sizeof(arpc));
1612         /* skip deleted entries */
1613         if ((lle->la_flags & LLE_DELETED) == LLE_DELETED)
1614                 return (0);
1615         /* Skip if jailed and not a valid IP of the prison. */
1616         lltable_fill_sa_entry(lle,(struct sockaddr *)&arpc.sin);
1617         if (prison_if(wr->td->td_ucred, (struct sockaddr *)&arpc.sin) != 0)
1618                 return (0);
1619         /*
1620          * produce a msg made of:
1621          *  struct rt_msghdr;
1622          *  struct sockaddr_in; (IPv4)
1623          *  struct sockaddr_dl;
1624          */
1625         arpc.rtm.rtm_msglen = sizeof(arpc);
1626         arpc.rtm.rtm_version = RTM_VERSION;
1627         arpc.rtm.rtm_type = RTM_GET;
1628         arpc.rtm.rtm_flags = RTF_UP;
1629         arpc.rtm.rtm_addrs = RTA_DST | RTA_GATEWAY;
1630
1631         /* publish */
1632         if (lle->la_flags & LLE_PUB)
1633                 arpc.rtm.rtm_flags |= RTF_ANNOUNCE;
1634
1635         sdl = &arpc.sdl;
1636         sdl->sdl_family = AF_LINK;
1637         sdl->sdl_len = sizeof(*sdl);
1638         sdl->sdl_index = ifp->if_index;
1639         sdl->sdl_type = ifp->if_type;
1640         if ((lle->la_flags & LLE_VALID) == LLE_VALID) {
1641                 sdl->sdl_alen = ifp->if_addrlen;
1642                 bcopy(lle->ll_addr, LLADDR(sdl), ifp->if_addrlen);
1643         } else {
1644                 sdl->sdl_alen = 0;
1645                 bzero(LLADDR(sdl), ifp->if_addrlen);
1646         }
1647
1648         arpc.rtm.rtm_rmx.rmx_expire =
1649             lle->la_flags & LLE_STATIC ? 0 : lle->la_expire;
1650         arpc.rtm.rtm_flags |= (RTF_HOST | RTF_LLDATA);
1651         if (lle->la_flags & LLE_STATIC)
1652                 arpc.rtm.rtm_flags |= RTF_STATIC;
1653         if (lle->la_flags & LLE_IFADDR)
1654                 arpc.rtm.rtm_flags |= RTF_PINNED;
1655         arpc.rtm.rtm_index = ifp->if_index;
1656         error = SYSCTL_OUT(wr, &arpc, sizeof(arpc));
1657
1658         return (error);
1659 }
1660
1661 static struct lltable *
1662 in_lltattach(struct ifnet *ifp)
1663 {
1664         struct lltable *llt;
1665
1666         llt = lltable_allocate_htbl(IN_LLTBL_DEFAULT_HSIZE);
1667         llt->llt_af = AF_INET;
1668         llt->llt_ifp = ifp;
1669
1670         llt->llt_lookup = in_lltable_lookup;
1671         llt->llt_alloc_entry = in_lltable_alloc;
1672         llt->llt_delete_entry = in_lltable_delete_entry;
1673         llt->llt_dump_entry = in_lltable_dump_entry;
1674         llt->llt_hash = in_lltable_hash;
1675         llt->llt_fill_sa_entry = in_lltable_fill_sa_entry;
1676         llt->llt_free_entry = in_lltable_free_entry;
1677         llt->llt_match_prefix = in_lltable_match_prefix;
1678         llt->llt_mark_used = llentry_mark_used;
1679         lltable_link(llt);
1680
1681         return (llt);
1682 }
1683
1684 void *
1685 in_domifattach(struct ifnet *ifp)
1686 {
1687         struct in_ifinfo *ii;
1688
1689         ii = malloc(sizeof(struct in_ifinfo), M_IFADDR, M_WAITOK|M_ZERO);
1690
1691         ii->ii_llt = in_lltattach(ifp);
1692         ii->ii_igmp = igmp_domifattach(ifp);
1693
1694         return (ii);
1695 }
1696
1697 void
1698 in_domifdetach(struct ifnet *ifp, void *aux)
1699 {
1700         struct in_ifinfo *ii = (struct in_ifinfo *)aux;
1701
1702         igmp_domifdetach(ifp);
1703         lltable_free(ii->ii_llt);
1704         free(ii, M_IFADDR);
1705 }