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