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