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