]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/in_mcast.c
Merge ^/head r364082 through r364250.
[FreeBSD/FreeBSD.git] / sys / netinet / in_mcast.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2007-2009 Bruce Simpson.
5  * Copyright (c) 2005 Robert N. M. Watson.
6  * 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. The name of the author may not be used to endorse or promote
17  *    products derived from this software without specific prior written
18  *    permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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
33 /*
34  * IPv4 multicast socket, group, and socket option processing module.
35  */
36
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/kernel.h>
43 #include <sys/lock.h>
44 #include <sys/malloc.h>
45 #include <sys/mbuf.h>
46 #include <sys/protosw.h>
47 #include <sys/rmlock.h>
48 #include <sys/socket.h>
49 #include <sys/socketvar.h>
50 #include <sys/protosw.h>
51 #include <sys/sysctl.h>
52 #include <sys/ktr.h>
53 #include <sys/taskqueue.h>
54 #include <sys/tree.h>
55
56 #include <net/if.h>
57 #include <net/if_var.h>
58 #include <net/if_dl.h>
59 #include <net/route.h>
60 #include <net/route/nhop.h>
61 #include <net/vnet.h>
62
63 #include <net/ethernet.h>
64
65 #include <netinet/in.h>
66 #include <netinet/in_systm.h>
67 #include <netinet/in_fib.h>
68 #include <netinet/in_pcb.h>
69 #include <netinet/in_var.h>
70 #include <netinet/ip_var.h>
71 #include <netinet/igmp_var.h>
72
73 #ifndef KTR_IGMPV3
74 #define KTR_IGMPV3 KTR_INET
75 #endif
76
77 #ifndef __SOCKUNION_DECLARED
78 union sockunion {
79         struct sockaddr_storage ss;
80         struct sockaddr         sa;
81         struct sockaddr_dl      sdl;
82         struct sockaddr_in      sin;
83 };
84 typedef union sockunion sockunion_t;
85 #define __SOCKUNION_DECLARED
86 #endif /* __SOCKUNION_DECLARED */
87
88 static MALLOC_DEFINE(M_INMFILTER, "in_mfilter",
89     "IPv4 multicast PCB-layer source filter");
90 static MALLOC_DEFINE(M_IPMADDR, "in_multi", "IPv4 multicast group");
91 static MALLOC_DEFINE(M_IPMOPTS, "ip_moptions", "IPv4 multicast options");
92 static MALLOC_DEFINE(M_IPMSOURCE, "ip_msource",
93     "IPv4 multicast IGMP-layer source filter");
94
95 /*
96  * Locking:
97  *
98  * - Lock order is: Giant, IN_MULTI_LOCK, INP_WLOCK,
99  *   IN_MULTI_LIST_LOCK, IGMP_LOCK, IF_ADDR_LOCK.
100  * - The IF_ADDR_LOCK is implicitly taken by inm_lookup() earlier, however
101  *   it can be taken by code in net/if.c also.
102  * - ip_moptions and in_mfilter are covered by the INP_WLOCK.
103  *
104  * struct in_multi is covered by IN_MULTI_LIST_LOCK. There isn't strictly
105  * any need for in_multi itself to be virtualized -- it is bound to an ifp
106  * anyway no matter what happens.
107  */
108 struct mtx in_multi_list_mtx;
109 MTX_SYSINIT(in_multi_mtx, &in_multi_list_mtx, "in_multi_list_mtx", MTX_DEF);
110
111 struct mtx in_multi_free_mtx;
112 MTX_SYSINIT(in_multi_free_mtx, &in_multi_free_mtx, "in_multi_free_mtx", MTX_DEF);
113
114 struct sx in_multi_sx;
115 SX_SYSINIT(in_multi_sx, &in_multi_sx, "in_multi_sx");
116
117 int ifma_restart;
118
119 /*
120  * Functions with non-static linkage defined in this file should be
121  * declared in in_var.h:
122  *  imo_multi_filter()
123  *  in_addmulti()
124  *  in_delmulti()
125  *  in_joingroup()
126  *  in_joingroup_locked()
127  *  in_leavegroup()
128  *  in_leavegroup_locked()
129  * and ip_var.h:
130  *  inp_freemoptions()
131  *  inp_getmoptions()
132  *  inp_setmoptions()
133  *
134  * XXX: Both carp and pf need to use the legacy (*,G) KPIs in_addmulti()
135  * and in_delmulti().
136  */
137 static void     imf_commit(struct in_mfilter *);
138 static int      imf_get_source(struct in_mfilter *imf,
139                     const struct sockaddr_in *psin,
140                     struct in_msource **);
141 static struct in_msource *
142                 imf_graft(struct in_mfilter *, const uint8_t,
143                     const struct sockaddr_in *);
144 static void     imf_leave(struct in_mfilter *);
145 static int      imf_prune(struct in_mfilter *, const struct sockaddr_in *);
146 static void     imf_purge(struct in_mfilter *);
147 static void     imf_rollback(struct in_mfilter *);
148 static void     imf_reap(struct in_mfilter *);
149 static struct in_mfilter *
150                 imo_match_group(const struct ip_moptions *,
151                     const struct ifnet *, const struct sockaddr *);
152 static struct in_msource *
153                 imo_match_source(struct in_mfilter *, const struct sockaddr *);
154 static void     ims_merge(struct ip_msource *ims,
155                     const struct in_msource *lims, const int rollback);
156 static int      in_getmulti(struct ifnet *, const struct in_addr *,
157                     struct in_multi **);
158 static int      inm_get_source(struct in_multi *inm, const in_addr_t haddr,
159                     const int noalloc, struct ip_msource **pims);
160 #ifdef KTR
161 static int      inm_is_ifp_detached(const struct in_multi *);
162 #endif
163 static int      inm_merge(struct in_multi *, /*const*/ struct in_mfilter *);
164 static void     inm_purge(struct in_multi *);
165 static void     inm_reap(struct in_multi *);
166 static void inm_release(struct in_multi *);
167 static struct ip_moptions *
168                 inp_findmoptions(struct inpcb *);
169 static int      inp_get_source_filters(struct inpcb *, struct sockopt *);
170 static int      inp_join_group(struct inpcb *, struct sockopt *);
171 static int      inp_leave_group(struct inpcb *, struct sockopt *);
172 static struct ifnet *
173                 inp_lookup_mcast_ifp(const struct inpcb *,
174                     const struct sockaddr_in *, const struct in_addr);
175 static int      inp_block_unblock_source(struct inpcb *, struct sockopt *);
176 static int      inp_set_multicast_if(struct inpcb *, struct sockopt *);
177 static int      inp_set_source_filters(struct inpcb *, struct sockopt *);
178 static int      sysctl_ip_mcast_filters(SYSCTL_HANDLER_ARGS);
179
180 static SYSCTL_NODE(_net_inet_ip, OID_AUTO, mcast,
181     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
182     "IPv4 multicast");
183
184 static u_long in_mcast_maxgrpsrc = IP_MAX_GROUP_SRC_FILTER;
185 SYSCTL_ULONG(_net_inet_ip_mcast, OID_AUTO, maxgrpsrc,
186     CTLFLAG_RWTUN, &in_mcast_maxgrpsrc, 0,
187     "Max source filters per group");
188
189 static u_long in_mcast_maxsocksrc = IP_MAX_SOCK_SRC_FILTER;
190 SYSCTL_ULONG(_net_inet_ip_mcast, OID_AUTO, maxsocksrc,
191     CTLFLAG_RWTUN, &in_mcast_maxsocksrc, 0,
192     "Max source filters per socket");
193
194 int in_mcast_loop = IP_DEFAULT_MULTICAST_LOOP;
195 SYSCTL_INT(_net_inet_ip_mcast, OID_AUTO, loop, CTLFLAG_RWTUN,
196     &in_mcast_loop, 0, "Loopback multicast datagrams by default");
197
198 static SYSCTL_NODE(_net_inet_ip_mcast, OID_AUTO, filters,
199     CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_ip_mcast_filters,
200     "Per-interface stack-wide source filters");
201
202 #ifdef KTR
203 /*
204  * Inline function which wraps assertions for a valid ifp.
205  * The ifnet layer will set the ifma's ifp pointer to NULL if the ifp
206  * is detached.
207  */
208 static int __inline
209 inm_is_ifp_detached(const struct in_multi *inm)
210 {
211         struct ifnet *ifp;
212
213         KASSERT(inm->inm_ifma != NULL, ("%s: no ifma", __func__));
214         ifp = inm->inm_ifma->ifma_ifp;
215         if (ifp != NULL) {
216                 /*
217                  * Sanity check that netinet's notion of ifp is the
218                  * same as net's.
219                  */
220                 KASSERT(inm->inm_ifp == ifp, ("%s: bad ifp", __func__));
221         }
222
223         return (ifp == NULL);
224 }
225 #endif
226
227 /*
228  * Interface detach can happen in a taskqueue thread context, so we must use a
229  * dedicated thread to avoid deadlocks when draining inm_release tasks.
230  */
231 TASKQUEUE_DEFINE_THREAD(inm_free);
232 static struct in_multi_head inm_free_list = SLIST_HEAD_INITIALIZER();
233 static void inm_release_task(void *arg __unused, int pending __unused);
234 static struct task inm_free_task = TASK_INITIALIZER(0, inm_release_task, NULL);
235
236 void
237 inm_release_wait(void *arg __unused)
238 {
239
240         /*
241          * Make sure all pending multicast addresses are freed before
242          * the VNET or network device is destroyed:
243          */
244         taskqueue_drain(taskqueue_inm_free, &inm_free_task);
245 }
246 #ifdef VIMAGE
247 /* XXX-BZ FIXME, see D24914. */
248 VNET_SYSUNINIT(inm_release_wait, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST, inm_release_wait, NULL);
249 #endif
250
251 void
252 inm_release_list_deferred(struct in_multi_head *inmh)
253 {
254
255         if (SLIST_EMPTY(inmh))
256                 return;
257         mtx_lock(&in_multi_free_mtx);
258         SLIST_CONCAT(&inm_free_list, inmh, in_multi, inm_nrele);
259         mtx_unlock(&in_multi_free_mtx);
260         taskqueue_enqueue(taskqueue_inm_free, &inm_free_task);
261 }
262
263 void
264 inm_disconnect(struct in_multi *inm)
265 {
266         struct ifnet *ifp;
267         struct ifmultiaddr *ifma, *ll_ifma;
268
269         ifp = inm->inm_ifp;
270         IF_ADDR_WLOCK_ASSERT(ifp);
271         ifma = inm->inm_ifma;
272
273         if_ref(ifp);
274         if (ifma->ifma_flags & IFMA_F_ENQUEUED) {
275                 CK_STAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifmultiaddr, ifma_link);
276                 ifma->ifma_flags &= ~IFMA_F_ENQUEUED;
277         }
278         MCDPRINTF("removed ifma: %p from %s\n", ifma, ifp->if_xname);
279         if ((ll_ifma = ifma->ifma_llifma) != NULL) {
280                 MPASS(ifma != ll_ifma);
281                 ifma->ifma_llifma = NULL;
282                 MPASS(ll_ifma->ifma_llifma == NULL);
283                 MPASS(ll_ifma->ifma_ifp == ifp);
284                 if (--ll_ifma->ifma_refcount == 0) {
285                         if (ll_ifma->ifma_flags & IFMA_F_ENQUEUED) {
286                                 CK_STAILQ_REMOVE(&ifp->if_multiaddrs, ll_ifma, ifmultiaddr, ifma_link);
287                                 ll_ifma->ifma_flags &= ~IFMA_F_ENQUEUED;
288                         }
289                         MCDPRINTF("removed ll_ifma: %p from %s\n", ll_ifma, ifp->if_xname);
290                         if_freemulti(ll_ifma);
291                         ifma_restart = true;
292                 }
293         }
294 }
295
296 void
297 inm_release_deferred(struct in_multi *inm)
298 {
299         struct in_multi_head tmp;
300
301         IN_MULTI_LIST_LOCK_ASSERT();
302         MPASS(inm->inm_refcount > 0);
303         if (--inm->inm_refcount == 0) {
304                 SLIST_INIT(&tmp);
305                 inm_disconnect(inm);
306                 inm->inm_ifma->ifma_protospec = NULL;
307                 SLIST_INSERT_HEAD(&tmp, inm, inm_nrele);
308                 inm_release_list_deferred(&tmp);
309         }
310 }
311
312 static void
313 inm_release_task(void *arg __unused, int pending __unused)
314 {
315         struct in_multi_head inm_free_tmp;
316         struct in_multi *inm, *tinm;
317
318         SLIST_INIT(&inm_free_tmp);
319         mtx_lock(&in_multi_free_mtx);
320         SLIST_CONCAT(&inm_free_tmp, &inm_free_list, in_multi, inm_nrele);
321         mtx_unlock(&in_multi_free_mtx);
322         IN_MULTI_LOCK();
323         SLIST_FOREACH_SAFE(inm, &inm_free_tmp, inm_nrele, tinm) {
324                 SLIST_REMOVE_HEAD(&inm_free_tmp, inm_nrele);
325                 MPASS(inm);
326                 inm_release(inm);
327         }
328         IN_MULTI_UNLOCK();
329 }
330
331 /*
332  * Initialize an in_mfilter structure to a known state at t0, t1
333  * with an empty source filter list.
334  */
335 static __inline void
336 imf_init(struct in_mfilter *imf, const int st0, const int st1)
337 {
338         memset(imf, 0, sizeof(struct in_mfilter));
339         RB_INIT(&imf->imf_sources);
340         imf->imf_st[0] = st0;
341         imf->imf_st[1] = st1;
342 }
343
344 struct in_mfilter *
345 ip_mfilter_alloc(const int mflags, const int st0, const int st1)
346 {
347         struct in_mfilter *imf;
348
349         imf = malloc(sizeof(*imf), M_INMFILTER, mflags);
350         if (imf != NULL)
351                 imf_init(imf, st0, st1);
352
353         return (imf);
354 }
355
356 void
357 ip_mfilter_free(struct in_mfilter *imf)
358 {
359
360         imf_purge(imf);
361         free(imf, M_INMFILTER);
362 }
363
364 /*
365  * Function for looking up an in_multi record for an IPv4 multicast address
366  * on a given interface. ifp must be valid. If no record found, return NULL.
367  * The IN_MULTI_LIST_LOCK and IF_ADDR_LOCK on ifp must be held.
368  */
369 struct in_multi *
370 inm_lookup_locked(struct ifnet *ifp, const struct in_addr ina)
371 {
372         struct ifmultiaddr *ifma;
373         struct in_multi *inm;
374
375         IN_MULTI_LIST_LOCK_ASSERT();
376         IF_ADDR_LOCK_ASSERT(ifp);
377
378         inm = NULL;
379         CK_STAILQ_FOREACH(ifma, &((ifp)->if_multiaddrs), ifma_link) {
380                 if (ifma->ifma_addr->sa_family != AF_INET ||
381                         ifma->ifma_protospec == NULL)
382                         continue;
383                 inm = (struct in_multi *)ifma->ifma_protospec;
384                 if (inm->inm_addr.s_addr == ina.s_addr)
385                         break;
386                 inm = NULL;
387         }
388         return (inm);
389 }
390
391 /*
392  * Wrapper for inm_lookup_locked().
393  * The IF_ADDR_LOCK will be taken on ifp and released on return.
394  */
395 struct in_multi *
396 inm_lookup(struct ifnet *ifp, const struct in_addr ina)
397 {
398         struct epoch_tracker et;
399         struct in_multi *inm;
400
401         IN_MULTI_LIST_LOCK_ASSERT();
402         NET_EPOCH_ENTER(et);
403
404         inm = inm_lookup_locked(ifp, ina);
405         NET_EPOCH_EXIT(et);
406
407         return (inm);
408 }
409
410 /*
411  * Find an IPv4 multicast group entry for this ip_moptions instance
412  * which matches the specified group, and optionally an interface.
413  * Return its index into the array, or -1 if not found.
414  */
415 static struct in_mfilter *
416 imo_match_group(const struct ip_moptions *imo, const struct ifnet *ifp,
417     const struct sockaddr *group)
418 {
419         const struct sockaddr_in *gsin;
420         struct in_mfilter *imf;
421         struct in_multi *inm;
422
423         gsin = (const struct sockaddr_in *)group;
424
425         IP_MFILTER_FOREACH(imf, &imo->imo_head) {
426                 inm = imf->imf_inm;
427                 if (inm == NULL)
428                         continue;
429                 if ((ifp == NULL || (inm->inm_ifp == ifp)) &&
430                     in_hosteq(inm->inm_addr, gsin->sin_addr)) {
431                         break;
432                 }
433         }
434         return (imf);
435 }
436
437 /*
438  * Find an IPv4 multicast source entry for this imo which matches
439  * the given group index for this socket, and source address.
440  *
441  * NOTE: This does not check if the entry is in-mode, merely if
442  * it exists, which may not be the desired behaviour.
443  */
444 static struct in_msource *
445 imo_match_source(struct in_mfilter *imf, const struct sockaddr *src)
446 {
447         struct ip_msource        find;
448         struct ip_msource       *ims;
449         const sockunion_t       *psa;
450
451         KASSERT(src->sa_family == AF_INET, ("%s: !AF_INET", __func__));
452
453         /* Source trees are keyed in host byte order. */
454         psa = (const sockunion_t *)src;
455         find.ims_haddr = ntohl(psa->sin.sin_addr.s_addr);
456         ims = RB_FIND(ip_msource_tree, &imf->imf_sources, &find);
457
458         return ((struct in_msource *)ims);
459 }
460
461 /*
462  * Perform filtering for multicast datagrams on a socket by group and source.
463  *
464  * Returns 0 if a datagram should be allowed through, or various error codes
465  * if the socket was not a member of the group, or the source was muted, etc.
466  */
467 int
468 imo_multi_filter(const struct ip_moptions *imo, const struct ifnet *ifp,
469     const struct sockaddr *group, const struct sockaddr *src)
470 {
471         struct in_mfilter *imf;
472         struct in_msource *ims;
473         int mode;
474
475         KASSERT(ifp != NULL, ("%s: null ifp", __func__));
476
477         imf = imo_match_group(imo, ifp, group);
478         if (imf == NULL)
479                 return (MCAST_NOTGMEMBER);
480
481         /*
482          * Check if the source was included in an (S,G) join.
483          * Allow reception on exclusive memberships by default,
484          * reject reception on inclusive memberships by default.
485          * Exclude source only if an in-mode exclude filter exists.
486          * Include source only if an in-mode include filter exists.
487          * NOTE: We are comparing group state here at IGMP t1 (now)
488          * with socket-layer t0 (since last downcall).
489          */
490         mode = imf->imf_st[1];
491         ims = imo_match_source(imf, src);
492
493         if ((ims == NULL && mode == MCAST_INCLUDE) ||
494             (ims != NULL && ims->imsl_st[0] != mode))
495                 return (MCAST_NOTSMEMBER);
496
497         return (MCAST_PASS);
498 }
499
500 /*
501  * Find and return a reference to an in_multi record for (ifp, group),
502  * and bump its reference count.
503  * If one does not exist, try to allocate it, and update link-layer multicast
504  * filters on ifp to listen for group.
505  * Assumes the IN_MULTI lock is held across the call.
506  * Return 0 if successful, otherwise return an appropriate error code.
507  */
508 static int
509 in_getmulti(struct ifnet *ifp, const struct in_addr *group,
510     struct in_multi **pinm)
511 {
512         struct sockaddr_in       gsin;
513         struct ifmultiaddr      *ifma;
514         struct in_ifinfo        *ii;
515         struct in_multi         *inm;
516         int error;
517
518         IN_MULTI_LOCK_ASSERT();
519
520         ii = (struct in_ifinfo *)ifp->if_afdata[AF_INET];
521         IN_MULTI_LIST_LOCK();
522         inm = inm_lookup(ifp, *group);
523         if (inm != NULL) {
524                 /*
525                  * If we already joined this group, just bump the
526                  * refcount and return it.
527                  */
528                 KASSERT(inm->inm_refcount >= 1,
529                     ("%s: bad refcount %d", __func__, inm->inm_refcount));
530                 inm_acquire_locked(inm);
531                 *pinm = inm;
532         }
533         IN_MULTI_LIST_UNLOCK();
534         if (inm != NULL)
535                 return (0);
536
537         memset(&gsin, 0, sizeof(gsin));
538         gsin.sin_family = AF_INET;
539         gsin.sin_len = sizeof(struct sockaddr_in);
540         gsin.sin_addr = *group;
541
542         /*
543          * Check if a link-layer group is already associated
544          * with this network-layer group on the given ifnet.
545          */
546         error = if_addmulti(ifp, (struct sockaddr *)&gsin, &ifma);
547         if (error != 0)
548                 return (error);
549
550         /* XXX ifma_protospec must be covered by IF_ADDR_LOCK */
551         IN_MULTI_LIST_LOCK();
552         IF_ADDR_WLOCK(ifp);
553
554         /*
555          * If something other than netinet is occupying the link-layer
556          * group, print a meaningful error message and back out of
557          * the allocation.
558          * Otherwise, bump the refcount on the existing network-layer
559          * group association and return it.
560          */
561         if (ifma->ifma_protospec != NULL) {
562                 inm = (struct in_multi *)ifma->ifma_protospec;
563 #ifdef INVARIANTS
564                 KASSERT(ifma->ifma_addr != NULL, ("%s: no ifma_addr",
565                     __func__));
566                 KASSERT(ifma->ifma_addr->sa_family == AF_INET,
567                     ("%s: ifma not AF_INET", __func__));
568                 KASSERT(inm != NULL, ("%s: no ifma_protospec", __func__));
569                 if (inm->inm_ifma != ifma || inm->inm_ifp != ifp ||
570                     !in_hosteq(inm->inm_addr, *group)) {
571                         char addrbuf[INET_ADDRSTRLEN];
572
573                         panic("%s: ifma %p is inconsistent with %p (%s)",
574                             __func__, ifma, inm, inet_ntoa_r(*group, addrbuf));
575                 }
576 #endif
577                 inm_acquire_locked(inm);
578                 *pinm = inm;
579                 goto out_locked;
580         }
581
582         IF_ADDR_WLOCK_ASSERT(ifp);
583
584         /*
585          * A new in_multi record is needed; allocate and initialize it.
586          * We DO NOT perform an IGMP join as the in_ layer may need to
587          * push an initial source list down to IGMP to support SSM.
588          *
589          * The initial source filter state is INCLUDE, {} as per the RFC.
590          */
591         inm = malloc(sizeof(*inm), M_IPMADDR, M_NOWAIT | M_ZERO);
592         if (inm == NULL) {
593                 IF_ADDR_WUNLOCK(ifp);
594                 IN_MULTI_LIST_UNLOCK();
595                 if_delmulti_ifma(ifma);
596                 return (ENOMEM);
597         }
598         inm->inm_addr = *group;
599         inm->inm_ifp = ifp;
600         inm->inm_igi = ii->ii_igmp;
601         inm->inm_ifma = ifma;
602         inm->inm_refcount = 1;
603         inm->inm_state = IGMP_NOT_MEMBER;
604         mbufq_init(&inm->inm_scq, IGMP_MAX_STATE_CHANGES);
605         inm->inm_st[0].iss_fmode = MCAST_UNDEFINED;
606         inm->inm_st[1].iss_fmode = MCAST_UNDEFINED;
607         RB_INIT(&inm->inm_srcs);
608
609         ifma->ifma_protospec = inm;
610
611         *pinm = inm;
612  out_locked:
613         IF_ADDR_WUNLOCK(ifp);
614         IN_MULTI_LIST_UNLOCK();
615         return (0);
616 }
617
618 /*
619  * Drop a reference to an in_multi record.
620  *
621  * If the refcount drops to 0, free the in_multi record and
622  * delete the underlying link-layer membership.
623  */
624 static void
625 inm_release(struct in_multi *inm)
626 {
627         struct ifmultiaddr *ifma;
628         struct ifnet *ifp;
629
630         CTR2(KTR_IGMPV3, "%s: refcount is %d", __func__, inm->inm_refcount);
631         MPASS(inm->inm_refcount == 0);
632         CTR2(KTR_IGMPV3, "%s: freeing inm %p", __func__, inm);
633
634         ifma = inm->inm_ifma;
635         ifp = inm->inm_ifp;
636
637         /* XXX this access is not covered by IF_ADDR_LOCK */
638         CTR2(KTR_IGMPV3, "%s: purging ifma %p", __func__, ifma);
639         if (ifp != NULL) {
640                 CURVNET_SET(ifp->if_vnet);
641                 inm_purge(inm);
642                 free(inm, M_IPMADDR);
643                 if_delmulti_ifma_flags(ifma, 1);
644                 CURVNET_RESTORE();
645                 if_rele(ifp);
646         } else {
647                 inm_purge(inm);
648                 free(inm, M_IPMADDR);
649                 if_delmulti_ifma_flags(ifma, 1);
650         }
651 }
652
653 /*
654  * Clear recorded source entries for a group.
655  * Used by the IGMP code. Caller must hold the IN_MULTI lock.
656  * FIXME: Should reap.
657  */
658 void
659 inm_clear_recorded(struct in_multi *inm)
660 {
661         struct ip_msource       *ims;
662
663         IN_MULTI_LIST_LOCK_ASSERT();
664
665         RB_FOREACH(ims, ip_msource_tree, &inm->inm_srcs) {
666                 if (ims->ims_stp) {
667                         ims->ims_stp = 0;
668                         --inm->inm_st[1].iss_rec;
669                 }
670         }
671         KASSERT(inm->inm_st[1].iss_rec == 0,
672             ("%s: iss_rec %d not 0", __func__, inm->inm_st[1].iss_rec));
673 }
674
675 /*
676  * Record a source as pending for a Source-Group IGMPv3 query.
677  * This lives here as it modifies the shared tree.
678  *
679  * inm is the group descriptor.
680  * naddr is the address of the source to record in network-byte order.
681  *
682  * If the net.inet.igmp.sgalloc sysctl is non-zero, we will
683  * lazy-allocate a source node in response to an SG query.
684  * Otherwise, no allocation is performed. This saves some memory
685  * with the trade-off that the source will not be reported to the
686  * router if joined in the window between the query response and
687  * the group actually being joined on the local host.
688  *
689  * VIMAGE: XXX: Currently the igmp_sgalloc feature has been removed.
690  * This turns off the allocation of a recorded source entry if
691  * the group has not been joined.
692  *
693  * Return 0 if the source didn't exist or was already marked as recorded.
694  * Return 1 if the source was marked as recorded by this function.
695  * Return <0 if any error occurred (negated errno code).
696  */
697 int
698 inm_record_source(struct in_multi *inm, const in_addr_t naddr)
699 {
700         struct ip_msource        find;
701         struct ip_msource       *ims, *nims;
702
703         IN_MULTI_LIST_LOCK_ASSERT();
704
705         find.ims_haddr = ntohl(naddr);
706         ims = RB_FIND(ip_msource_tree, &inm->inm_srcs, &find);
707         if (ims && ims->ims_stp)
708                 return (0);
709         if (ims == NULL) {
710                 if (inm->inm_nsrc == in_mcast_maxgrpsrc)
711                         return (-ENOSPC);
712                 nims = malloc(sizeof(struct ip_msource), M_IPMSOURCE,
713                     M_NOWAIT | M_ZERO);
714                 if (nims == NULL)
715                         return (-ENOMEM);
716                 nims->ims_haddr = find.ims_haddr;
717                 RB_INSERT(ip_msource_tree, &inm->inm_srcs, nims);
718                 ++inm->inm_nsrc;
719                 ims = nims;
720         }
721
722         /*
723          * Mark the source as recorded and update the recorded
724          * source count.
725          */
726         ++ims->ims_stp;
727         ++inm->inm_st[1].iss_rec;
728
729         return (1);
730 }
731
732 /*
733  * Return a pointer to an in_msource owned by an in_mfilter,
734  * given its source address.
735  * Lazy-allocate if needed. If this is a new entry its filter state is
736  * undefined at t0.
737  *
738  * imf is the filter set being modified.
739  * haddr is the source address in *host* byte-order.
740  *
741  * SMPng: May be called with locks held; malloc must not block.
742  */
743 static int
744 imf_get_source(struct in_mfilter *imf, const struct sockaddr_in *psin,
745     struct in_msource **plims)
746 {
747         struct ip_msource        find;
748         struct ip_msource       *ims, *nims;
749         struct in_msource       *lims;
750         int                      error;
751
752         error = 0;
753         ims = NULL;
754         lims = NULL;
755
756         /* key is host byte order */
757         find.ims_haddr = ntohl(psin->sin_addr.s_addr);
758         ims = RB_FIND(ip_msource_tree, &imf->imf_sources, &find);
759         lims = (struct in_msource *)ims;
760         if (lims == NULL) {
761                 if (imf->imf_nsrc == in_mcast_maxsocksrc)
762                         return (ENOSPC);
763                 nims = malloc(sizeof(struct in_msource), M_INMFILTER,
764                     M_NOWAIT | M_ZERO);
765                 if (nims == NULL)
766                         return (ENOMEM);
767                 lims = (struct in_msource *)nims;
768                 lims->ims_haddr = find.ims_haddr;
769                 lims->imsl_st[0] = MCAST_UNDEFINED;
770                 RB_INSERT(ip_msource_tree, &imf->imf_sources, nims);
771                 ++imf->imf_nsrc;
772         }
773
774         *plims = lims;
775
776         return (error);
777 }
778
779 /*
780  * Graft a source entry into an existing socket-layer filter set,
781  * maintaining any required invariants and checking allocations.
782  *
783  * The source is marked as being in the new filter mode at t1.
784  *
785  * Return the pointer to the new node, otherwise return NULL.
786  */
787 static struct in_msource *
788 imf_graft(struct in_mfilter *imf, const uint8_t st1,
789     const struct sockaddr_in *psin)
790 {
791         struct ip_msource       *nims;
792         struct in_msource       *lims;
793
794         nims = malloc(sizeof(struct in_msource), M_INMFILTER,
795             M_NOWAIT | M_ZERO);
796         if (nims == NULL)
797                 return (NULL);
798         lims = (struct in_msource *)nims;
799         lims->ims_haddr = ntohl(psin->sin_addr.s_addr);
800         lims->imsl_st[0] = MCAST_UNDEFINED;
801         lims->imsl_st[1] = st1;
802         RB_INSERT(ip_msource_tree, &imf->imf_sources, nims);
803         ++imf->imf_nsrc;
804
805         return (lims);
806 }
807
808 /*
809  * Prune a source entry from an existing socket-layer filter set,
810  * maintaining any required invariants and checking allocations.
811  *
812  * The source is marked as being left at t1, it is not freed.
813  *
814  * Return 0 if no error occurred, otherwise return an errno value.
815  */
816 static int
817 imf_prune(struct in_mfilter *imf, const struct sockaddr_in *psin)
818 {
819         struct ip_msource        find;
820         struct ip_msource       *ims;
821         struct in_msource       *lims;
822
823         /* key is host byte order */
824         find.ims_haddr = ntohl(psin->sin_addr.s_addr);
825         ims = RB_FIND(ip_msource_tree, &imf->imf_sources, &find);
826         if (ims == NULL)
827                 return (ENOENT);
828         lims = (struct in_msource *)ims;
829         lims->imsl_st[1] = MCAST_UNDEFINED;
830         return (0);
831 }
832
833 /*
834  * Revert socket-layer filter set deltas at t1 to t0 state.
835  */
836 static void
837 imf_rollback(struct in_mfilter *imf)
838 {
839         struct ip_msource       *ims, *tims;
840         struct in_msource       *lims;
841
842         RB_FOREACH_SAFE(ims, ip_msource_tree, &imf->imf_sources, tims) {
843                 lims = (struct in_msource *)ims;
844                 if (lims->imsl_st[0] == lims->imsl_st[1]) {
845                         /* no change at t1 */
846                         continue;
847                 } else if (lims->imsl_st[0] != MCAST_UNDEFINED) {
848                         /* revert change to existing source at t1 */
849                         lims->imsl_st[1] = lims->imsl_st[0];
850                 } else {
851                         /* revert source added t1 */
852                         CTR2(KTR_IGMPV3, "%s: free ims %p", __func__, ims);
853                         RB_REMOVE(ip_msource_tree, &imf->imf_sources, ims);
854                         free(ims, M_INMFILTER);
855                         imf->imf_nsrc--;
856                 }
857         }
858         imf->imf_st[1] = imf->imf_st[0];
859 }
860
861 /*
862  * Mark socket-layer filter set as INCLUDE {} at t1.
863  */
864 static void
865 imf_leave(struct in_mfilter *imf)
866 {
867         struct ip_msource       *ims;
868         struct in_msource       *lims;
869
870         RB_FOREACH(ims, ip_msource_tree, &imf->imf_sources) {
871                 lims = (struct in_msource *)ims;
872                 lims->imsl_st[1] = MCAST_UNDEFINED;
873         }
874         imf->imf_st[1] = MCAST_INCLUDE;
875 }
876
877 /*
878  * Mark socket-layer filter set deltas as committed.
879  */
880 static void
881 imf_commit(struct in_mfilter *imf)
882 {
883         struct ip_msource       *ims;
884         struct in_msource       *lims;
885
886         RB_FOREACH(ims, ip_msource_tree, &imf->imf_sources) {
887                 lims = (struct in_msource *)ims;
888                 lims->imsl_st[0] = lims->imsl_st[1];
889         }
890         imf->imf_st[0] = imf->imf_st[1];
891 }
892
893 /*
894  * Reap unreferenced sources from socket-layer filter set.
895  */
896 static void
897 imf_reap(struct in_mfilter *imf)
898 {
899         struct ip_msource       *ims, *tims;
900         struct in_msource       *lims;
901
902         RB_FOREACH_SAFE(ims, ip_msource_tree, &imf->imf_sources, tims) {
903                 lims = (struct in_msource *)ims;
904                 if ((lims->imsl_st[0] == MCAST_UNDEFINED) &&
905                     (lims->imsl_st[1] == MCAST_UNDEFINED)) {
906                         CTR2(KTR_IGMPV3, "%s: free lims %p", __func__, ims);
907                         RB_REMOVE(ip_msource_tree, &imf->imf_sources, ims);
908                         free(ims, M_INMFILTER);
909                         imf->imf_nsrc--;
910                 }
911         }
912 }
913
914 /*
915  * Purge socket-layer filter set.
916  */
917 static void
918 imf_purge(struct in_mfilter *imf)
919 {
920         struct ip_msource       *ims, *tims;
921
922         RB_FOREACH_SAFE(ims, ip_msource_tree, &imf->imf_sources, tims) {
923                 CTR2(KTR_IGMPV3, "%s: free ims %p", __func__, ims);
924                 RB_REMOVE(ip_msource_tree, &imf->imf_sources, ims);
925                 free(ims, M_INMFILTER);
926                 imf->imf_nsrc--;
927         }
928         imf->imf_st[0] = imf->imf_st[1] = MCAST_UNDEFINED;
929         KASSERT(RB_EMPTY(&imf->imf_sources),
930             ("%s: imf_sources not empty", __func__));
931 }
932
933 /*
934  * Look up a source filter entry for a multicast group.
935  *
936  * inm is the group descriptor to work with.
937  * haddr is the host-byte-order IPv4 address to look up.
938  * noalloc may be non-zero to suppress allocation of sources.
939  * *pims will be set to the address of the retrieved or allocated source.
940  *
941  * SMPng: NOTE: may be called with locks held.
942  * Return 0 if successful, otherwise return a non-zero error code.
943  */
944 static int
945 inm_get_source(struct in_multi *inm, const in_addr_t haddr,
946     const int noalloc, struct ip_msource **pims)
947 {
948         struct ip_msource        find;
949         struct ip_msource       *ims, *nims;
950
951         find.ims_haddr = haddr;
952         ims = RB_FIND(ip_msource_tree, &inm->inm_srcs, &find);
953         if (ims == NULL && !noalloc) {
954                 if (inm->inm_nsrc == in_mcast_maxgrpsrc)
955                         return (ENOSPC);
956                 nims = malloc(sizeof(struct ip_msource), M_IPMSOURCE,
957                     M_NOWAIT | M_ZERO);
958                 if (nims == NULL)
959                         return (ENOMEM);
960                 nims->ims_haddr = haddr;
961                 RB_INSERT(ip_msource_tree, &inm->inm_srcs, nims);
962                 ++inm->inm_nsrc;
963                 ims = nims;
964 #ifdef KTR
965                 CTR3(KTR_IGMPV3, "%s: allocated 0x%08x as %p", __func__,
966                     haddr, ims);
967 #endif
968         }
969
970         *pims = ims;
971         return (0);
972 }
973
974 /*
975  * Merge socket-layer source into IGMP-layer source.
976  * If rollback is non-zero, perform the inverse of the merge.
977  */
978 static void
979 ims_merge(struct ip_msource *ims, const struct in_msource *lims,
980     const int rollback)
981 {
982         int n = rollback ? -1 : 1;
983
984         if (lims->imsl_st[0] == MCAST_EXCLUDE) {
985                 CTR3(KTR_IGMPV3, "%s: t1 ex -= %d on 0x%08x",
986                     __func__, n, ims->ims_haddr);
987                 ims->ims_st[1].ex -= n;
988         } else if (lims->imsl_st[0] == MCAST_INCLUDE) {
989                 CTR3(KTR_IGMPV3, "%s: t1 in -= %d on 0x%08x",
990                     __func__, n, ims->ims_haddr);
991                 ims->ims_st[1].in -= n;
992         }
993
994         if (lims->imsl_st[1] == MCAST_EXCLUDE) {
995                 CTR3(KTR_IGMPV3, "%s: t1 ex += %d on 0x%08x",
996                     __func__, n, ims->ims_haddr);
997                 ims->ims_st[1].ex += n;
998         } else if (lims->imsl_st[1] == MCAST_INCLUDE) {
999                 CTR3(KTR_IGMPV3, "%s: t1 in += %d on 0x%08x",
1000                     __func__, n, ims->ims_haddr);
1001                 ims->ims_st[1].in += n;
1002         }
1003 }
1004
1005 /*
1006  * Atomically update the global in_multi state, when a membership's
1007  * filter list is being updated in any way.
1008  *
1009  * imf is the per-inpcb-membership group filter pointer.
1010  * A fake imf may be passed for in-kernel consumers.
1011  *
1012  * XXX This is a candidate for a set-symmetric-difference style loop
1013  * which would eliminate the repeated lookup from root of ims nodes,
1014  * as they share the same key space.
1015  *
1016  * If any error occurred this function will back out of refcounts
1017  * and return a non-zero value.
1018  */
1019 static int
1020 inm_merge(struct in_multi *inm, /*const*/ struct in_mfilter *imf)
1021 {
1022         struct ip_msource       *ims, *nims;
1023         struct in_msource       *lims;
1024         int                      schanged, error;
1025         int                      nsrc0, nsrc1;
1026
1027         schanged = 0;
1028         error = 0;
1029         nsrc1 = nsrc0 = 0;
1030         IN_MULTI_LIST_LOCK_ASSERT();
1031
1032         /*
1033          * Update the source filters first, as this may fail.
1034          * Maintain count of in-mode filters at t0, t1. These are
1035          * used to work out if we transition into ASM mode or not.
1036          * Maintain a count of source filters whose state was
1037          * actually modified by this operation.
1038          */
1039         RB_FOREACH(ims, ip_msource_tree, &imf->imf_sources) {
1040                 lims = (struct in_msource *)ims;
1041                 if (lims->imsl_st[0] == imf->imf_st[0]) nsrc0++;
1042                 if (lims->imsl_st[1] == imf->imf_st[1]) nsrc1++;
1043                 if (lims->imsl_st[0] == lims->imsl_st[1]) continue;
1044                 error = inm_get_source(inm, lims->ims_haddr, 0, &nims);
1045                 ++schanged;
1046                 if (error)
1047                         break;
1048                 ims_merge(nims, lims, 0);
1049         }
1050         if (error) {
1051                 struct ip_msource *bims;
1052
1053                 RB_FOREACH_REVERSE_FROM(ims, ip_msource_tree, nims) {
1054                         lims = (struct in_msource *)ims;
1055                         if (lims->imsl_st[0] == lims->imsl_st[1])
1056                                 continue;
1057                         (void)inm_get_source(inm, lims->ims_haddr, 1, &bims);
1058                         if (bims == NULL)
1059                                 continue;
1060                         ims_merge(bims, lims, 1);
1061                 }
1062                 goto out_reap;
1063         }
1064
1065         CTR3(KTR_IGMPV3, "%s: imf filters in-mode: %d at t0, %d at t1",
1066             __func__, nsrc0, nsrc1);
1067
1068         /* Handle transition between INCLUDE {n} and INCLUDE {} on socket. */
1069         if (imf->imf_st[0] == imf->imf_st[1] &&
1070             imf->imf_st[1] == MCAST_INCLUDE) {
1071                 if (nsrc1 == 0) {
1072                         CTR1(KTR_IGMPV3, "%s: --in on inm at t1", __func__);
1073                         --inm->inm_st[1].iss_in;
1074                 }
1075         }
1076
1077         /* Handle filter mode transition on socket. */
1078         if (imf->imf_st[0] != imf->imf_st[1]) {
1079                 CTR3(KTR_IGMPV3, "%s: imf transition %d to %d",
1080                     __func__, imf->imf_st[0], imf->imf_st[1]);
1081
1082                 if (imf->imf_st[0] == MCAST_EXCLUDE) {
1083                         CTR1(KTR_IGMPV3, "%s: --ex on inm at t1", __func__);
1084                         --inm->inm_st[1].iss_ex;
1085                 } else if (imf->imf_st[0] == MCAST_INCLUDE) {
1086                         CTR1(KTR_IGMPV3, "%s: --in on inm at t1", __func__);
1087                         --inm->inm_st[1].iss_in;
1088                 }
1089
1090                 if (imf->imf_st[1] == MCAST_EXCLUDE) {
1091                         CTR1(KTR_IGMPV3, "%s: ex++ on inm at t1", __func__);
1092                         inm->inm_st[1].iss_ex++;
1093                 } else if (imf->imf_st[1] == MCAST_INCLUDE && nsrc1 > 0) {
1094                         CTR1(KTR_IGMPV3, "%s: in++ on inm at t1", __func__);
1095                         inm->inm_st[1].iss_in++;
1096                 }
1097         }
1098
1099         /*
1100          * Track inm filter state in terms of listener counts.
1101          * If there are any exclusive listeners, stack-wide
1102          * membership is exclusive.
1103          * Otherwise, if only inclusive listeners, stack-wide is inclusive.
1104          * If no listeners remain, state is undefined at t1,
1105          * and the IGMP lifecycle for this group should finish.
1106          */
1107         if (inm->inm_st[1].iss_ex > 0) {
1108                 CTR1(KTR_IGMPV3, "%s: transition to EX", __func__);
1109                 inm->inm_st[1].iss_fmode = MCAST_EXCLUDE;
1110         } else if (inm->inm_st[1].iss_in > 0) {
1111                 CTR1(KTR_IGMPV3, "%s: transition to IN", __func__);
1112                 inm->inm_st[1].iss_fmode = MCAST_INCLUDE;
1113         } else {
1114                 CTR1(KTR_IGMPV3, "%s: transition to UNDEF", __func__);
1115                 inm->inm_st[1].iss_fmode = MCAST_UNDEFINED;
1116         }
1117
1118         /* Decrement ASM listener count on transition out of ASM mode. */
1119         if (imf->imf_st[0] == MCAST_EXCLUDE && nsrc0 == 0) {
1120                 if ((imf->imf_st[1] != MCAST_EXCLUDE) ||
1121                     (imf->imf_st[1] == MCAST_EXCLUDE && nsrc1 > 0)) {
1122                         CTR1(KTR_IGMPV3, "%s: --asm on inm at t1", __func__);
1123                         --inm->inm_st[1].iss_asm;
1124                 }
1125         }
1126
1127         /* Increment ASM listener count on transition to ASM mode. */
1128         if (imf->imf_st[1] == MCAST_EXCLUDE && nsrc1 == 0) {
1129                 CTR1(KTR_IGMPV3, "%s: asm++ on inm at t1", __func__);
1130                 inm->inm_st[1].iss_asm++;
1131         }
1132
1133         CTR3(KTR_IGMPV3, "%s: merged imf %p to inm %p", __func__, imf, inm);
1134         inm_print(inm);
1135
1136 out_reap:
1137         if (schanged > 0) {
1138                 CTR1(KTR_IGMPV3, "%s: sources changed; reaping", __func__);
1139                 inm_reap(inm);
1140         }
1141         return (error);
1142 }
1143
1144 /*
1145  * Mark an in_multi's filter set deltas as committed.
1146  * Called by IGMP after a state change has been enqueued.
1147  */
1148 void
1149 inm_commit(struct in_multi *inm)
1150 {
1151         struct ip_msource       *ims;
1152
1153         CTR2(KTR_IGMPV3, "%s: commit inm %p", __func__, inm);
1154         CTR1(KTR_IGMPV3, "%s: pre commit:", __func__);
1155         inm_print(inm);
1156
1157         RB_FOREACH(ims, ip_msource_tree, &inm->inm_srcs) {
1158                 ims->ims_st[0] = ims->ims_st[1];
1159         }
1160         inm->inm_st[0] = inm->inm_st[1];
1161 }
1162
1163 /*
1164  * Reap unreferenced nodes from an in_multi's filter set.
1165  */
1166 static void
1167 inm_reap(struct in_multi *inm)
1168 {
1169         struct ip_msource       *ims, *tims;
1170
1171         RB_FOREACH_SAFE(ims, ip_msource_tree, &inm->inm_srcs, tims) {
1172                 if (ims->ims_st[0].ex > 0 || ims->ims_st[0].in > 0 ||
1173                     ims->ims_st[1].ex > 0 || ims->ims_st[1].in > 0 ||
1174                     ims->ims_stp != 0)
1175                         continue;
1176                 CTR2(KTR_IGMPV3, "%s: free ims %p", __func__, ims);
1177                 RB_REMOVE(ip_msource_tree, &inm->inm_srcs, ims);
1178                 free(ims, M_IPMSOURCE);
1179                 inm->inm_nsrc--;
1180         }
1181 }
1182
1183 /*
1184  * Purge all source nodes from an in_multi's filter set.
1185  */
1186 static void
1187 inm_purge(struct in_multi *inm)
1188 {
1189         struct ip_msource       *ims, *tims;
1190
1191         RB_FOREACH_SAFE(ims, ip_msource_tree, &inm->inm_srcs, tims) {
1192                 CTR2(KTR_IGMPV3, "%s: free ims %p", __func__, ims);
1193                 RB_REMOVE(ip_msource_tree, &inm->inm_srcs, ims);
1194                 free(ims, M_IPMSOURCE);
1195                 inm->inm_nsrc--;
1196         }
1197 }
1198
1199 /*
1200  * Join a multicast group; unlocked entry point.
1201  *
1202  * SMPng: XXX: in_joingroup() is called from in_control() when Giant
1203  * is not held. Fortunately, ifp is unlikely to have been detached
1204  * at this point, so we assume it's OK to recurse.
1205  */
1206 int
1207 in_joingroup(struct ifnet *ifp, const struct in_addr *gina,
1208     /*const*/ struct in_mfilter *imf, struct in_multi **pinm)
1209 {
1210         int error;
1211
1212         IN_MULTI_LOCK();
1213         error = in_joingroup_locked(ifp, gina, imf, pinm);
1214         IN_MULTI_UNLOCK();
1215
1216         return (error);
1217 }
1218
1219 /*
1220  * Join a multicast group; real entry point.
1221  *
1222  * Only preserves atomicity at inm level.
1223  * NOTE: imf argument cannot be const due to sys/tree.h limitations.
1224  *
1225  * If the IGMP downcall fails, the group is not joined, and an error
1226  * code is returned.
1227  */
1228 int
1229 in_joingroup_locked(struct ifnet *ifp, const struct in_addr *gina,
1230     /*const*/ struct in_mfilter *imf, struct in_multi **pinm)
1231 {
1232         struct in_mfilter        timf;
1233         struct in_multi         *inm;
1234         int                      error;
1235
1236         IN_MULTI_LOCK_ASSERT();
1237         IN_MULTI_LIST_UNLOCK_ASSERT();
1238
1239         CTR4(KTR_IGMPV3, "%s: join 0x%08x on %p(%s))", __func__,
1240             ntohl(gina->s_addr), ifp, ifp->if_xname);
1241
1242         error = 0;
1243         inm = NULL;
1244
1245         /*
1246          * If no imf was specified (i.e. kernel consumer),
1247          * fake one up and assume it is an ASM join.
1248          */
1249         if (imf == NULL) {
1250                 imf_init(&timf, MCAST_UNDEFINED, MCAST_EXCLUDE);
1251                 imf = &timf;
1252         }
1253
1254         error = in_getmulti(ifp, gina, &inm);
1255         if (error) {
1256                 CTR1(KTR_IGMPV3, "%s: in_getmulti() failure", __func__);
1257                 return (error);
1258         }
1259         IN_MULTI_LIST_LOCK();
1260         CTR1(KTR_IGMPV3, "%s: merge inm state", __func__);
1261         error = inm_merge(inm, imf);
1262         if (error) {
1263                 CTR1(KTR_IGMPV3, "%s: failed to merge inm state", __func__);
1264                 goto out_inm_release;
1265         }
1266
1267         CTR1(KTR_IGMPV3, "%s: doing igmp downcall", __func__);
1268         error = igmp_change_state(inm);
1269         if (error) {
1270                 CTR1(KTR_IGMPV3, "%s: failed to update source", __func__);
1271                 goto out_inm_release;
1272         }
1273
1274  out_inm_release:
1275         if (error) {
1276
1277                 CTR2(KTR_IGMPV3, "%s: dropping ref on %p", __func__, inm);
1278                 IF_ADDR_WLOCK(ifp);
1279                 inm_release_deferred(inm);
1280                 IF_ADDR_WUNLOCK(ifp);
1281         } else {
1282                 *pinm = inm;
1283         }
1284         IN_MULTI_LIST_UNLOCK();
1285
1286         return (error);
1287 }
1288
1289 /*
1290  * Leave a multicast group; unlocked entry point.
1291  */
1292 int
1293 in_leavegroup(struct in_multi *inm, /*const*/ struct in_mfilter *imf)
1294 {
1295         int error;
1296
1297         IN_MULTI_LOCK();
1298         error = in_leavegroup_locked(inm, imf);
1299         IN_MULTI_UNLOCK();
1300
1301         return (error);
1302 }
1303
1304 /*
1305  * Leave a multicast group; real entry point.
1306  * All source filters will be expunged.
1307  *
1308  * Only preserves atomicity at inm level.
1309  *
1310  * Holding the write lock for the INP which contains imf
1311  * is highly advisable. We can't assert for it as imf does not
1312  * contain a back-pointer to the owning inp.
1313  *
1314  * Note: This is not the same as inm_release(*) as this function also
1315  * makes a state change downcall into IGMP.
1316  */
1317 int
1318 in_leavegroup_locked(struct in_multi *inm, /*const*/ struct in_mfilter *imf)
1319 {
1320         struct in_mfilter        timf;
1321         int                      error;
1322
1323         IN_MULTI_LOCK_ASSERT();
1324         IN_MULTI_LIST_UNLOCK_ASSERT();
1325
1326         error = 0;
1327
1328         CTR5(KTR_IGMPV3, "%s: leave inm %p, 0x%08x/%s, imf %p", __func__,
1329             inm, ntohl(inm->inm_addr.s_addr),
1330             (inm_is_ifp_detached(inm) ? "null" : inm->inm_ifp->if_xname),
1331             imf);
1332
1333         /*
1334          * If no imf was specified (i.e. kernel consumer),
1335          * fake one up and assume it is an ASM join.
1336          */
1337         if (imf == NULL) {
1338                 imf_init(&timf, MCAST_EXCLUDE, MCAST_UNDEFINED);
1339                 imf = &timf;
1340         }
1341
1342         /*
1343          * Begin state merge transaction at IGMP layer.
1344          *
1345          * As this particular invocation should not cause any memory
1346          * to be allocated, and there is no opportunity to roll back
1347          * the transaction, it MUST NOT fail.
1348          */
1349         CTR1(KTR_IGMPV3, "%s: merge inm state", __func__);
1350         IN_MULTI_LIST_LOCK();
1351         error = inm_merge(inm, imf);
1352         KASSERT(error == 0, ("%s: failed to merge inm state", __func__));
1353
1354         CTR1(KTR_IGMPV3, "%s: doing igmp downcall", __func__);
1355         CURVNET_SET(inm->inm_ifp->if_vnet);
1356         error = igmp_change_state(inm);
1357         IF_ADDR_WLOCK(inm->inm_ifp);
1358         inm_release_deferred(inm);
1359         IF_ADDR_WUNLOCK(inm->inm_ifp);
1360         IN_MULTI_LIST_UNLOCK();
1361         CURVNET_RESTORE();
1362         if (error)
1363                 CTR1(KTR_IGMPV3, "%s: failed igmp downcall", __func__);
1364
1365         CTR2(KTR_IGMPV3, "%s: dropping ref on %p", __func__, inm);
1366
1367         return (error);
1368 }
1369
1370 /*#ifndef BURN_BRIDGES*/
1371 /*
1372  * Join an IPv4 multicast group in (*,G) exclusive mode.
1373  * The group must be a 224.0.0.0/24 link-scope group.
1374  * This KPI is for legacy kernel consumers only.
1375  */
1376 struct in_multi *
1377 in_addmulti(struct in_addr *ap, struct ifnet *ifp)
1378 {
1379         struct in_multi *pinm;
1380         int error;
1381 #ifdef INVARIANTS
1382         char addrbuf[INET_ADDRSTRLEN];
1383 #endif
1384
1385         KASSERT(IN_LOCAL_GROUP(ntohl(ap->s_addr)),
1386             ("%s: %s not in 224.0.0.0/24", __func__,
1387             inet_ntoa_r(*ap, addrbuf)));
1388
1389         error = in_joingroup(ifp, ap, NULL, &pinm);
1390         if (error != 0)
1391                 pinm = NULL;
1392
1393         return (pinm);
1394 }
1395
1396 /*
1397  * Block or unblock an ASM multicast source on an inpcb.
1398  * This implements the delta-based API described in RFC 3678.
1399  *
1400  * The delta-based API applies only to exclusive-mode memberships.
1401  * An IGMP downcall will be performed.
1402  *
1403  * SMPng: NOTE: Must take Giant as a join may create a new ifma.
1404  *
1405  * Return 0 if successful, otherwise return an appropriate error code.
1406  */
1407 static int
1408 inp_block_unblock_source(struct inpcb *inp, struct sockopt *sopt)
1409 {
1410         struct group_source_req          gsr;
1411         struct rm_priotracker            in_ifa_tracker;
1412         sockunion_t                     *gsa, *ssa;
1413         struct ifnet                    *ifp;
1414         struct in_mfilter               *imf;
1415         struct ip_moptions              *imo;
1416         struct in_msource               *ims;
1417         struct in_multi                 *inm;
1418         uint16_t                         fmode;
1419         int                              error, doblock;
1420
1421         ifp = NULL;
1422         error = 0;
1423         doblock = 0;
1424
1425         memset(&gsr, 0, sizeof(struct group_source_req));
1426         gsa = (sockunion_t *)&gsr.gsr_group;
1427         ssa = (sockunion_t *)&gsr.gsr_source;
1428
1429         switch (sopt->sopt_name) {
1430         case IP_BLOCK_SOURCE:
1431         case IP_UNBLOCK_SOURCE: {
1432                 struct ip_mreq_source    mreqs;
1433
1434                 error = sooptcopyin(sopt, &mreqs,
1435                     sizeof(struct ip_mreq_source),
1436                     sizeof(struct ip_mreq_source));
1437                 if (error)
1438                         return (error);
1439
1440                 gsa->sin.sin_family = AF_INET;
1441                 gsa->sin.sin_len = sizeof(struct sockaddr_in);
1442                 gsa->sin.sin_addr = mreqs.imr_multiaddr;
1443
1444                 ssa->sin.sin_family = AF_INET;
1445                 ssa->sin.sin_len = sizeof(struct sockaddr_in);
1446                 ssa->sin.sin_addr = mreqs.imr_sourceaddr;
1447
1448                 if (!in_nullhost(mreqs.imr_interface)) {
1449                         IN_IFADDR_RLOCK(&in_ifa_tracker);
1450                         INADDR_TO_IFP(mreqs.imr_interface, ifp);
1451                         IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1452                 }
1453                 if (sopt->sopt_name == IP_BLOCK_SOURCE)
1454                         doblock = 1;
1455
1456                 CTR3(KTR_IGMPV3, "%s: imr_interface = 0x%08x, ifp = %p",
1457                     __func__, ntohl(mreqs.imr_interface.s_addr), ifp);
1458                 break;
1459             }
1460
1461         case MCAST_BLOCK_SOURCE:
1462         case MCAST_UNBLOCK_SOURCE:
1463                 error = sooptcopyin(sopt, &gsr,
1464                     sizeof(struct group_source_req),
1465                     sizeof(struct group_source_req));
1466                 if (error)
1467                         return (error);
1468
1469                 if (gsa->sin.sin_family != AF_INET ||
1470                     gsa->sin.sin_len != sizeof(struct sockaddr_in))
1471                         return (EINVAL);
1472
1473                 if (ssa->sin.sin_family != AF_INET ||
1474                     ssa->sin.sin_len != sizeof(struct sockaddr_in))
1475                         return (EINVAL);
1476
1477                 if (gsr.gsr_interface == 0 || V_if_index < gsr.gsr_interface)
1478                         return (EADDRNOTAVAIL);
1479
1480                 ifp = ifnet_byindex(gsr.gsr_interface);
1481
1482                 if (sopt->sopt_name == MCAST_BLOCK_SOURCE)
1483                         doblock = 1;
1484                 break;
1485
1486         default:
1487                 CTR2(KTR_IGMPV3, "%s: unknown sopt_name %d",
1488                     __func__, sopt->sopt_name);
1489                 return (EOPNOTSUPP);
1490                 break;
1491         }
1492
1493         if (!IN_MULTICAST(ntohl(gsa->sin.sin_addr.s_addr)))
1494                 return (EINVAL);
1495
1496         IN_MULTI_LOCK();
1497
1498         /*
1499          * Check if we are actually a member of this group.
1500          */
1501         imo = inp_findmoptions(inp);
1502         imf = imo_match_group(imo, ifp, &gsa->sa);
1503         if (imf == NULL) {
1504                 error = EADDRNOTAVAIL;
1505                 goto out_inp_locked;
1506         }
1507         inm = imf->imf_inm;
1508
1509         /*
1510          * Attempting to use the delta-based API on an
1511          * non exclusive-mode membership is an error.
1512          */
1513         fmode = imf->imf_st[0];
1514         if (fmode != MCAST_EXCLUDE) {
1515                 error = EINVAL;
1516                 goto out_inp_locked;
1517         }
1518
1519         /*
1520          * Deal with error cases up-front:
1521          *  Asked to block, but already blocked; or
1522          *  Asked to unblock, but nothing to unblock.
1523          * If adding a new block entry, allocate it.
1524          */
1525         ims = imo_match_source(imf, &ssa->sa);
1526         if ((ims != NULL && doblock) || (ims == NULL && !doblock)) {
1527                 CTR3(KTR_IGMPV3, "%s: source 0x%08x %spresent", __func__,
1528                     ntohl(ssa->sin.sin_addr.s_addr), doblock ? "" : "not ");
1529                 error = EADDRNOTAVAIL;
1530                 goto out_inp_locked;
1531         }
1532
1533         INP_WLOCK_ASSERT(inp);
1534
1535         /*
1536          * Begin state merge transaction at socket layer.
1537          */
1538         if (doblock) {
1539                 CTR2(KTR_IGMPV3, "%s: %s source", __func__, "block");
1540                 ims = imf_graft(imf, fmode, &ssa->sin);
1541                 if (ims == NULL)
1542                         error = ENOMEM;
1543         } else {
1544                 CTR2(KTR_IGMPV3, "%s: %s source", __func__, "allow");
1545                 error = imf_prune(imf, &ssa->sin);
1546         }
1547
1548         if (error) {
1549                 CTR1(KTR_IGMPV3, "%s: merge imf state failed", __func__);
1550                 goto out_imf_rollback;
1551         }
1552
1553         /*
1554          * Begin state merge transaction at IGMP layer.
1555          */
1556         CTR1(KTR_IGMPV3, "%s: merge inm state", __func__);
1557         IN_MULTI_LIST_LOCK();
1558         error = inm_merge(inm, imf);
1559         if (error) {
1560                 CTR1(KTR_IGMPV3, "%s: failed to merge inm state", __func__);
1561                 IN_MULTI_LIST_UNLOCK();
1562                 goto out_imf_rollback;
1563         }
1564
1565         CTR1(KTR_IGMPV3, "%s: doing igmp downcall", __func__);
1566         error = igmp_change_state(inm);
1567         IN_MULTI_LIST_UNLOCK();
1568         if (error)
1569                 CTR1(KTR_IGMPV3, "%s: failed igmp downcall", __func__);
1570
1571 out_imf_rollback:
1572         if (error)
1573                 imf_rollback(imf);
1574         else
1575                 imf_commit(imf);
1576
1577         imf_reap(imf);
1578
1579 out_inp_locked:
1580         INP_WUNLOCK(inp);
1581         IN_MULTI_UNLOCK();
1582         return (error);
1583 }
1584
1585 /*
1586  * Given an inpcb, return its multicast options structure pointer.  Accepts
1587  * an unlocked inpcb pointer, but will return it locked.  May sleep.
1588  *
1589  * SMPng: NOTE: Potentially calls malloc(M_WAITOK) with Giant held.
1590  * SMPng: NOTE: Returns with the INP write lock held.
1591  */
1592 static struct ip_moptions *
1593 inp_findmoptions(struct inpcb *inp)
1594 {
1595         struct ip_moptions       *imo;
1596
1597         INP_WLOCK(inp);
1598         if (inp->inp_moptions != NULL)
1599                 return (inp->inp_moptions);
1600
1601         INP_WUNLOCK(inp);
1602
1603         imo = malloc(sizeof(*imo), M_IPMOPTS, M_WAITOK);
1604
1605         imo->imo_multicast_ifp = NULL;
1606         imo->imo_multicast_addr.s_addr = INADDR_ANY;
1607         imo->imo_multicast_vif = -1;
1608         imo->imo_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1609         imo->imo_multicast_loop = in_mcast_loop;
1610         STAILQ_INIT(&imo->imo_head);
1611
1612         INP_WLOCK(inp);
1613         if (inp->inp_moptions != NULL) {
1614                 free(imo, M_IPMOPTS);
1615                 return (inp->inp_moptions);
1616         }
1617         inp->inp_moptions = imo;
1618         return (imo);
1619 }
1620
1621 static void
1622 inp_gcmoptions(struct ip_moptions *imo)
1623 {
1624         struct in_mfilter *imf;
1625         struct in_multi *inm;
1626         struct ifnet *ifp;
1627
1628         while ((imf = ip_mfilter_first(&imo->imo_head)) != NULL) {
1629                 ip_mfilter_remove(&imo->imo_head, imf);
1630
1631                 imf_leave(imf);
1632                 if ((inm = imf->imf_inm) != NULL) {
1633                         if ((ifp = inm->inm_ifp) != NULL) {
1634                                 CURVNET_SET(ifp->if_vnet);
1635                                 (void)in_leavegroup(inm, imf);
1636                                 CURVNET_RESTORE();
1637                         } else {
1638                                 (void)in_leavegroup(inm, imf);
1639                         }
1640                 }
1641                 ip_mfilter_free(imf);
1642         }
1643         free(imo, M_IPMOPTS);
1644 }
1645
1646 /*
1647  * Discard the IP multicast options (and source filters).  To minimize
1648  * the amount of work done while holding locks such as the INP's
1649  * pcbinfo lock (which is used in the receive path), the free
1650  * operation is deferred to the epoch callback task.
1651  */
1652 void
1653 inp_freemoptions(struct ip_moptions *imo)
1654 {
1655         if (imo == NULL)
1656                 return;
1657         inp_gcmoptions(imo);
1658 }
1659
1660 /*
1661  * Atomically get source filters on a socket for an IPv4 multicast group.
1662  * Called with INP lock held; returns with lock released.
1663  */
1664 static int
1665 inp_get_source_filters(struct inpcb *inp, struct sockopt *sopt)
1666 {
1667         struct __msfilterreq     msfr;
1668         sockunion_t             *gsa;
1669         struct ifnet            *ifp;
1670         struct ip_moptions      *imo;
1671         struct in_mfilter       *imf;
1672         struct ip_msource       *ims;
1673         struct in_msource       *lims;
1674         struct sockaddr_in      *psin;
1675         struct sockaddr_storage *ptss;
1676         struct sockaddr_storage *tss;
1677         int                      error;
1678         size_t                   nsrcs, ncsrcs;
1679
1680         INP_WLOCK_ASSERT(inp);
1681
1682         imo = inp->inp_moptions;
1683         KASSERT(imo != NULL, ("%s: null ip_moptions", __func__));
1684
1685         INP_WUNLOCK(inp);
1686
1687         error = sooptcopyin(sopt, &msfr, sizeof(struct __msfilterreq),
1688             sizeof(struct __msfilterreq));
1689         if (error)
1690                 return (error);
1691
1692         if (msfr.msfr_ifindex == 0 || V_if_index < msfr.msfr_ifindex)
1693                 return (EINVAL);
1694
1695         ifp = ifnet_byindex(msfr.msfr_ifindex);
1696         if (ifp == NULL)
1697                 return (EINVAL);
1698
1699         INP_WLOCK(inp);
1700
1701         /*
1702          * Lookup group on the socket.
1703          */
1704         gsa = (sockunion_t *)&msfr.msfr_group;
1705         imf = imo_match_group(imo, ifp, &gsa->sa);
1706         if (imf == NULL) {
1707                 INP_WUNLOCK(inp);
1708                 return (EADDRNOTAVAIL);
1709         }
1710
1711         /*
1712          * Ignore memberships which are in limbo.
1713          */
1714         if (imf->imf_st[1] == MCAST_UNDEFINED) {
1715                 INP_WUNLOCK(inp);
1716                 return (EAGAIN);
1717         }
1718         msfr.msfr_fmode = imf->imf_st[1];
1719
1720         /*
1721          * If the user specified a buffer, copy out the source filter
1722          * entries to userland gracefully.
1723          * We only copy out the number of entries which userland
1724          * has asked for, but we always tell userland how big the
1725          * buffer really needs to be.
1726          */
1727         if (msfr.msfr_nsrcs > in_mcast_maxsocksrc)
1728                 msfr.msfr_nsrcs = in_mcast_maxsocksrc;
1729         tss = NULL;
1730         if (msfr.msfr_srcs != NULL && msfr.msfr_nsrcs > 0) {
1731                 tss = malloc(sizeof(struct sockaddr_storage) * msfr.msfr_nsrcs,
1732                     M_TEMP, M_NOWAIT | M_ZERO);
1733                 if (tss == NULL) {
1734                         INP_WUNLOCK(inp);
1735                         return (ENOBUFS);
1736                 }
1737         }
1738
1739         /*
1740          * Count number of sources in-mode at t0.
1741          * If buffer space exists and remains, copy out source entries.
1742          */
1743         nsrcs = msfr.msfr_nsrcs;
1744         ncsrcs = 0;
1745         ptss = tss;
1746         RB_FOREACH(ims, ip_msource_tree, &imf->imf_sources) {
1747                 lims = (struct in_msource *)ims;
1748                 if (lims->imsl_st[0] == MCAST_UNDEFINED ||
1749                     lims->imsl_st[0] != imf->imf_st[0])
1750                         continue;
1751                 ++ncsrcs;
1752                 if (tss != NULL && nsrcs > 0) {
1753                         psin = (struct sockaddr_in *)ptss;
1754                         psin->sin_family = AF_INET;
1755                         psin->sin_len = sizeof(struct sockaddr_in);
1756                         psin->sin_addr.s_addr = htonl(lims->ims_haddr);
1757                         psin->sin_port = 0;
1758                         ++ptss;
1759                         --nsrcs;
1760                 }
1761         }
1762
1763         INP_WUNLOCK(inp);
1764
1765         if (tss != NULL) {
1766                 error = copyout(tss, msfr.msfr_srcs,
1767                     sizeof(struct sockaddr_storage) * msfr.msfr_nsrcs);
1768                 free(tss, M_TEMP);
1769                 if (error)
1770                         return (error);
1771         }
1772
1773         msfr.msfr_nsrcs = ncsrcs;
1774         error = sooptcopyout(sopt, &msfr, sizeof(struct __msfilterreq));
1775
1776         return (error);
1777 }
1778
1779 /*
1780  * Return the IP multicast options in response to user getsockopt().
1781  */
1782 int
1783 inp_getmoptions(struct inpcb *inp, struct sockopt *sopt)
1784 {
1785         struct rm_priotracker    in_ifa_tracker;
1786         struct ip_mreqn          mreqn;
1787         struct ip_moptions      *imo;
1788         struct ifnet            *ifp;
1789         struct in_ifaddr        *ia;
1790         int                      error, optval;
1791         u_char                   coptval;
1792
1793         INP_WLOCK(inp);
1794         imo = inp->inp_moptions;
1795         /*
1796          * If socket is neither of type SOCK_RAW or SOCK_DGRAM,
1797          * or is a divert socket, reject it.
1798          */
1799         if (inp->inp_socket->so_proto->pr_protocol == IPPROTO_DIVERT ||
1800             (inp->inp_socket->so_proto->pr_type != SOCK_RAW &&
1801             inp->inp_socket->so_proto->pr_type != SOCK_DGRAM)) {
1802                 INP_WUNLOCK(inp);
1803                 return (EOPNOTSUPP);
1804         }
1805
1806         error = 0;
1807         switch (sopt->sopt_name) {
1808         case IP_MULTICAST_VIF:
1809                 if (imo != NULL)
1810                         optval = imo->imo_multicast_vif;
1811                 else
1812                         optval = -1;
1813                 INP_WUNLOCK(inp);
1814                 error = sooptcopyout(sopt, &optval, sizeof(int));
1815                 break;
1816
1817         case IP_MULTICAST_IF:
1818                 memset(&mreqn, 0, sizeof(struct ip_mreqn));
1819                 if (imo != NULL) {
1820                         ifp = imo->imo_multicast_ifp;
1821                         if (!in_nullhost(imo->imo_multicast_addr)) {
1822                                 mreqn.imr_address = imo->imo_multicast_addr;
1823                         } else if (ifp != NULL) {
1824                                 struct epoch_tracker et;
1825
1826                                 mreqn.imr_ifindex = ifp->if_index;
1827                                 NET_EPOCH_ENTER(et);
1828                                 IFP_TO_IA(ifp, ia, &in_ifa_tracker);
1829                                 if (ia != NULL)
1830                                         mreqn.imr_address =
1831                                             IA_SIN(ia)->sin_addr;
1832                                 NET_EPOCH_EXIT(et);
1833                         }
1834                 }
1835                 INP_WUNLOCK(inp);
1836                 if (sopt->sopt_valsize == sizeof(struct ip_mreqn)) {
1837                         error = sooptcopyout(sopt, &mreqn,
1838                             sizeof(struct ip_mreqn));
1839                 } else {
1840                         error = sooptcopyout(sopt, &mreqn.imr_address,
1841                             sizeof(struct in_addr));
1842                 }
1843                 break;
1844
1845         case IP_MULTICAST_TTL:
1846                 if (imo == NULL)
1847                         optval = coptval = IP_DEFAULT_MULTICAST_TTL;
1848                 else
1849                         optval = coptval = imo->imo_multicast_ttl;
1850                 INP_WUNLOCK(inp);
1851                 if (sopt->sopt_valsize == sizeof(u_char))
1852                         error = sooptcopyout(sopt, &coptval, sizeof(u_char));
1853                 else
1854                         error = sooptcopyout(sopt, &optval, sizeof(int));
1855                 break;
1856
1857         case IP_MULTICAST_LOOP:
1858                 if (imo == NULL)
1859                         optval = coptval = IP_DEFAULT_MULTICAST_LOOP;
1860                 else
1861                         optval = coptval = imo->imo_multicast_loop;
1862                 INP_WUNLOCK(inp);
1863                 if (sopt->sopt_valsize == sizeof(u_char))
1864                         error = sooptcopyout(sopt, &coptval, sizeof(u_char));
1865                 else
1866                         error = sooptcopyout(sopt, &optval, sizeof(int));
1867                 break;
1868
1869         case IP_MSFILTER:
1870                 if (imo == NULL) {
1871                         error = EADDRNOTAVAIL;
1872                         INP_WUNLOCK(inp);
1873                 } else {
1874                         error = inp_get_source_filters(inp, sopt);
1875                 }
1876                 break;
1877
1878         default:
1879                 INP_WUNLOCK(inp);
1880                 error = ENOPROTOOPT;
1881                 break;
1882         }
1883
1884         INP_UNLOCK_ASSERT(inp);
1885
1886         return (error);
1887 }
1888
1889 /*
1890  * Look up the ifnet to use for a multicast group membership,
1891  * given the IPv4 address of an interface, and the IPv4 group address.
1892  *
1893  * This routine exists to support legacy multicast applications
1894  * which do not understand that multicast memberships are scoped to
1895  * specific physical links in the networking stack, or which need
1896  * to join link-scope groups before IPv4 addresses are configured.
1897  *
1898  * If inp is non-NULL, use this socket's current FIB number for any
1899  * required FIB lookup.
1900  * If ina is INADDR_ANY, look up the group address in the unicast FIB,
1901  * and use its ifp; usually, this points to the default next-hop.
1902  *
1903  * If the FIB lookup fails, attempt to use the first non-loopback
1904  * interface with multicast capability in the system as a
1905  * last resort. The legacy IPv4 ASM API requires that we do
1906  * this in order to allow groups to be joined when the routing
1907  * table has not yet been populated during boot.
1908  *
1909  * Returns NULL if no ifp could be found.
1910  *
1911  * FUTURE: Implement IPv4 source-address selection.
1912  */
1913 static struct ifnet *
1914 inp_lookup_mcast_ifp(const struct inpcb *inp,
1915     const struct sockaddr_in *gsin, const struct in_addr ina)
1916 {
1917         struct rm_priotracker in_ifa_tracker;
1918         struct ifnet *ifp;
1919         struct nhop_object *nh;
1920         uint32_t fibnum;
1921
1922         KASSERT(gsin->sin_family == AF_INET, ("%s: not AF_INET", __func__));
1923         KASSERT(IN_MULTICAST(ntohl(gsin->sin_addr.s_addr)),
1924             ("%s: not multicast", __func__));
1925
1926         ifp = NULL;
1927         if (!in_nullhost(ina)) {
1928                 IN_IFADDR_RLOCK(&in_ifa_tracker);
1929                 INADDR_TO_IFP(ina, ifp);
1930                 IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1931         } else {
1932                 fibnum = inp ? inp->inp_inc.inc_fibnum : 0;
1933                 nh = fib4_lookup(fibnum, gsin->sin_addr, 0, 0, 0);
1934                 if (nh != NULL)
1935                         ifp = nh->nh_ifp;
1936                 else {
1937                         struct in_ifaddr *ia;
1938                         struct ifnet *mifp;
1939
1940                         mifp = NULL;
1941                         IN_IFADDR_RLOCK(&in_ifa_tracker);
1942                         CK_STAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
1943                                 mifp = ia->ia_ifp;
1944                                 if (!(mifp->if_flags & IFF_LOOPBACK) &&
1945                                      (mifp->if_flags & IFF_MULTICAST)) {
1946                                         ifp = mifp;
1947                                         break;
1948                                 }
1949                         }
1950                         IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1951                 }
1952         }
1953
1954         return (ifp);
1955 }
1956
1957 /*
1958  * Join an IPv4 multicast group, possibly with a source.
1959  */
1960 static int
1961 inp_join_group(struct inpcb *inp, struct sockopt *sopt)
1962 {
1963         struct group_source_req          gsr;
1964         sockunion_t                     *gsa, *ssa;
1965         struct ifnet                    *ifp;
1966         struct in_mfilter               *imf;
1967         struct ip_moptions              *imo;
1968         struct in_multi                 *inm;
1969         struct in_msource               *lims;
1970         int                              error, is_new;
1971
1972         ifp = NULL;
1973         lims = NULL;
1974         error = 0;
1975
1976         memset(&gsr, 0, sizeof(struct group_source_req));
1977         gsa = (sockunion_t *)&gsr.gsr_group;
1978         gsa->ss.ss_family = AF_UNSPEC;
1979         ssa = (sockunion_t *)&gsr.gsr_source;
1980         ssa->ss.ss_family = AF_UNSPEC;
1981
1982         switch (sopt->sopt_name) {
1983         case IP_ADD_MEMBERSHIP: {
1984                 struct ip_mreqn mreqn;
1985
1986                 if (sopt->sopt_valsize == sizeof(struct ip_mreqn))
1987                         error = sooptcopyin(sopt, &mreqn,
1988                             sizeof(struct ip_mreqn), sizeof(struct ip_mreqn));
1989                 else
1990                         error = sooptcopyin(sopt, &mreqn,
1991                             sizeof(struct ip_mreq), sizeof(struct ip_mreq));
1992                 if (error)
1993                         return (error);
1994
1995                 gsa->sin.sin_family = AF_INET;
1996                 gsa->sin.sin_len = sizeof(struct sockaddr_in);
1997                 gsa->sin.sin_addr = mreqn.imr_multiaddr;
1998                 if (!IN_MULTICAST(ntohl(gsa->sin.sin_addr.s_addr)))
1999                         return (EINVAL);
2000
2001                 if (sopt->sopt_valsize == sizeof(struct ip_mreqn) &&
2002                     mreqn.imr_ifindex != 0)
2003                         ifp = ifnet_byindex(mreqn.imr_ifindex);
2004                 else
2005                         ifp = inp_lookup_mcast_ifp(inp, &gsa->sin,
2006                             mreqn.imr_address);
2007                 break;
2008         }
2009         case IP_ADD_SOURCE_MEMBERSHIP: {
2010                 struct ip_mreq_source    mreqs;
2011
2012                 error = sooptcopyin(sopt, &mreqs, sizeof(struct ip_mreq_source),
2013                             sizeof(struct ip_mreq_source));
2014                 if (error)
2015                         return (error);
2016
2017                 gsa->sin.sin_family = ssa->sin.sin_family = AF_INET;
2018                 gsa->sin.sin_len = ssa->sin.sin_len =
2019                     sizeof(struct sockaddr_in);
2020
2021                 gsa->sin.sin_addr = mreqs.imr_multiaddr;
2022                 if (!IN_MULTICAST(ntohl(gsa->sin.sin_addr.s_addr)))
2023                         return (EINVAL);
2024
2025                 ssa->sin.sin_addr = mreqs.imr_sourceaddr;
2026
2027                 ifp = inp_lookup_mcast_ifp(inp, &gsa->sin,
2028                     mreqs.imr_interface);
2029                 CTR3(KTR_IGMPV3, "%s: imr_interface = 0x%08x, ifp = %p",
2030                     __func__, ntohl(mreqs.imr_interface.s_addr), ifp);
2031                 break;
2032         }
2033
2034         case MCAST_JOIN_GROUP:
2035         case MCAST_JOIN_SOURCE_GROUP:
2036                 if (sopt->sopt_name == MCAST_JOIN_GROUP) {
2037                         error = sooptcopyin(sopt, &gsr,
2038                             sizeof(struct group_req),
2039                             sizeof(struct group_req));
2040                 } else if (sopt->sopt_name == MCAST_JOIN_SOURCE_GROUP) {
2041                         error = sooptcopyin(sopt, &gsr,
2042                             sizeof(struct group_source_req),
2043                             sizeof(struct group_source_req));
2044                 }
2045                 if (error)
2046                         return (error);
2047
2048                 if (gsa->sin.sin_family != AF_INET ||
2049                     gsa->sin.sin_len != sizeof(struct sockaddr_in))
2050                         return (EINVAL);
2051
2052                 /*
2053                  * Overwrite the port field if present, as the sockaddr
2054                  * being copied in may be matched with a binary comparison.
2055                  */
2056                 gsa->sin.sin_port = 0;
2057                 if (sopt->sopt_name == MCAST_JOIN_SOURCE_GROUP) {
2058                         if (ssa->sin.sin_family != AF_INET ||
2059                             ssa->sin.sin_len != sizeof(struct sockaddr_in))
2060                                 return (EINVAL);
2061                         ssa->sin.sin_port = 0;
2062                 }
2063
2064                 if (!IN_MULTICAST(ntohl(gsa->sin.sin_addr.s_addr)))
2065                         return (EINVAL);
2066
2067                 if (gsr.gsr_interface == 0 || V_if_index < gsr.gsr_interface)
2068                         return (EADDRNOTAVAIL);
2069                 ifp = ifnet_byindex(gsr.gsr_interface);
2070                 break;
2071
2072         default:
2073                 CTR2(KTR_IGMPV3, "%s: unknown sopt_name %d",
2074                     __func__, sopt->sopt_name);
2075                 return (EOPNOTSUPP);
2076                 break;
2077         }
2078
2079         if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0)
2080                 return (EADDRNOTAVAIL);
2081
2082         IN_MULTI_LOCK();
2083
2084         /*
2085          * Find the membership in the membership list.
2086          */
2087         imo = inp_findmoptions(inp);
2088         imf = imo_match_group(imo, ifp, &gsa->sa);
2089         if (imf == NULL) {
2090                 is_new = 1;
2091                 inm = NULL;
2092
2093                 if (ip_mfilter_count(&imo->imo_head) >= IP_MAX_MEMBERSHIPS) {
2094                         error = ENOMEM;
2095                         goto out_inp_locked;
2096                 }
2097         } else {
2098                 is_new = 0;
2099                 inm = imf->imf_inm;
2100
2101                 if (ssa->ss.ss_family != AF_UNSPEC) {
2102                         /*
2103                          * MCAST_JOIN_SOURCE_GROUP on an exclusive membership
2104                          * is an error. On an existing inclusive membership,
2105                          * it just adds the source to the filter list.
2106                          */
2107                         if (imf->imf_st[1] != MCAST_INCLUDE) {
2108                                 error = EINVAL;
2109                                 goto out_inp_locked;
2110                         }
2111                         /*
2112                          * Throw out duplicates.
2113                          *
2114                          * XXX FIXME: This makes a naive assumption that
2115                          * even if entries exist for *ssa in this imf,
2116                          * they will be rejected as dupes, even if they
2117                          * are not valid in the current mode (in-mode).
2118                          *
2119                          * in_msource is transactioned just as for anything
2120                          * else in SSM -- but note naive use of inm_graft()
2121                          * below for allocating new filter entries.
2122                          *
2123                          * This is only an issue if someone mixes the
2124                          * full-state SSM API with the delta-based API,
2125                          * which is discouraged in the relevant RFCs.
2126                          */
2127                         lims = imo_match_source(imf, &ssa->sa);
2128                         if (lims != NULL /*&&
2129                             lims->imsl_st[1] == MCAST_INCLUDE*/) {
2130                                 error = EADDRNOTAVAIL;
2131                                 goto out_inp_locked;
2132                         }
2133                 } else {
2134                         /*
2135                          * MCAST_JOIN_GROUP on an existing exclusive
2136                          * membership is an error; return EADDRINUSE
2137                          * to preserve 4.4BSD API idempotence, and
2138                          * avoid tedious detour to code below.
2139                          * NOTE: This is bending RFC 3678 a bit.
2140                          *
2141                          * On an existing inclusive membership, this is also
2142                          * an error; if you want to change filter mode,
2143                          * you must use the userland API setsourcefilter().
2144                          * XXX We don't reject this for imf in UNDEFINED
2145                          * state at t1, because allocation of a filter
2146                          * is atomic with allocation of a membership.
2147                          */
2148                         error = EINVAL;
2149                         if (imf->imf_st[1] == MCAST_EXCLUDE)
2150                                 error = EADDRINUSE;
2151                         goto out_inp_locked;
2152                 }
2153         }
2154
2155         /*
2156          * Begin state merge transaction at socket layer.
2157          */
2158         INP_WLOCK_ASSERT(inp);
2159
2160         /*
2161          * Graft new source into filter list for this inpcb's
2162          * membership of the group. The in_multi may not have
2163          * been allocated yet if this is a new membership, however,
2164          * the in_mfilter slot will be allocated and must be initialized.
2165          *
2166          * Note: Grafting of exclusive mode filters doesn't happen
2167          * in this path.
2168          * XXX: Should check for non-NULL lims (node exists but may
2169          * not be in-mode) for interop with full-state API.
2170          */
2171         if (ssa->ss.ss_family != AF_UNSPEC) {
2172                 /* Membership starts in IN mode */
2173                 if (is_new) {
2174                         CTR1(KTR_IGMPV3, "%s: new join w/source", __func__);
2175                         imf = ip_mfilter_alloc(M_NOWAIT, MCAST_UNDEFINED, MCAST_INCLUDE);
2176                         if (imf == NULL) {
2177                                 error = ENOMEM;
2178                                 goto out_inp_locked;
2179                         }
2180                 } else {
2181                         CTR2(KTR_IGMPV3, "%s: %s source", __func__, "allow");
2182                 }
2183                 lims = imf_graft(imf, MCAST_INCLUDE, &ssa->sin);
2184                 if (lims == NULL) {
2185                         CTR1(KTR_IGMPV3, "%s: merge imf state failed",
2186                             __func__);
2187                         error = ENOMEM;
2188                         goto out_inp_locked;
2189                 }
2190         } else {
2191                 /* No address specified; Membership starts in EX mode */
2192                 if (is_new) {
2193                         CTR1(KTR_IGMPV3, "%s: new join w/o source", __func__);
2194                         imf = ip_mfilter_alloc(M_NOWAIT, MCAST_UNDEFINED, MCAST_EXCLUDE);
2195                         if (imf == NULL) {
2196                                 error = ENOMEM;
2197                                 goto out_inp_locked;
2198                         }
2199                 }
2200         }
2201
2202         /*
2203          * Begin state merge transaction at IGMP layer.
2204          */
2205         if (is_new) {
2206                 in_pcbref(inp);
2207                 INP_WUNLOCK(inp);
2208
2209                 error = in_joingroup_locked(ifp, &gsa->sin.sin_addr, imf,
2210                     &imf->imf_inm);
2211
2212                 INP_WLOCK(inp);
2213                 if (in_pcbrele_wlocked(inp)) {
2214                         error = ENXIO;
2215                         goto out_inp_unlocked;
2216                 }
2217                 if (error) {
2218                         CTR1(KTR_IGMPV3, "%s: in_joingroup_locked failed",
2219                             __func__);
2220                         goto out_inp_locked;
2221                 }
2222                 /*
2223                  * NOTE: Refcount from in_joingroup_locked()
2224                  * is protecting membership.
2225                  */
2226                 ip_mfilter_insert(&imo->imo_head, imf);
2227         } else {
2228                 CTR1(KTR_IGMPV3, "%s: merge inm state", __func__);
2229                 IN_MULTI_LIST_LOCK();
2230                 error = inm_merge(inm, imf);
2231                 if (error) {
2232                         CTR1(KTR_IGMPV3, "%s: failed to merge inm state",
2233                                  __func__);
2234                         IN_MULTI_LIST_UNLOCK();
2235                         imf_rollback(imf);
2236                         imf_reap(imf);
2237                         goto out_inp_locked;
2238                 }
2239                 CTR1(KTR_IGMPV3, "%s: doing igmp downcall", __func__);
2240                 error = igmp_change_state(inm);
2241                 IN_MULTI_LIST_UNLOCK();
2242                 if (error) {
2243                         CTR1(KTR_IGMPV3, "%s: failed igmp downcall",
2244                             __func__);
2245                         imf_rollback(imf);
2246                         imf_reap(imf);
2247                         goto out_inp_locked;
2248                 }
2249         }
2250
2251         imf_commit(imf);
2252         imf = NULL;
2253
2254 out_inp_locked:
2255         INP_WUNLOCK(inp);
2256 out_inp_unlocked:
2257         IN_MULTI_UNLOCK();
2258
2259         if (is_new && imf) {
2260                 if (imf->imf_inm != NULL) {
2261                         IN_MULTI_LIST_LOCK();
2262                         IF_ADDR_WLOCK(ifp);
2263                         inm_release_deferred(imf->imf_inm);
2264                         IF_ADDR_WUNLOCK(ifp);
2265                         IN_MULTI_LIST_UNLOCK();
2266                 }
2267                 ip_mfilter_free(imf);
2268         }
2269         return (error);
2270 }
2271
2272 /*
2273  * Leave an IPv4 multicast group on an inpcb, possibly with a source.
2274  */
2275 static int
2276 inp_leave_group(struct inpcb *inp, struct sockopt *sopt)
2277 {
2278         struct group_source_req          gsr;
2279         struct ip_mreq_source            mreqs;
2280         struct rm_priotracker            in_ifa_tracker;
2281         sockunion_t                     *gsa, *ssa;
2282         struct ifnet                    *ifp;
2283         struct in_mfilter               *imf;
2284         struct ip_moptions              *imo;
2285         struct in_msource               *ims;
2286         struct in_multi                 *inm;
2287         int                              error;
2288         bool                             is_final;
2289
2290         ifp = NULL;
2291         error = 0;
2292         is_final = true;
2293
2294         memset(&gsr, 0, sizeof(struct group_source_req));
2295         gsa = (sockunion_t *)&gsr.gsr_group;
2296         gsa->ss.ss_family = AF_UNSPEC;
2297         ssa = (sockunion_t *)&gsr.gsr_source;
2298         ssa->ss.ss_family = AF_UNSPEC;
2299
2300         switch (sopt->sopt_name) {
2301         case IP_DROP_MEMBERSHIP:
2302         case IP_DROP_SOURCE_MEMBERSHIP:
2303                 if (sopt->sopt_name == IP_DROP_MEMBERSHIP) {
2304                         error = sooptcopyin(sopt, &mreqs,
2305                             sizeof(struct ip_mreq),
2306                             sizeof(struct ip_mreq));
2307                         /*
2308                          * Swap interface and sourceaddr arguments,
2309                          * as ip_mreq and ip_mreq_source are laid
2310                          * out differently.
2311                          */
2312                         mreqs.imr_interface = mreqs.imr_sourceaddr;
2313                         mreqs.imr_sourceaddr.s_addr = INADDR_ANY;
2314                 } else if (sopt->sopt_name == IP_DROP_SOURCE_MEMBERSHIP) {
2315                         error = sooptcopyin(sopt, &mreqs,
2316                             sizeof(struct ip_mreq_source),
2317                             sizeof(struct ip_mreq_source));
2318                 }
2319                 if (error)
2320                         return (error);
2321
2322                 gsa->sin.sin_family = AF_INET;
2323                 gsa->sin.sin_len = sizeof(struct sockaddr_in);
2324                 gsa->sin.sin_addr = mreqs.imr_multiaddr;
2325
2326                 if (sopt->sopt_name == IP_DROP_SOURCE_MEMBERSHIP) {
2327                         ssa->sin.sin_family = AF_INET;
2328                         ssa->sin.sin_len = sizeof(struct sockaddr_in);
2329                         ssa->sin.sin_addr = mreqs.imr_sourceaddr;
2330                 }
2331
2332                 /*
2333                  * Attempt to look up hinted ifp from interface address.
2334                  * Fallthrough with null ifp iff lookup fails, to
2335                  * preserve 4.4BSD mcast API idempotence.
2336                  * XXX NOTE WELL: The RFC 3678 API is preferred because
2337                  * using an IPv4 address as a key is racy.
2338                  */
2339                 if (!in_nullhost(mreqs.imr_interface)) {
2340                         IN_IFADDR_RLOCK(&in_ifa_tracker);
2341                         INADDR_TO_IFP(mreqs.imr_interface, ifp);
2342                         IN_IFADDR_RUNLOCK(&in_ifa_tracker);
2343                 }
2344                 CTR3(KTR_IGMPV3, "%s: imr_interface = 0x%08x, ifp = %p",
2345                     __func__, ntohl(mreqs.imr_interface.s_addr), ifp);
2346
2347                 break;
2348
2349         case MCAST_LEAVE_GROUP:
2350         case MCAST_LEAVE_SOURCE_GROUP:
2351                 if (sopt->sopt_name == MCAST_LEAVE_GROUP) {
2352                         error = sooptcopyin(sopt, &gsr,
2353                             sizeof(struct group_req),
2354                             sizeof(struct group_req));
2355                 } else if (sopt->sopt_name == MCAST_LEAVE_SOURCE_GROUP) {
2356                         error = sooptcopyin(sopt, &gsr,
2357                             sizeof(struct group_source_req),
2358                             sizeof(struct group_source_req));
2359                 }
2360                 if (error)
2361                         return (error);
2362
2363                 if (gsa->sin.sin_family != AF_INET ||
2364                     gsa->sin.sin_len != sizeof(struct sockaddr_in))
2365                         return (EINVAL);
2366
2367                 if (sopt->sopt_name == MCAST_LEAVE_SOURCE_GROUP) {
2368                         if (ssa->sin.sin_family != AF_INET ||
2369                             ssa->sin.sin_len != sizeof(struct sockaddr_in))
2370                                 return (EINVAL);
2371                 }
2372
2373                 if (gsr.gsr_interface == 0 || V_if_index < gsr.gsr_interface)
2374                         return (EADDRNOTAVAIL);
2375
2376                 ifp = ifnet_byindex(gsr.gsr_interface);
2377
2378                 if (ifp == NULL)
2379                         return (EADDRNOTAVAIL);
2380                 break;
2381
2382         default:
2383                 CTR2(KTR_IGMPV3, "%s: unknown sopt_name %d",
2384                     __func__, sopt->sopt_name);
2385                 return (EOPNOTSUPP);
2386                 break;
2387         }
2388
2389         if (!IN_MULTICAST(ntohl(gsa->sin.sin_addr.s_addr)))
2390                 return (EINVAL);
2391
2392         IN_MULTI_LOCK();
2393
2394         /*
2395          * Find the membership in the membership list.
2396          */
2397         imo = inp_findmoptions(inp);
2398         imf = imo_match_group(imo, ifp, &gsa->sa);
2399         if (imf == NULL) {
2400                 error = EADDRNOTAVAIL;
2401                 goto out_inp_locked;
2402         }
2403         inm = imf->imf_inm;
2404
2405         if (ssa->ss.ss_family != AF_UNSPEC)
2406                 is_final = false;
2407
2408         /*
2409          * Begin state merge transaction at socket layer.
2410          */
2411         INP_WLOCK_ASSERT(inp);
2412
2413         /*
2414          * If we were instructed only to leave a given source, do so.
2415          * MCAST_LEAVE_SOURCE_GROUP is only valid for inclusive memberships.
2416          */
2417         if (is_final) {
2418                 ip_mfilter_remove(&imo->imo_head, imf);
2419                 imf_leave(imf);
2420
2421                 /*
2422                  * Give up the multicast address record to which
2423                  * the membership points.
2424                  */
2425                 (void) in_leavegroup_locked(imf->imf_inm, imf);
2426         } else {
2427                 if (imf->imf_st[0] == MCAST_EXCLUDE) {
2428                         error = EADDRNOTAVAIL;
2429                         goto out_inp_locked;
2430                 }
2431                 ims = imo_match_source(imf, &ssa->sa);
2432                 if (ims == NULL) {
2433                         CTR3(KTR_IGMPV3, "%s: source 0x%08x %spresent",
2434                             __func__, ntohl(ssa->sin.sin_addr.s_addr), "not ");
2435                         error = EADDRNOTAVAIL;
2436                         goto out_inp_locked;
2437                 }
2438                 CTR2(KTR_IGMPV3, "%s: %s source", __func__, "block");
2439                 error = imf_prune(imf, &ssa->sin);
2440                 if (error) {
2441                         CTR1(KTR_IGMPV3, "%s: merge imf state failed",
2442                             __func__);
2443                         goto out_inp_locked;
2444                 }
2445         }
2446
2447         /*
2448          * Begin state merge transaction at IGMP layer.
2449          */
2450         if (!is_final) {
2451                 CTR1(KTR_IGMPV3, "%s: merge inm state", __func__);
2452                 IN_MULTI_LIST_LOCK();
2453                 error = inm_merge(inm, imf);
2454                 if (error) {
2455                         CTR1(KTR_IGMPV3, "%s: failed to merge inm state",
2456                             __func__);
2457                         IN_MULTI_LIST_UNLOCK();
2458                         imf_rollback(imf);
2459                         imf_reap(imf);
2460                         goto out_inp_locked;
2461                 }
2462
2463                 CTR1(KTR_IGMPV3, "%s: doing igmp downcall", __func__);
2464                 error = igmp_change_state(inm);
2465                 IN_MULTI_LIST_UNLOCK();
2466                 if (error) {
2467                         CTR1(KTR_IGMPV3, "%s: failed igmp downcall",
2468                             __func__);
2469                         imf_rollback(imf);
2470                         imf_reap(imf);
2471                         goto out_inp_locked;
2472                 }
2473         }
2474         imf_commit(imf);
2475         imf_reap(imf);
2476
2477 out_inp_locked:
2478         INP_WUNLOCK(inp);
2479
2480         if (is_final && imf)
2481                 ip_mfilter_free(imf);
2482
2483         IN_MULTI_UNLOCK();
2484         return (error);
2485 }
2486
2487 /*
2488  * Select the interface for transmitting IPv4 multicast datagrams.
2489  *
2490  * Either an instance of struct in_addr or an instance of struct ip_mreqn
2491  * may be passed to this socket option. An address of INADDR_ANY or an
2492  * interface index of 0 is used to remove a previous selection.
2493  * When no interface is selected, one is chosen for every send.
2494  */
2495 static int
2496 inp_set_multicast_if(struct inpcb *inp, struct sockopt *sopt)
2497 {
2498         struct rm_priotracker    in_ifa_tracker;
2499         struct in_addr           addr;
2500         struct ip_mreqn          mreqn;
2501         struct ifnet            *ifp;
2502         struct ip_moptions      *imo;
2503         int                      error;
2504
2505         if (sopt->sopt_valsize == sizeof(struct ip_mreqn)) {
2506                 /*
2507                  * An interface index was specified using the
2508                  * Linux-derived ip_mreqn structure.
2509                  */
2510                 error = sooptcopyin(sopt, &mreqn, sizeof(struct ip_mreqn),
2511                     sizeof(struct ip_mreqn));
2512                 if (error)
2513                         return (error);
2514
2515                 if (mreqn.imr_ifindex < 0 || V_if_index < mreqn.imr_ifindex)
2516                         return (EINVAL);
2517
2518                 if (mreqn.imr_ifindex == 0) {
2519                         ifp = NULL;
2520                 } else {
2521                         ifp = ifnet_byindex(mreqn.imr_ifindex);
2522                         if (ifp == NULL)
2523                                 return (EADDRNOTAVAIL);
2524                 }
2525         } else {
2526                 /*
2527                  * An interface was specified by IPv4 address.
2528                  * This is the traditional BSD usage.
2529                  */
2530                 error = sooptcopyin(sopt, &addr, sizeof(struct in_addr),
2531                     sizeof(struct in_addr));
2532                 if (error)
2533                         return (error);
2534                 if (in_nullhost(addr)) {
2535                         ifp = NULL;
2536                 } else {
2537                         IN_IFADDR_RLOCK(&in_ifa_tracker);
2538                         INADDR_TO_IFP(addr, ifp);
2539                         IN_IFADDR_RUNLOCK(&in_ifa_tracker);
2540                         if (ifp == NULL)
2541                                 return (EADDRNOTAVAIL);
2542                 }
2543                 CTR3(KTR_IGMPV3, "%s: ifp = %p, addr = 0x%08x", __func__, ifp,
2544                     ntohl(addr.s_addr));
2545         }
2546
2547         /* Reject interfaces which do not support multicast. */
2548         if (ifp != NULL && (ifp->if_flags & IFF_MULTICAST) == 0)
2549                 return (EOPNOTSUPP);
2550
2551         imo = inp_findmoptions(inp);
2552         imo->imo_multicast_ifp = ifp;
2553         imo->imo_multicast_addr.s_addr = INADDR_ANY;
2554         INP_WUNLOCK(inp);
2555
2556         return (0);
2557 }
2558
2559 /*
2560  * Atomically set source filters on a socket for an IPv4 multicast group.
2561  *
2562  * SMPng: NOTE: Potentially calls malloc(M_WAITOK) with Giant held.
2563  */
2564 static int
2565 inp_set_source_filters(struct inpcb *inp, struct sockopt *sopt)
2566 {
2567         struct __msfilterreq     msfr;
2568         sockunion_t             *gsa;
2569         struct ifnet            *ifp;
2570         struct in_mfilter       *imf;
2571         struct ip_moptions      *imo;
2572         struct in_multi         *inm;
2573         int                      error;
2574
2575         error = sooptcopyin(sopt, &msfr, sizeof(struct __msfilterreq),
2576             sizeof(struct __msfilterreq));
2577         if (error)
2578                 return (error);
2579
2580         if (msfr.msfr_nsrcs > in_mcast_maxsocksrc)
2581                 return (ENOBUFS);
2582
2583         if ((msfr.msfr_fmode != MCAST_EXCLUDE &&
2584              msfr.msfr_fmode != MCAST_INCLUDE))
2585                 return (EINVAL);
2586
2587         if (msfr.msfr_group.ss_family != AF_INET ||
2588             msfr.msfr_group.ss_len != sizeof(struct sockaddr_in))
2589                 return (EINVAL);
2590
2591         gsa = (sockunion_t *)&msfr.msfr_group;
2592         if (!IN_MULTICAST(ntohl(gsa->sin.sin_addr.s_addr)))
2593                 return (EINVAL);
2594
2595         gsa->sin.sin_port = 0;  /* ignore port */
2596
2597         if (msfr.msfr_ifindex == 0 || V_if_index < msfr.msfr_ifindex)
2598                 return (EADDRNOTAVAIL);
2599
2600         ifp = ifnet_byindex(msfr.msfr_ifindex);
2601         if (ifp == NULL)
2602                 return (EADDRNOTAVAIL);
2603
2604         IN_MULTI_LOCK();
2605
2606         /*
2607          * Take the INP write lock.
2608          * Check if this socket is a member of this group.
2609          */
2610         imo = inp_findmoptions(inp);
2611         imf = imo_match_group(imo, ifp, &gsa->sa);
2612         if (imf == NULL) {
2613                 error = EADDRNOTAVAIL;
2614                 goto out_inp_locked;
2615         }
2616         inm = imf->imf_inm;
2617
2618         /*
2619          * Begin state merge transaction at socket layer.
2620          */
2621         INP_WLOCK_ASSERT(inp);
2622
2623         imf->imf_st[1] = msfr.msfr_fmode;
2624
2625         /*
2626          * Apply any new source filters, if present.
2627          * Make a copy of the user-space source vector so
2628          * that we may copy them with a single copyin. This
2629          * allows us to deal with page faults up-front.
2630          */
2631         if (msfr.msfr_nsrcs > 0) {
2632                 struct in_msource       *lims;
2633                 struct sockaddr_in      *psin;
2634                 struct sockaddr_storage *kss, *pkss;
2635                 int                      i;
2636
2637                 INP_WUNLOCK(inp);
2638
2639                 CTR2(KTR_IGMPV3, "%s: loading %lu source list entries",
2640                     __func__, (unsigned long)msfr.msfr_nsrcs);
2641                 kss = malloc(sizeof(struct sockaddr_storage) * msfr.msfr_nsrcs,
2642                     M_TEMP, M_WAITOK);
2643                 error = copyin(msfr.msfr_srcs, kss,
2644                     sizeof(struct sockaddr_storage) * msfr.msfr_nsrcs);
2645                 if (error) {
2646                         free(kss, M_TEMP);
2647                         return (error);
2648                 }
2649
2650                 INP_WLOCK(inp);
2651
2652                 /*
2653                  * Mark all source filters as UNDEFINED at t1.
2654                  * Restore new group filter mode, as imf_leave()
2655                  * will set it to INCLUDE.
2656                  */
2657                 imf_leave(imf);
2658                 imf->imf_st[1] = msfr.msfr_fmode;
2659
2660                 /*
2661                  * Update socket layer filters at t1, lazy-allocating
2662                  * new entries. This saves a bunch of memory at the
2663                  * cost of one RB_FIND() per source entry; duplicate
2664                  * entries in the msfr_nsrcs vector are ignored.
2665                  * If we encounter an error, rollback transaction.
2666                  *
2667                  * XXX This too could be replaced with a set-symmetric
2668                  * difference like loop to avoid walking from root
2669                  * every time, as the key space is common.
2670                  */
2671                 for (i = 0, pkss = kss; i < msfr.msfr_nsrcs; i++, pkss++) {
2672                         psin = (struct sockaddr_in *)pkss;
2673                         if (psin->sin_family != AF_INET) {
2674                                 error = EAFNOSUPPORT;
2675                                 break;
2676                         }
2677                         if (psin->sin_len != sizeof(struct sockaddr_in)) {
2678                                 error = EINVAL;
2679                                 break;
2680                         }
2681                         error = imf_get_source(imf, psin, &lims);
2682                         if (error)
2683                                 break;
2684                         lims->imsl_st[1] = imf->imf_st[1];
2685                 }
2686                 free(kss, M_TEMP);
2687         }
2688
2689         if (error)
2690                 goto out_imf_rollback;
2691
2692         INP_WLOCK_ASSERT(inp);
2693
2694         /*
2695          * Begin state merge transaction at IGMP layer.
2696          */
2697         CTR1(KTR_IGMPV3, "%s: merge inm state", __func__);
2698         IN_MULTI_LIST_LOCK();
2699         error = inm_merge(inm, imf);
2700         if (error) {
2701                 CTR1(KTR_IGMPV3, "%s: failed to merge inm state", __func__);
2702                 IN_MULTI_LIST_UNLOCK();
2703                 goto out_imf_rollback;
2704         }
2705
2706         CTR1(KTR_IGMPV3, "%s: doing igmp downcall", __func__);
2707         error = igmp_change_state(inm);
2708         IN_MULTI_LIST_UNLOCK();
2709         if (error)
2710                 CTR1(KTR_IGMPV3, "%s: failed igmp downcall", __func__);
2711
2712 out_imf_rollback:
2713         if (error)
2714                 imf_rollback(imf);
2715         else
2716                 imf_commit(imf);
2717
2718         imf_reap(imf);
2719
2720 out_inp_locked:
2721         INP_WUNLOCK(inp);
2722         IN_MULTI_UNLOCK();
2723         return (error);
2724 }
2725
2726 /*
2727  * Set the IP multicast options in response to user setsockopt().
2728  *
2729  * Many of the socket options handled in this function duplicate the
2730  * functionality of socket options in the regular unicast API. However,
2731  * it is not possible to merge the duplicate code, because the idempotence
2732  * of the IPv4 multicast part of the BSD Sockets API must be preserved;
2733  * the effects of these options must be treated as separate and distinct.
2734  *
2735  * SMPng: XXX: Unlocked read of inp_socket believed OK.
2736  * FUTURE: The IP_MULTICAST_VIF option may be eliminated if MROUTING
2737  * is refactored to no longer use vifs.
2738  */
2739 int
2740 inp_setmoptions(struct inpcb *inp, struct sockopt *sopt)
2741 {
2742         struct ip_moptions      *imo;
2743         int                      error;
2744         struct epoch_tracker    et;
2745
2746         error = 0;
2747
2748         /*
2749          * If socket is neither of type SOCK_RAW or SOCK_DGRAM,
2750          * or is a divert socket, reject it.
2751          */
2752         if (inp->inp_socket->so_proto->pr_protocol == IPPROTO_DIVERT ||
2753             (inp->inp_socket->so_proto->pr_type != SOCK_RAW &&
2754              inp->inp_socket->so_proto->pr_type != SOCK_DGRAM))
2755                 return (EOPNOTSUPP);
2756
2757         switch (sopt->sopt_name) {
2758         case IP_MULTICAST_VIF: {
2759                 int vifi;
2760                 /*
2761                  * Select a multicast VIF for transmission.
2762                  * Only useful if multicast forwarding is active.
2763                  */
2764                 if (legal_vif_num == NULL) {
2765                         error = EOPNOTSUPP;
2766                         break;
2767                 }
2768                 error = sooptcopyin(sopt, &vifi, sizeof(int), sizeof(int));
2769                 if (error)
2770                         break;
2771                 if (!legal_vif_num(vifi) && (vifi != -1)) {
2772                         error = EINVAL;
2773                         break;
2774                 }
2775                 imo = inp_findmoptions(inp);
2776                 imo->imo_multicast_vif = vifi;
2777                 INP_WUNLOCK(inp);
2778                 break;
2779         }
2780
2781         case IP_MULTICAST_IF:
2782                 error = inp_set_multicast_if(inp, sopt);
2783                 break;
2784
2785         case IP_MULTICAST_TTL: {
2786                 u_char ttl;
2787
2788                 /*
2789                  * Set the IP time-to-live for outgoing multicast packets.
2790                  * The original multicast API required a char argument,
2791                  * which is inconsistent with the rest of the socket API.
2792                  * We allow either a char or an int.
2793                  */
2794                 if (sopt->sopt_valsize == sizeof(u_char)) {
2795                         error = sooptcopyin(sopt, &ttl, sizeof(u_char),
2796                             sizeof(u_char));
2797                         if (error)
2798                                 break;
2799                 } else {
2800                         u_int ittl;
2801
2802                         error = sooptcopyin(sopt, &ittl, sizeof(u_int),
2803                             sizeof(u_int));
2804                         if (error)
2805                                 break;
2806                         if (ittl > 255) {
2807                                 error = EINVAL;
2808                                 break;
2809                         }
2810                         ttl = (u_char)ittl;
2811                 }
2812                 imo = inp_findmoptions(inp);
2813                 imo->imo_multicast_ttl = ttl;
2814                 INP_WUNLOCK(inp);
2815                 break;
2816         }
2817
2818         case IP_MULTICAST_LOOP: {
2819                 u_char loop;
2820
2821                 /*
2822                  * Set the loopback flag for outgoing multicast packets.
2823                  * Must be zero or one.  The original multicast API required a
2824                  * char argument, which is inconsistent with the rest
2825                  * of the socket API.  We allow either a char or an int.
2826                  */
2827                 if (sopt->sopt_valsize == sizeof(u_char)) {
2828                         error = sooptcopyin(sopt, &loop, sizeof(u_char),
2829                             sizeof(u_char));
2830                         if (error)
2831                                 break;
2832                 } else {
2833                         u_int iloop;
2834
2835                         error = sooptcopyin(sopt, &iloop, sizeof(u_int),
2836                                             sizeof(u_int));
2837                         if (error)
2838                                 break;
2839                         loop = (u_char)iloop;
2840                 }
2841                 imo = inp_findmoptions(inp);
2842                 imo->imo_multicast_loop = !!loop;
2843                 INP_WUNLOCK(inp);
2844                 break;
2845         }
2846
2847         case IP_ADD_MEMBERSHIP:
2848         case IP_ADD_SOURCE_MEMBERSHIP:
2849         case MCAST_JOIN_GROUP:
2850         case MCAST_JOIN_SOURCE_GROUP:
2851                 NET_EPOCH_ENTER(et);
2852                 error = inp_join_group(inp, sopt);
2853                 NET_EPOCH_EXIT(et);
2854                 break;
2855
2856         case IP_DROP_MEMBERSHIP:
2857         case IP_DROP_SOURCE_MEMBERSHIP:
2858         case MCAST_LEAVE_GROUP:
2859         case MCAST_LEAVE_SOURCE_GROUP:
2860                 error = inp_leave_group(inp, sopt);
2861                 break;
2862
2863         case IP_BLOCK_SOURCE:
2864         case IP_UNBLOCK_SOURCE:
2865         case MCAST_BLOCK_SOURCE:
2866         case MCAST_UNBLOCK_SOURCE:
2867                 error = inp_block_unblock_source(inp, sopt);
2868                 break;
2869
2870         case IP_MSFILTER:
2871                 error = inp_set_source_filters(inp, sopt);
2872                 break;
2873
2874         default:
2875                 error = EOPNOTSUPP;
2876                 break;
2877         }
2878
2879         INP_UNLOCK_ASSERT(inp);
2880
2881         return (error);
2882 }
2883
2884 /*
2885  * Expose IGMP's multicast filter mode and source list(s) to userland,
2886  * keyed by (ifindex, group).
2887  * The filter mode is written out as a uint32_t, followed by
2888  * 0..n of struct in_addr.
2889  * For use by ifmcstat(8).
2890  * SMPng: NOTE: unlocked read of ifindex space.
2891  */
2892 static int
2893 sysctl_ip_mcast_filters(SYSCTL_HANDLER_ARGS)
2894 {
2895         struct in_addr                   src, group;
2896         struct epoch_tracker             et;
2897         struct ifnet                    *ifp;
2898         struct ifmultiaddr              *ifma;
2899         struct in_multi                 *inm;
2900         struct ip_msource               *ims;
2901         int                             *name;
2902         int                              retval;
2903         u_int                            namelen;
2904         uint32_t                         fmode, ifindex;
2905
2906         name = (int *)arg1;
2907         namelen = arg2;
2908
2909         if (req->newptr != NULL)
2910                 return (EPERM);
2911
2912         if (namelen != 2)
2913                 return (EINVAL);
2914
2915         ifindex = name[0];
2916         if (ifindex <= 0 || ifindex > V_if_index) {
2917                 CTR2(KTR_IGMPV3, "%s: ifindex %u out of range",
2918                     __func__, ifindex);
2919                 return (ENOENT);
2920         }
2921
2922         group.s_addr = name[1];
2923         if (!IN_MULTICAST(ntohl(group.s_addr))) {
2924                 CTR2(KTR_IGMPV3, "%s: group 0x%08x is not multicast",
2925                     __func__, ntohl(group.s_addr));
2926                 return (EINVAL);
2927         }
2928
2929         NET_EPOCH_ENTER(et);
2930         ifp = ifnet_byindex(ifindex);
2931         if (ifp == NULL) {
2932                 NET_EPOCH_EXIT(et);
2933                 CTR2(KTR_IGMPV3, "%s: no ifp for ifindex %u",
2934                     __func__, ifindex);
2935                 return (ENOENT);
2936         }
2937
2938         retval = sysctl_wire_old_buffer(req,
2939             sizeof(uint32_t) + (in_mcast_maxgrpsrc * sizeof(struct in_addr)));
2940         if (retval) {
2941                 NET_EPOCH_EXIT(et);
2942                 return (retval);
2943         }
2944
2945         IN_MULTI_LIST_LOCK();
2946
2947         CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2948                 if (ifma->ifma_addr->sa_family != AF_INET ||
2949                     ifma->ifma_protospec == NULL)
2950                         continue;
2951                 inm = (struct in_multi *)ifma->ifma_protospec;
2952                 if (!in_hosteq(inm->inm_addr, group))
2953                         continue;
2954                 fmode = inm->inm_st[1].iss_fmode;
2955                 retval = SYSCTL_OUT(req, &fmode, sizeof(uint32_t));
2956                 if (retval != 0)
2957                         break;
2958                 RB_FOREACH(ims, ip_msource_tree, &inm->inm_srcs) {
2959                         CTR2(KTR_IGMPV3, "%s: visit node 0x%08x", __func__,
2960                             ims->ims_haddr);
2961                         /*
2962                          * Only copy-out sources which are in-mode.
2963                          */
2964                         if (fmode != ims_get_mode(inm, ims, 1)) {
2965                                 CTR1(KTR_IGMPV3, "%s: skip non-in-mode",
2966                                     __func__);
2967                                 continue;
2968                         }
2969                         src.s_addr = htonl(ims->ims_haddr);
2970                         retval = SYSCTL_OUT(req, &src, sizeof(struct in_addr));
2971                         if (retval != 0)
2972                                 break;
2973                 }
2974         }
2975
2976         IN_MULTI_LIST_UNLOCK();
2977         NET_EPOCH_EXIT(et);
2978
2979         return (retval);
2980 }
2981
2982 #if defined(KTR) && (KTR_COMPILE & KTR_IGMPV3)
2983
2984 static const char *inm_modestrs[] = {
2985         [MCAST_UNDEFINED] = "un",
2986         [MCAST_INCLUDE] = "in",
2987         [MCAST_EXCLUDE] = "ex",
2988 };
2989 _Static_assert(MCAST_UNDEFINED == 0 &&
2990                MCAST_EXCLUDE + 1 == nitems(inm_modestrs),
2991                "inm_modestrs: no longer matches #defines");
2992
2993 static const char *
2994 inm_mode_str(const int mode)
2995 {
2996
2997         if (mode >= MCAST_UNDEFINED && mode <= MCAST_EXCLUDE)
2998                 return (inm_modestrs[mode]);
2999         return ("??");
3000 }
3001
3002 static const char *inm_statestrs[] = {
3003         [IGMP_NOT_MEMBER] = "not-member",
3004         [IGMP_SILENT_MEMBER] = "silent",
3005         [IGMP_REPORTING_MEMBER] = "reporting",
3006         [IGMP_IDLE_MEMBER] = "idle",
3007         [IGMP_LAZY_MEMBER] = "lazy",
3008         [IGMP_SLEEPING_MEMBER] = "sleeping",
3009         [IGMP_AWAKENING_MEMBER] = "awakening",
3010         [IGMP_G_QUERY_PENDING_MEMBER] = "query-pending",
3011         [IGMP_SG_QUERY_PENDING_MEMBER] = "sg-query-pending",
3012         [IGMP_LEAVING_MEMBER] = "leaving",
3013 };
3014 _Static_assert(IGMP_NOT_MEMBER == 0 &&
3015                IGMP_LEAVING_MEMBER + 1 == nitems(inm_statestrs),
3016                "inm_statetrs: no longer matches #defines");
3017
3018 static const char *
3019 inm_state_str(const int state)
3020 {
3021
3022         if (state >= IGMP_NOT_MEMBER && state <= IGMP_LEAVING_MEMBER)
3023                 return (inm_statestrs[state]);
3024         return ("??");
3025 }
3026
3027 /*
3028  * Dump an in_multi structure to the console.
3029  */
3030 void
3031 inm_print(const struct in_multi *inm)
3032 {
3033         int t;
3034         char addrbuf[INET_ADDRSTRLEN];
3035
3036         if ((ktr_mask & KTR_IGMPV3) == 0)
3037                 return;
3038
3039         printf("%s: --- begin inm %p ---\n", __func__, inm);
3040         printf("addr %s ifp %p(%s) ifma %p\n",
3041             inet_ntoa_r(inm->inm_addr, addrbuf),
3042             inm->inm_ifp,
3043             inm->inm_ifp->if_xname,
3044             inm->inm_ifma);
3045         printf("timer %u state %s refcount %u scq.len %u\n",
3046             inm->inm_timer,
3047             inm_state_str(inm->inm_state),
3048             inm->inm_refcount,
3049             inm->inm_scq.mq_len);
3050         printf("igi %p nsrc %lu sctimer %u scrv %u\n",
3051             inm->inm_igi,
3052             inm->inm_nsrc,
3053             inm->inm_sctimer,
3054             inm->inm_scrv);
3055         for (t = 0; t < 2; t++) {
3056                 printf("t%d: fmode %s asm %u ex %u in %u rec %u\n", t,
3057                     inm_mode_str(inm->inm_st[t].iss_fmode),
3058                     inm->inm_st[t].iss_asm,
3059                     inm->inm_st[t].iss_ex,
3060                     inm->inm_st[t].iss_in,
3061                     inm->inm_st[t].iss_rec);
3062         }
3063         printf("%s: --- end inm %p ---\n", __func__, inm);
3064 }
3065
3066 #else /* !KTR || !(KTR_COMPILE & KTR_IGMPV3) */
3067
3068 void
3069 inm_print(const struct in_multi *inm)
3070 {
3071
3072 }
3073
3074 #endif /* KTR && (KTR_COMPILE & KTR_IGMPV3) */
3075
3076 RB_GENERATE(ip_msource_tree, ip_msource, ims_link, ip_msource_cmp);