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