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