]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/in_mcast.c
Fix TCP IPv6 SYN cache kernel information disclosure.
[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
1056         /* Increment ASM listener count on transition to ASM mode. */
1057         if (imf->imf_st[1] == MCAST_EXCLUDE && nsrc1 == 0) {
1058                 CTR1(KTR_IGMPV3, "%s: asm++ on inm at t1", __func__);
1059                 inm->inm_st[1].iss_asm++;
1060         }
1061
1062         CTR3(KTR_IGMPV3, "%s: merged imf %p to inm %p", __func__, imf, inm);
1063         inm_print(inm);
1064
1065 out_reap:
1066         if (schanged > 0) {
1067                 CTR1(KTR_IGMPV3, "%s: sources changed; reaping", __func__);
1068                 inm_reap(inm);
1069         }
1070         return (error);
1071 }
1072
1073 /*
1074  * Mark an in_multi's filter set deltas as committed.
1075  * Called by IGMP after a state change has been enqueued.
1076  */
1077 void
1078 inm_commit(struct in_multi *inm)
1079 {
1080         struct ip_msource       *ims;
1081
1082         CTR2(KTR_IGMPV3, "%s: commit inm %p", __func__, inm);
1083         CTR1(KTR_IGMPV3, "%s: pre commit:", __func__);
1084         inm_print(inm);
1085
1086         RB_FOREACH(ims, ip_msource_tree, &inm->inm_srcs) {
1087                 ims->ims_st[0] = ims->ims_st[1];
1088         }
1089         inm->inm_st[0] = inm->inm_st[1];
1090 }
1091
1092 /*
1093  * Reap unreferenced nodes from an in_multi's filter set.
1094  */
1095 static void
1096 inm_reap(struct in_multi *inm)
1097 {
1098         struct ip_msource       *ims, *tims;
1099
1100         RB_FOREACH_SAFE(ims, ip_msource_tree, &inm->inm_srcs, tims) {
1101                 if (ims->ims_st[0].ex > 0 || ims->ims_st[0].in > 0 ||
1102                     ims->ims_st[1].ex > 0 || ims->ims_st[1].in > 0 ||
1103                     ims->ims_stp != 0)
1104                         continue;
1105                 CTR2(KTR_IGMPV3, "%s: free ims %p", __func__, ims);
1106                 RB_REMOVE(ip_msource_tree, &inm->inm_srcs, ims);
1107                 free(ims, M_IPMSOURCE);
1108                 inm->inm_nsrc--;
1109         }
1110 }
1111
1112 /*
1113  * Purge all source nodes from an in_multi's filter set.
1114  */
1115 static void
1116 inm_purge(struct in_multi *inm)
1117 {
1118         struct ip_msource       *ims, *tims;
1119
1120         RB_FOREACH_SAFE(ims, ip_msource_tree, &inm->inm_srcs, tims) {
1121                 CTR2(KTR_IGMPV3, "%s: free ims %p", __func__, ims);
1122                 RB_REMOVE(ip_msource_tree, &inm->inm_srcs, ims);
1123                 free(ims, M_IPMSOURCE);
1124                 inm->inm_nsrc--;
1125         }
1126 }
1127
1128 /*
1129  * Join a multicast group; unlocked entry point.
1130  *
1131  * SMPng: XXX: in_joingroup() is called from in_control() when Giant
1132  * is not held. Fortunately, ifp is unlikely to have been detached
1133  * at this point, so we assume it's OK to recurse.
1134  */
1135 int
1136 in_joingroup(struct ifnet *ifp, const struct in_addr *gina,
1137     /*const*/ struct in_mfilter *imf, struct in_multi **pinm)
1138 {
1139         int error;
1140
1141         IN_MULTI_LOCK();
1142         error = in_joingroup_locked(ifp, gina, imf, pinm);
1143         IN_MULTI_UNLOCK();
1144
1145         return (error);
1146 }
1147
1148 /*
1149  * Join a multicast group; real entry point.
1150  *
1151  * Only preserves atomicity at inm level.
1152  * NOTE: imf argument cannot be const due to sys/tree.h limitations.
1153  *
1154  * If the IGMP downcall fails, the group is not joined, and an error
1155  * code is returned.
1156  */
1157 int
1158 in_joingroup_locked(struct ifnet *ifp, const struct in_addr *gina,
1159     /*const*/ struct in_mfilter *imf, struct in_multi **pinm)
1160 {
1161         struct in_mfilter        timf;
1162         struct in_multi         *inm;
1163         int                      error;
1164
1165         IN_MULTI_LOCK_ASSERT();
1166
1167         CTR4(KTR_IGMPV3, "%s: join 0x%08x on %p(%s))", __func__,
1168             ntohl(gina->s_addr), ifp, ifp->if_xname);
1169
1170         error = 0;
1171         inm = NULL;
1172
1173         /*
1174          * If no imf was specified (i.e. kernel consumer),
1175          * fake one up and assume it is an ASM join.
1176          */
1177         if (imf == NULL) {
1178                 imf_init(&timf, MCAST_UNDEFINED, MCAST_EXCLUDE);
1179                 imf = &timf;
1180         }
1181
1182         error = in_getmulti(ifp, gina, &inm);
1183         if (error) {
1184                 CTR1(KTR_IGMPV3, "%s: in_getmulti() failure", __func__);
1185                 return (error);
1186         }
1187
1188         CTR1(KTR_IGMPV3, "%s: merge inm state", __func__);
1189         error = inm_merge(inm, imf);
1190         if (error) {
1191                 CTR1(KTR_IGMPV3, "%s: failed to merge inm state", __func__);
1192                 goto out_inm_release;
1193         }
1194
1195         CTR1(KTR_IGMPV3, "%s: doing igmp downcall", __func__);
1196         error = igmp_change_state(inm);
1197         if (error) {
1198                 CTR1(KTR_IGMPV3, "%s: failed to update source", __func__);
1199                 goto out_inm_release;
1200         }
1201
1202 out_inm_release:
1203         if (error) {
1204                 CTR2(KTR_IGMPV3, "%s: dropping ref on %p", __func__, inm);
1205                 inm_release_locked(inm);
1206         } else {
1207                 *pinm = inm;
1208         }
1209
1210         return (error);
1211 }
1212
1213 /*
1214  * Leave a multicast group; unlocked entry point.
1215  */
1216 int
1217 in_leavegroup(struct in_multi *inm, /*const*/ struct in_mfilter *imf)
1218 {
1219         int error;
1220
1221         IN_MULTI_LOCK();
1222         error = in_leavegroup_locked(inm, imf);
1223         IN_MULTI_UNLOCK();
1224
1225         return (error);
1226 }
1227
1228 /*
1229  * Leave a multicast group; real entry point.
1230  * All source filters will be expunged.
1231  *
1232  * Only preserves atomicity at inm level.
1233  *
1234  * Holding the write lock for the INP which contains imf
1235  * is highly advisable. We can't assert for it as imf does not
1236  * contain a back-pointer to the owning inp.
1237  *
1238  * Note: This is not the same as inm_release(*) as this function also
1239  * makes a state change downcall into IGMP.
1240  */
1241 int
1242 in_leavegroup_locked(struct in_multi *inm, /*const*/ struct in_mfilter *imf)
1243 {
1244         struct in_mfilter        timf;
1245         int                      error;
1246
1247         error = 0;
1248
1249         IN_MULTI_LOCK_ASSERT();
1250
1251         CTR5(KTR_IGMPV3, "%s: leave inm %p, 0x%08x/%s, imf %p", __func__,
1252             inm, ntohl(inm->inm_addr.s_addr),
1253             (inm_is_ifp_detached(inm) ? "null" : inm->inm_ifp->if_xname),
1254             imf);
1255
1256         /*
1257          * If no imf was specified (i.e. kernel consumer),
1258          * fake one up and assume it is an ASM join.
1259          */
1260         if (imf == NULL) {
1261                 imf_init(&timf, MCAST_EXCLUDE, MCAST_UNDEFINED);
1262                 imf = &timf;
1263         }
1264
1265         /*
1266          * Begin state merge transaction at IGMP layer.
1267          *
1268          * As this particular invocation should not cause any memory
1269          * to be allocated, and there is no opportunity to roll back
1270          * the transaction, it MUST NOT fail.
1271          */
1272         CTR1(KTR_IGMPV3, "%s: merge inm state", __func__);
1273         error = inm_merge(inm, imf);
1274         KASSERT(error == 0, ("%s: failed to merge inm state", __func__));
1275
1276         CTR1(KTR_IGMPV3, "%s: doing igmp downcall", __func__);
1277         CURVNET_SET(inm->inm_ifp->if_vnet);
1278         error = igmp_change_state(inm);
1279         CURVNET_RESTORE();
1280         if (error)
1281                 CTR1(KTR_IGMPV3, "%s: failed igmp downcall", __func__);
1282
1283         CTR2(KTR_IGMPV3, "%s: dropping ref on %p", __func__, inm);
1284         inm_release_locked(inm);
1285
1286         return (error);
1287 }
1288
1289 /*#ifndef BURN_BRIDGES*/
1290 /*
1291  * Join an IPv4 multicast group in (*,G) exclusive mode.
1292  * The group must be a 224.0.0.0/24 link-scope group.
1293  * This KPI is for legacy kernel consumers only.
1294  */
1295 struct in_multi *
1296 in_addmulti(struct in_addr *ap, struct ifnet *ifp)
1297 {
1298         struct in_multi *pinm;
1299         int error;
1300 #ifdef INVARIANTS
1301         char addrbuf[INET_ADDRSTRLEN];
1302 #endif
1303
1304         KASSERT(IN_LOCAL_GROUP(ntohl(ap->s_addr)),
1305             ("%s: %s not in 224.0.0.0/24", __func__,
1306             inet_ntoa_r(*ap, addrbuf)));
1307
1308         error = in_joingroup(ifp, ap, NULL, &pinm);
1309         if (error != 0)
1310                 pinm = NULL;
1311
1312         return (pinm);
1313 }
1314
1315 /*
1316  * Leave an IPv4 multicast group, assumed to be in exclusive (*,G) mode.
1317  * This KPI is for legacy kernel consumers only.
1318  */
1319 void
1320 in_delmulti(struct in_multi *inm)
1321 {
1322
1323         (void)in_leavegroup(inm, NULL);
1324 }
1325 /*#endif*/
1326
1327 /*
1328  * Block or unblock an ASM multicast source on an inpcb.
1329  * This implements the delta-based API described in RFC 3678.
1330  *
1331  * The delta-based API applies only to exclusive-mode memberships.
1332  * An IGMP downcall will be performed.
1333  *
1334  * SMPng: NOTE: Must take Giant as a join may create a new ifma.
1335  *
1336  * Return 0 if successful, otherwise return an appropriate error code.
1337  */
1338 static int
1339 inp_block_unblock_source(struct inpcb *inp, struct sockopt *sopt)
1340 {
1341         struct group_source_req          gsr;
1342         struct rm_priotracker            in_ifa_tracker;
1343         sockunion_t                     *gsa, *ssa;
1344         struct ifnet                    *ifp;
1345         struct in_mfilter               *imf;
1346         struct ip_moptions              *imo;
1347         struct in_msource               *ims;
1348         struct in_multi                 *inm;
1349         size_t                           idx;
1350         uint16_t                         fmode;
1351         int                              error, doblock;
1352
1353         ifp = NULL;
1354         error = 0;
1355         doblock = 0;
1356
1357         memset(&gsr, 0, sizeof(struct group_source_req));
1358         gsa = (sockunion_t *)&gsr.gsr_group;
1359         ssa = (sockunion_t *)&gsr.gsr_source;
1360
1361         switch (sopt->sopt_name) {
1362         case IP_BLOCK_SOURCE:
1363         case IP_UNBLOCK_SOURCE: {
1364                 struct ip_mreq_source    mreqs;
1365
1366                 error = sooptcopyin(sopt, &mreqs,
1367                     sizeof(struct ip_mreq_source),
1368                     sizeof(struct ip_mreq_source));
1369                 if (error)
1370                         return (error);
1371
1372                 gsa->sin.sin_family = AF_INET;
1373                 gsa->sin.sin_len = sizeof(struct sockaddr_in);
1374                 gsa->sin.sin_addr = mreqs.imr_multiaddr;
1375
1376                 ssa->sin.sin_family = AF_INET;
1377                 ssa->sin.sin_len = sizeof(struct sockaddr_in);
1378                 ssa->sin.sin_addr = mreqs.imr_sourceaddr;
1379
1380                 if (!in_nullhost(mreqs.imr_interface)) {
1381                         IN_IFADDR_RLOCK(&in_ifa_tracker);
1382                         INADDR_TO_IFP(mreqs.imr_interface, ifp);
1383                         IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1384                 }
1385                 if (sopt->sopt_name == IP_BLOCK_SOURCE)
1386                         doblock = 1;
1387
1388                 CTR3(KTR_IGMPV3, "%s: imr_interface = 0x%08x, ifp = %p",
1389                     __func__, ntohl(mreqs.imr_interface.s_addr), ifp);
1390                 break;
1391             }
1392
1393         case MCAST_BLOCK_SOURCE:
1394         case MCAST_UNBLOCK_SOURCE:
1395                 error = sooptcopyin(sopt, &gsr,
1396                     sizeof(struct group_source_req),
1397                     sizeof(struct group_source_req));
1398                 if (error)
1399                         return (error);
1400
1401                 if (gsa->sin.sin_family != AF_INET ||
1402                     gsa->sin.sin_len != sizeof(struct sockaddr_in))
1403                         return (EINVAL);
1404
1405                 if (ssa->sin.sin_family != AF_INET ||
1406                     ssa->sin.sin_len != sizeof(struct sockaddr_in))
1407                         return (EINVAL);
1408
1409                 if (gsr.gsr_interface == 0 || V_if_index < gsr.gsr_interface)
1410                         return (EADDRNOTAVAIL);
1411
1412                 ifp = ifnet_byindex(gsr.gsr_interface);
1413
1414                 if (sopt->sopt_name == MCAST_BLOCK_SOURCE)
1415                         doblock = 1;
1416                 break;
1417
1418         default:
1419                 CTR2(KTR_IGMPV3, "%s: unknown sopt_name %d",
1420                     __func__, sopt->sopt_name);
1421                 return (EOPNOTSUPP);
1422                 break;
1423         }
1424
1425         if (!IN_MULTICAST(ntohl(gsa->sin.sin_addr.s_addr)))
1426                 return (EINVAL);
1427
1428         /*
1429          * Check if we are actually a member of this group.
1430          */
1431         imo = inp_findmoptions(inp);
1432         idx = imo_match_group(imo, ifp, &gsa->sa);
1433         if (idx == -1 || imo->imo_mfilters == NULL) {
1434                 error = EADDRNOTAVAIL;
1435                 goto out_inp_locked;
1436         }
1437
1438         KASSERT(imo->imo_mfilters != NULL,
1439             ("%s: imo_mfilters not allocated", __func__));
1440         imf = &imo->imo_mfilters[idx];
1441         inm = imo->imo_membership[idx];
1442
1443         /*
1444          * Attempting to use the delta-based API on an
1445          * non exclusive-mode membership is an error.
1446          */
1447         fmode = imf->imf_st[0];
1448         if (fmode != MCAST_EXCLUDE) {
1449                 error = EINVAL;
1450                 goto out_inp_locked;
1451         }
1452
1453         /*
1454          * Deal with error cases up-front:
1455          *  Asked to block, but already blocked; or
1456          *  Asked to unblock, but nothing to unblock.
1457          * If adding a new block entry, allocate it.
1458          */
1459         ims = imo_match_source(imo, idx, &ssa->sa);
1460         if ((ims != NULL && doblock) || (ims == NULL && !doblock)) {
1461                 CTR3(KTR_IGMPV3, "%s: source 0x%08x %spresent", __func__,
1462                     ntohl(ssa->sin.sin_addr.s_addr), doblock ? "" : "not ");
1463                 error = EADDRNOTAVAIL;
1464                 goto out_inp_locked;
1465         }
1466
1467         INP_WLOCK_ASSERT(inp);
1468
1469         /*
1470          * Begin state merge transaction at socket layer.
1471          */
1472         if (doblock) {
1473                 CTR2(KTR_IGMPV3, "%s: %s source", __func__, "block");
1474                 ims = imf_graft(imf, fmode, &ssa->sin);
1475                 if (ims == NULL)
1476                         error = ENOMEM;
1477         } else {
1478                 CTR2(KTR_IGMPV3, "%s: %s source", __func__, "allow");
1479                 error = imf_prune(imf, &ssa->sin);
1480         }
1481
1482         if (error) {
1483                 CTR1(KTR_IGMPV3, "%s: merge imf state failed", __func__);
1484                 goto out_imf_rollback;
1485         }
1486
1487         /*
1488          * Begin state merge transaction at IGMP layer.
1489          */
1490         IN_MULTI_LOCK();
1491
1492         CTR1(KTR_IGMPV3, "%s: merge inm state", __func__);
1493         error = inm_merge(inm, imf);
1494         if (error) {
1495                 CTR1(KTR_IGMPV3, "%s: failed to merge inm state", __func__);
1496                 goto out_in_multi_locked;
1497         }
1498
1499         CTR1(KTR_IGMPV3, "%s: doing igmp downcall", __func__);
1500         error = igmp_change_state(inm);
1501         if (error)
1502                 CTR1(KTR_IGMPV3, "%s: failed igmp downcall", __func__);
1503
1504 out_in_multi_locked:
1505
1506         IN_MULTI_UNLOCK();
1507
1508 out_imf_rollback:
1509         if (error)
1510                 imf_rollback(imf);
1511         else
1512                 imf_commit(imf);
1513
1514         imf_reap(imf);
1515
1516 out_inp_locked:
1517         INP_WUNLOCK(inp);
1518         return (error);
1519 }
1520
1521 /*
1522  * Given an inpcb, return its multicast options structure pointer.  Accepts
1523  * an unlocked inpcb pointer, but will return it locked.  May sleep.
1524  *
1525  * SMPng: NOTE: Potentially calls malloc(M_WAITOK) with Giant held.
1526  * SMPng: NOTE: Returns with the INP write lock held.
1527  */
1528 static struct ip_moptions *
1529 inp_findmoptions(struct inpcb *inp)
1530 {
1531         struct ip_moptions       *imo;
1532         struct in_multi         **immp;
1533         struct in_mfilter        *imfp;
1534         size_t                    idx;
1535
1536         INP_WLOCK(inp);
1537         if (inp->inp_moptions != NULL)
1538                 return (inp->inp_moptions);
1539
1540         INP_WUNLOCK(inp);
1541
1542         imo = malloc(sizeof(*imo), M_IPMOPTS, M_WAITOK);
1543         immp = malloc(sizeof(*immp) * IP_MIN_MEMBERSHIPS, M_IPMOPTS,
1544             M_WAITOK | M_ZERO);
1545         imfp = malloc(sizeof(struct in_mfilter) * IP_MIN_MEMBERSHIPS,
1546             M_INMFILTER, M_WAITOK);
1547
1548         imo->imo_multicast_ifp = NULL;
1549         imo->imo_multicast_addr.s_addr = INADDR_ANY;
1550         imo->imo_multicast_vif = -1;
1551         imo->imo_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1552         imo->imo_multicast_loop = in_mcast_loop;
1553         imo->imo_num_memberships = 0;
1554         imo->imo_max_memberships = IP_MIN_MEMBERSHIPS;
1555         imo->imo_membership = immp;
1556
1557         /* Initialize per-group source filters. */
1558         for (idx = 0; idx < IP_MIN_MEMBERSHIPS; idx++)
1559                 imf_init(&imfp[idx], MCAST_UNDEFINED, MCAST_EXCLUDE);
1560         imo->imo_mfilters = imfp;
1561
1562         INP_WLOCK(inp);
1563         if (inp->inp_moptions != NULL) {
1564                 free(imfp, M_INMFILTER);
1565                 free(immp, M_IPMOPTS);
1566                 free(imo, M_IPMOPTS);
1567                 return (inp->inp_moptions);
1568         }
1569         inp->inp_moptions = imo;
1570         return (imo);
1571 }
1572
1573 /*
1574  * Discard the IP multicast options (and source filters).  To minimize
1575  * the amount of work done while holding locks such as the INP's
1576  * pcbinfo lock (which is used in the receive path), the free
1577  * operation is performed asynchronously in a separate task.
1578  *
1579  * SMPng: NOTE: assumes INP write lock is held.
1580  */
1581 void
1582 inp_freemoptions(struct ip_moptions *imo)
1583 {
1584
1585         KASSERT(imo != NULL, ("%s: ip_moptions is NULL", __func__));
1586         IN_MULTI_LOCK();
1587         STAILQ_INSERT_TAIL(&imo_gc_list, imo, imo_link);
1588         IN_MULTI_UNLOCK();
1589         taskqueue_enqueue(taskqueue_thread, &imo_gc_task);
1590 }
1591
1592 static void
1593 inp_freemoptions_internal(struct ip_moptions *imo)
1594 {
1595         struct in_mfilter       *imf;
1596         size_t                   idx, nmships;
1597
1598         nmships = imo->imo_num_memberships;
1599         for (idx = 0; idx < nmships; ++idx) {
1600                 imf = imo->imo_mfilters ? &imo->imo_mfilters[idx] : NULL;
1601                 if (imf)
1602                         imf_leave(imf);
1603                 (void)in_leavegroup(imo->imo_membership[idx], imf);
1604                 if (imf)
1605                         imf_purge(imf);
1606         }
1607
1608         if (imo->imo_mfilters)
1609                 free(imo->imo_mfilters, M_INMFILTER);
1610         free(imo->imo_membership, M_IPMOPTS);
1611         free(imo, M_IPMOPTS);
1612 }
1613
1614 static void
1615 inp_gcmoptions(void *context, int pending)
1616 {
1617         struct ip_moptions *imo;
1618
1619         IN_MULTI_LOCK();
1620         while (!STAILQ_EMPTY(&imo_gc_list)) {
1621                 imo = STAILQ_FIRST(&imo_gc_list);
1622                 STAILQ_REMOVE_HEAD(&imo_gc_list, imo_link);
1623                 IN_MULTI_UNLOCK();
1624                 inp_freemoptions_internal(imo);
1625                 IN_MULTI_LOCK();
1626         }
1627         IN_MULTI_UNLOCK();
1628 }
1629
1630 /*
1631  * Atomically get source filters on a socket for an IPv4 multicast group.
1632  * Called with INP lock held; returns with lock released.
1633  */
1634 static int
1635 inp_get_source_filters(struct inpcb *inp, struct sockopt *sopt)
1636 {
1637         struct __msfilterreq     msfr;
1638         sockunion_t             *gsa;
1639         struct ifnet            *ifp;
1640         struct ip_moptions      *imo;
1641         struct in_mfilter       *imf;
1642         struct ip_msource       *ims;
1643         struct in_msource       *lims;
1644         struct sockaddr_in      *psin;
1645         struct sockaddr_storage *ptss;
1646         struct sockaddr_storage *tss;
1647         int                      error;
1648         size_t                   idx, nsrcs, ncsrcs;
1649
1650         INP_WLOCK_ASSERT(inp);
1651
1652         imo = inp->inp_moptions;
1653         KASSERT(imo != NULL, ("%s: null ip_moptions", __func__));
1654
1655         INP_WUNLOCK(inp);
1656
1657         error = sooptcopyin(sopt, &msfr, sizeof(struct __msfilterreq),
1658             sizeof(struct __msfilterreq));
1659         if (error)
1660                 return (error);
1661
1662         if (msfr.msfr_ifindex == 0 || V_if_index < msfr.msfr_ifindex)
1663                 return (EINVAL);
1664
1665         ifp = ifnet_byindex(msfr.msfr_ifindex);
1666         if (ifp == NULL)
1667                 return (EINVAL);
1668
1669         INP_WLOCK(inp);
1670
1671         /*
1672          * Lookup group on the socket.
1673          */
1674         gsa = (sockunion_t *)&msfr.msfr_group;
1675         idx = imo_match_group(imo, ifp, &gsa->sa);
1676         if (idx == -1 || imo->imo_mfilters == NULL) {
1677                 INP_WUNLOCK(inp);
1678                 return (EADDRNOTAVAIL);
1679         }
1680         imf = &imo->imo_mfilters[idx];
1681
1682         /*
1683          * Ignore memberships which are in limbo.
1684          */
1685         if (imf->imf_st[1] == MCAST_UNDEFINED) {
1686                 INP_WUNLOCK(inp);
1687                 return (EAGAIN);
1688         }
1689         msfr.msfr_fmode = imf->imf_st[1];
1690
1691         /*
1692          * If the user specified a buffer, copy out the source filter
1693          * entries to userland gracefully.
1694          * We only copy out the number of entries which userland
1695          * has asked for, but we always tell userland how big the
1696          * buffer really needs to be.
1697          */
1698         if (msfr.msfr_nsrcs > in_mcast_maxsocksrc)
1699                 msfr.msfr_nsrcs = in_mcast_maxsocksrc;
1700         tss = NULL;
1701         if (msfr.msfr_srcs != NULL && msfr.msfr_nsrcs > 0) {
1702                 tss = malloc(sizeof(struct sockaddr_storage) * msfr.msfr_nsrcs,
1703                     M_TEMP, M_NOWAIT | M_ZERO);
1704                 if (tss == NULL) {
1705                         INP_WUNLOCK(inp);
1706                         return (ENOBUFS);
1707                 }
1708         }
1709
1710         /*
1711          * Count number of sources in-mode at t0.
1712          * If buffer space exists and remains, copy out source entries.
1713          */
1714         nsrcs = msfr.msfr_nsrcs;
1715         ncsrcs = 0;
1716         ptss = tss;
1717         RB_FOREACH(ims, ip_msource_tree, &imf->imf_sources) {
1718                 lims = (struct in_msource *)ims;
1719                 if (lims->imsl_st[0] == MCAST_UNDEFINED ||
1720                     lims->imsl_st[0] != imf->imf_st[0])
1721                         continue;
1722                 ++ncsrcs;
1723                 if (tss != NULL && nsrcs > 0) {
1724                         psin = (struct sockaddr_in *)ptss;
1725                         psin->sin_family = AF_INET;
1726                         psin->sin_len = sizeof(struct sockaddr_in);
1727                         psin->sin_addr.s_addr = htonl(lims->ims_haddr);
1728                         psin->sin_port = 0;
1729                         ++ptss;
1730                         --nsrcs;
1731                 }
1732         }
1733
1734         INP_WUNLOCK(inp);
1735
1736         if (tss != NULL) {
1737                 error = copyout(tss, msfr.msfr_srcs,
1738                     sizeof(struct sockaddr_storage) * msfr.msfr_nsrcs);
1739                 free(tss, M_TEMP);
1740                 if (error)
1741                         return (error);
1742         }
1743
1744         msfr.msfr_nsrcs = ncsrcs;
1745         error = sooptcopyout(sopt, &msfr, sizeof(struct __msfilterreq));
1746
1747         return (error);
1748 }
1749
1750 /*
1751  * Return the IP multicast options in response to user getsockopt().
1752  */
1753 int
1754 inp_getmoptions(struct inpcb *inp, struct sockopt *sopt)
1755 {
1756         struct rm_priotracker    in_ifa_tracker;
1757         struct ip_mreqn          mreqn;
1758         struct ip_moptions      *imo;
1759         struct ifnet            *ifp;
1760         struct in_ifaddr        *ia;
1761         int                      error, optval;
1762         u_char                   coptval;
1763
1764         INP_WLOCK(inp);
1765         imo = inp->inp_moptions;
1766         /*
1767          * If socket is neither of type SOCK_RAW or SOCK_DGRAM,
1768          * or is a divert socket, reject it.
1769          */
1770         if (inp->inp_socket->so_proto->pr_protocol == IPPROTO_DIVERT ||
1771             (inp->inp_socket->so_proto->pr_type != SOCK_RAW &&
1772             inp->inp_socket->so_proto->pr_type != SOCK_DGRAM)) {
1773                 INP_WUNLOCK(inp);
1774                 return (EOPNOTSUPP);
1775         }
1776
1777         error = 0;
1778         switch (sopt->sopt_name) {
1779         case IP_MULTICAST_VIF:
1780                 if (imo != NULL)
1781                         optval = imo->imo_multicast_vif;
1782                 else
1783                         optval = -1;
1784                 INP_WUNLOCK(inp);
1785                 error = sooptcopyout(sopt, &optval, sizeof(int));
1786                 break;
1787
1788         case IP_MULTICAST_IF:
1789                 memset(&mreqn, 0, sizeof(struct ip_mreqn));
1790                 if (imo != NULL) {
1791                         ifp = imo->imo_multicast_ifp;
1792                         if (!in_nullhost(imo->imo_multicast_addr)) {
1793                                 mreqn.imr_address = imo->imo_multicast_addr;
1794                         } else if (ifp != NULL) {
1795                                 mreqn.imr_ifindex = ifp->if_index;
1796                                 IFP_TO_IA(ifp, ia, &in_ifa_tracker);
1797                                 if (ia != NULL) {
1798                                         mreqn.imr_address =
1799                                             IA_SIN(ia)->sin_addr;
1800                                         ifa_free(&ia->ia_ifa);
1801                                 }
1802                         }
1803                 }
1804                 INP_WUNLOCK(inp);
1805                 if (sopt->sopt_valsize == sizeof(struct ip_mreqn)) {
1806                         error = sooptcopyout(sopt, &mreqn,
1807                             sizeof(struct ip_mreqn));
1808                 } else {
1809                         error = sooptcopyout(sopt, &mreqn.imr_address,
1810                             sizeof(struct in_addr));
1811                 }
1812                 break;
1813
1814         case IP_MULTICAST_TTL:
1815                 if (imo == NULL)
1816                         optval = coptval = IP_DEFAULT_MULTICAST_TTL;
1817                 else
1818                         optval = coptval = imo->imo_multicast_ttl;
1819                 INP_WUNLOCK(inp);
1820                 if (sopt->sopt_valsize == sizeof(u_char))
1821                         error = sooptcopyout(sopt, &coptval, sizeof(u_char));
1822                 else
1823                         error = sooptcopyout(sopt, &optval, sizeof(int));
1824                 break;
1825
1826         case IP_MULTICAST_LOOP:
1827                 if (imo == NULL)
1828                         optval = coptval = IP_DEFAULT_MULTICAST_LOOP;
1829                 else
1830                         optval = coptval = imo->imo_multicast_loop;
1831                 INP_WUNLOCK(inp);
1832                 if (sopt->sopt_valsize == sizeof(u_char))
1833                         error = sooptcopyout(sopt, &coptval, sizeof(u_char));
1834                 else
1835                         error = sooptcopyout(sopt, &optval, sizeof(int));
1836                 break;
1837
1838         case IP_MSFILTER:
1839                 if (imo == NULL) {
1840                         error = EADDRNOTAVAIL;
1841                         INP_WUNLOCK(inp);
1842                 } else {
1843                         error = inp_get_source_filters(inp, sopt);
1844                 }
1845                 break;
1846
1847         default:
1848                 INP_WUNLOCK(inp);
1849                 error = ENOPROTOOPT;
1850                 break;
1851         }
1852
1853         INP_UNLOCK_ASSERT(inp);
1854
1855         return (error);
1856 }
1857
1858 /*
1859  * Look up the ifnet to use for a multicast group membership,
1860  * given the IPv4 address of an interface, and the IPv4 group address.
1861  *
1862  * This routine exists to support legacy multicast applications
1863  * which do not understand that multicast memberships are scoped to
1864  * specific physical links in the networking stack, or which need
1865  * to join link-scope groups before IPv4 addresses are configured.
1866  *
1867  * If inp is non-NULL, use this socket's current FIB number for any
1868  * required FIB lookup.
1869  * If ina is INADDR_ANY, look up the group address in the unicast FIB,
1870  * and use its ifp; usually, this points to the default next-hop.
1871  *
1872  * If the FIB lookup fails, attempt to use the first non-loopback
1873  * interface with multicast capability in the system as a
1874  * last resort. The legacy IPv4 ASM API requires that we do
1875  * this in order to allow groups to be joined when the routing
1876  * table has not yet been populated during boot.
1877  *
1878  * Returns NULL if no ifp could be found.
1879  *
1880  * FUTURE: Implement IPv4 source-address selection.
1881  */
1882 static struct ifnet *
1883 inp_lookup_mcast_ifp(const struct inpcb *inp,
1884     const struct sockaddr_in *gsin, const struct in_addr ina)
1885 {
1886         struct rm_priotracker in_ifa_tracker;
1887         struct ifnet *ifp;
1888         struct nhop4_basic nh4;
1889         uint32_t fibnum;
1890
1891         KASSERT(gsin->sin_family == AF_INET, ("%s: not AF_INET", __func__));
1892         KASSERT(IN_MULTICAST(ntohl(gsin->sin_addr.s_addr)),
1893             ("%s: not multicast", __func__));
1894
1895         ifp = NULL;
1896         if (!in_nullhost(ina)) {
1897                 IN_IFADDR_RLOCK(&in_ifa_tracker);
1898                 INADDR_TO_IFP(ina, ifp);
1899                 IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1900         } else {
1901                 fibnum = inp ? inp->inp_inc.inc_fibnum : 0;
1902                 if (fib4_lookup_nh_basic(fibnum, gsin->sin_addr, 0, 0, &nh4)==0)
1903                         ifp = nh4.nh_ifp;
1904                 else {
1905                         struct in_ifaddr *ia;
1906                         struct ifnet *mifp;
1907
1908                         mifp = NULL;
1909                         IN_IFADDR_RLOCK(&in_ifa_tracker);
1910                         TAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
1911                                 mifp = ia->ia_ifp;
1912                                 if (!(mifp->if_flags & IFF_LOOPBACK) &&
1913                                      (mifp->if_flags & IFF_MULTICAST)) {
1914                                         ifp = mifp;
1915                                         break;
1916                                 }
1917                         }
1918                         IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1919                 }
1920         }
1921
1922         return (ifp);
1923 }
1924
1925 /*
1926  * Join an IPv4 multicast group, possibly with a source.
1927  */
1928 static int
1929 inp_join_group(struct inpcb *inp, struct sockopt *sopt)
1930 {
1931         struct group_source_req          gsr;
1932         sockunion_t                     *gsa, *ssa;
1933         struct ifnet                    *ifp;
1934         struct in_mfilter               *imf;
1935         struct ip_moptions              *imo;
1936         struct in_multi                 *inm;
1937         struct in_msource               *lims;
1938         size_t                           idx;
1939         int                              error, is_new;
1940
1941         ifp = NULL;
1942         imf = NULL;
1943         lims = NULL;
1944         error = 0;
1945         is_new = 0;
1946
1947         memset(&gsr, 0, sizeof(struct group_source_req));
1948         gsa = (sockunion_t *)&gsr.gsr_group;
1949         gsa->ss.ss_family = AF_UNSPEC;
1950         ssa = (sockunion_t *)&gsr.gsr_source;
1951         ssa->ss.ss_family = AF_UNSPEC;
1952
1953         switch (sopt->sopt_name) {
1954         case IP_ADD_MEMBERSHIP:
1955         case IP_ADD_SOURCE_MEMBERSHIP: {
1956                 struct ip_mreq_source    mreqs;
1957
1958                 if (sopt->sopt_name == IP_ADD_MEMBERSHIP) {
1959                         error = sooptcopyin(sopt, &mreqs,
1960                             sizeof(struct ip_mreq),
1961                             sizeof(struct ip_mreq));
1962                         /*
1963                          * Do argument switcharoo from ip_mreq into
1964                          * ip_mreq_source to avoid using two instances.
1965                          */
1966                         mreqs.imr_interface = mreqs.imr_sourceaddr;
1967                         mreqs.imr_sourceaddr.s_addr = INADDR_ANY;
1968                 } else if (sopt->sopt_name == IP_ADD_SOURCE_MEMBERSHIP) {
1969                         error = sooptcopyin(sopt, &mreqs,
1970                             sizeof(struct ip_mreq_source),
1971                             sizeof(struct ip_mreq_source));
1972                 }
1973                 if (error)
1974                         return (error);
1975
1976                 gsa->sin.sin_family = AF_INET;
1977                 gsa->sin.sin_len = sizeof(struct sockaddr_in);
1978                 gsa->sin.sin_addr = mreqs.imr_multiaddr;
1979
1980                 if (sopt->sopt_name == IP_ADD_SOURCE_MEMBERSHIP) {
1981                         ssa->sin.sin_family = AF_INET;
1982                         ssa->sin.sin_len = sizeof(struct sockaddr_in);
1983                         ssa->sin.sin_addr = mreqs.imr_sourceaddr;
1984                 }
1985
1986                 if (!IN_MULTICAST(ntohl(gsa->sin.sin_addr.s_addr)))
1987                         return (EINVAL);
1988
1989                 ifp = inp_lookup_mcast_ifp(inp, &gsa->sin,
1990                     mreqs.imr_interface);
1991                 CTR3(KTR_IGMPV3, "%s: imr_interface = 0x%08x, ifp = %p",
1992                     __func__, ntohl(mreqs.imr_interface.s_addr), ifp);
1993                 break;
1994         }
1995
1996         case MCAST_JOIN_GROUP:
1997         case MCAST_JOIN_SOURCE_GROUP:
1998                 if (sopt->sopt_name == MCAST_JOIN_GROUP) {
1999                         error = sooptcopyin(sopt, &gsr,
2000                             sizeof(struct group_req),
2001                             sizeof(struct group_req));
2002                 } else if (sopt->sopt_name == MCAST_JOIN_SOURCE_GROUP) {
2003                         error = sooptcopyin(sopt, &gsr,
2004                             sizeof(struct group_source_req),
2005                             sizeof(struct group_source_req));
2006                 }
2007                 if (error)
2008                         return (error);
2009
2010                 if (gsa->sin.sin_family != AF_INET ||
2011                     gsa->sin.sin_len != sizeof(struct sockaddr_in))
2012                         return (EINVAL);
2013
2014                 /*
2015                  * Overwrite the port field if present, as the sockaddr
2016                  * being copied in may be matched with a binary comparison.
2017                  */
2018                 gsa->sin.sin_port = 0;
2019                 if (sopt->sopt_name == MCAST_JOIN_SOURCE_GROUP) {
2020                         if (ssa->sin.sin_family != AF_INET ||
2021                             ssa->sin.sin_len != sizeof(struct sockaddr_in))
2022                                 return (EINVAL);
2023                         ssa->sin.sin_port = 0;
2024                 }
2025
2026                 if (!IN_MULTICAST(ntohl(gsa->sin.sin_addr.s_addr)))
2027                         return (EINVAL);
2028
2029                 if (gsr.gsr_interface == 0 || V_if_index < gsr.gsr_interface)
2030                         return (EADDRNOTAVAIL);
2031                 ifp = ifnet_byindex(gsr.gsr_interface);
2032                 break;
2033
2034         default:
2035                 CTR2(KTR_IGMPV3, "%s: unknown sopt_name %d",
2036                     __func__, sopt->sopt_name);
2037                 return (EOPNOTSUPP);
2038                 break;
2039         }
2040
2041         if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0)
2042                 return (EADDRNOTAVAIL);
2043
2044         imo = inp_findmoptions(inp);
2045         idx = imo_match_group(imo, ifp, &gsa->sa);
2046         if (idx == -1) {
2047                 is_new = 1;
2048         } else {
2049                 inm = imo->imo_membership[idx];
2050                 imf = &imo->imo_mfilters[idx];
2051                 if (ssa->ss.ss_family != AF_UNSPEC) {
2052                         /*
2053                          * MCAST_JOIN_SOURCE_GROUP on an exclusive membership
2054                          * is an error. On an existing inclusive membership,
2055                          * it just adds the source to the filter list.
2056                          */
2057                         if (imf->imf_st[1] != MCAST_INCLUDE) {
2058                                 error = EINVAL;
2059                                 goto out_inp_locked;
2060                         }
2061                         /*
2062                          * Throw out duplicates.
2063                          *
2064                          * XXX FIXME: This makes a naive assumption that
2065                          * even if entries exist for *ssa in this imf,
2066                          * they will be rejected as dupes, even if they
2067                          * are not valid in the current mode (in-mode).
2068                          *
2069                          * in_msource is transactioned just as for anything
2070                          * else in SSM -- but note naive use of inm_graft()
2071                          * below for allocating new filter entries.
2072                          *
2073                          * This is only an issue if someone mixes the
2074                          * full-state SSM API with the delta-based API,
2075                          * which is discouraged in the relevant RFCs.
2076                          */
2077                         lims = imo_match_source(imo, idx, &ssa->sa);
2078                         if (lims != NULL /*&&
2079                             lims->imsl_st[1] == MCAST_INCLUDE*/) {
2080                                 error = EADDRNOTAVAIL;
2081                                 goto out_inp_locked;
2082                         }
2083                 } else {
2084                         /*
2085                          * MCAST_JOIN_GROUP on an existing exclusive
2086                          * membership is an error; return EADDRINUSE
2087                          * to preserve 4.4BSD API idempotence, and
2088                          * avoid tedious detour to code below.
2089                          * NOTE: This is bending RFC 3678 a bit.
2090                          *
2091                          * On an existing inclusive membership, this is also
2092                          * an error; if you want to change filter mode,
2093                          * you must use the userland API setsourcefilter().
2094                          * XXX We don't reject this for imf in UNDEFINED
2095                          * state at t1, because allocation of a filter
2096                          * is atomic with allocation of a membership.
2097                          */
2098                         error = EINVAL;
2099                         if (imf->imf_st[1] == MCAST_EXCLUDE)
2100                                 error = EADDRINUSE;
2101                         goto out_inp_locked;
2102                 }
2103         }
2104
2105         /*
2106          * Begin state merge transaction at socket layer.
2107          */
2108         INP_WLOCK_ASSERT(inp);
2109
2110         if (is_new) {
2111                 if (imo->imo_num_memberships == imo->imo_max_memberships) {
2112                         error = imo_grow(imo);
2113                         if (error)
2114                                 goto out_inp_locked;
2115                 }
2116                 /*
2117                  * Allocate the new slot upfront so we can deal with
2118                  * grafting the new source filter in same code path
2119                  * as for join-source on existing membership.
2120                  */
2121                 idx = imo->imo_num_memberships;
2122                 imo->imo_membership[idx] = NULL;
2123                 imo->imo_num_memberships++;
2124                 KASSERT(imo->imo_mfilters != NULL,
2125                     ("%s: imf_mfilters vector was not allocated", __func__));
2126                 imf = &imo->imo_mfilters[idx];
2127                 KASSERT(RB_EMPTY(&imf->imf_sources),
2128                     ("%s: imf_sources not empty", __func__));
2129         }
2130
2131         /*
2132          * Graft new source into filter list for this inpcb's
2133          * membership of the group. The in_multi may not have
2134          * been allocated yet if this is a new membership, however,
2135          * the in_mfilter slot will be allocated and must be initialized.
2136          *
2137          * Note: Grafting of exclusive mode filters doesn't happen
2138          * in this path.
2139          * XXX: Should check for non-NULL lims (node exists but may
2140          * not be in-mode) for interop with full-state API.
2141          */
2142         if (ssa->ss.ss_family != AF_UNSPEC) {
2143                 /* Membership starts in IN mode */
2144                 if (is_new) {
2145                         CTR1(KTR_IGMPV3, "%s: new join w/source", __func__);
2146                         imf_init(imf, MCAST_UNDEFINED, MCAST_INCLUDE);
2147                 } else {
2148                         CTR2(KTR_IGMPV3, "%s: %s source", __func__, "allow");
2149                 }
2150                 lims = imf_graft(imf, MCAST_INCLUDE, &ssa->sin);
2151                 if (lims == NULL) {
2152                         CTR1(KTR_IGMPV3, "%s: merge imf state failed",
2153                             __func__);
2154                         error = ENOMEM;
2155                         goto out_imo_free;
2156                 }
2157         } else {
2158                 /* No address specified; Membership starts in EX mode */
2159                 if (is_new) {
2160                         CTR1(KTR_IGMPV3, "%s: new join w/o source", __func__);
2161                         imf_init(imf, MCAST_UNDEFINED, MCAST_EXCLUDE);
2162                 }
2163         }
2164
2165         /*
2166          * Begin state merge transaction at IGMP layer.
2167          */
2168         IN_MULTI_LOCK();
2169
2170         if (is_new) {
2171                 error = in_joingroup_locked(ifp, &gsa->sin.sin_addr, imf,
2172                     &inm);
2173                 if (error) {
2174                         CTR1(KTR_IGMPV3, "%s: in_joingroup_locked failed", 
2175                             __func__);
2176                         IN_MULTI_UNLOCK();
2177                         goto out_imo_free;
2178                 }
2179                 imo->imo_membership[idx] = inm;
2180         } else {
2181                 CTR1(KTR_IGMPV3, "%s: merge inm state", __func__);
2182                 error = inm_merge(inm, imf);
2183                 if (error) {
2184                         CTR1(KTR_IGMPV3, "%s: failed to merge inm state",
2185                             __func__);
2186                         goto out_in_multi_locked;
2187                 }
2188                 CTR1(KTR_IGMPV3, "%s: doing igmp downcall", __func__);
2189                 error = igmp_change_state(inm);
2190                 if (error) {
2191                         CTR1(KTR_IGMPV3, "%s: failed igmp downcall",
2192                             __func__);
2193                         goto out_in_multi_locked;
2194                 }
2195         }
2196
2197 out_in_multi_locked:
2198
2199         IN_MULTI_UNLOCK();
2200
2201         INP_WLOCK_ASSERT(inp);
2202         if (error) {
2203                 imf_rollback(imf);
2204                 if (is_new)
2205                         imf_purge(imf);
2206                 else
2207                         imf_reap(imf);
2208         } else {
2209                 imf_commit(imf);
2210         }
2211
2212 out_imo_free:
2213         if (error && is_new) {
2214                 imo->imo_membership[idx] = NULL;
2215                 --imo->imo_num_memberships;
2216         }
2217
2218 out_inp_locked:
2219         INP_WUNLOCK(inp);
2220         return (error);
2221 }
2222
2223 /*
2224  * Leave an IPv4 multicast group on an inpcb, possibly with a source.
2225  */
2226 static int
2227 inp_leave_group(struct inpcb *inp, struct sockopt *sopt)
2228 {
2229         struct group_source_req          gsr;
2230         struct ip_mreq_source            mreqs;
2231         struct rm_priotracker            in_ifa_tracker;
2232         sockunion_t                     *gsa, *ssa;
2233         struct ifnet                    *ifp;
2234         struct in_mfilter               *imf;
2235         struct ip_moptions              *imo;
2236         struct in_msource               *ims;
2237         struct in_multi                 *inm;
2238         size_t                           idx;
2239         int                              error, is_final;
2240
2241         ifp = NULL;
2242         error = 0;
2243         is_final = 1;
2244
2245         memset(&gsr, 0, sizeof(struct group_source_req));
2246         gsa = (sockunion_t *)&gsr.gsr_group;
2247         gsa->ss.ss_family = AF_UNSPEC;
2248         ssa = (sockunion_t *)&gsr.gsr_source;
2249         ssa->ss.ss_family = AF_UNSPEC;
2250
2251         switch (sopt->sopt_name) {
2252         case IP_DROP_MEMBERSHIP:
2253         case IP_DROP_SOURCE_MEMBERSHIP:
2254                 if (sopt->sopt_name == IP_DROP_MEMBERSHIP) {
2255                         error = sooptcopyin(sopt, &mreqs,
2256                             sizeof(struct ip_mreq),
2257                             sizeof(struct ip_mreq));
2258                         /*
2259                          * Swap interface and sourceaddr arguments,
2260                          * as ip_mreq and ip_mreq_source are laid
2261                          * out differently.
2262                          */
2263                         mreqs.imr_interface = mreqs.imr_sourceaddr;
2264                         mreqs.imr_sourceaddr.s_addr = INADDR_ANY;
2265                 } else if (sopt->sopt_name == IP_DROP_SOURCE_MEMBERSHIP) {
2266                         error = sooptcopyin(sopt, &mreqs,
2267                             sizeof(struct ip_mreq_source),
2268                             sizeof(struct ip_mreq_source));
2269                 }
2270                 if (error)
2271                         return (error);
2272
2273                 gsa->sin.sin_family = AF_INET;
2274                 gsa->sin.sin_len = sizeof(struct sockaddr_in);
2275                 gsa->sin.sin_addr = mreqs.imr_multiaddr;
2276
2277                 if (sopt->sopt_name == IP_DROP_SOURCE_MEMBERSHIP) {
2278                         ssa->sin.sin_family = AF_INET;
2279                         ssa->sin.sin_len = sizeof(struct sockaddr_in);
2280                         ssa->sin.sin_addr = mreqs.imr_sourceaddr;
2281                 }
2282
2283                 /*
2284                  * Attempt to look up hinted ifp from interface address.
2285                  * Fallthrough with null ifp iff lookup fails, to
2286                  * preserve 4.4BSD mcast API idempotence.
2287                  * XXX NOTE WELL: The RFC 3678 API is preferred because
2288                  * using an IPv4 address as a key is racy.
2289                  */
2290                 if (!in_nullhost(mreqs.imr_interface)) {
2291                         IN_IFADDR_RLOCK(&in_ifa_tracker);
2292                         INADDR_TO_IFP(mreqs.imr_interface, ifp);
2293                         IN_IFADDR_RUNLOCK(&in_ifa_tracker);
2294                 }
2295                 CTR3(KTR_IGMPV3, "%s: imr_interface = 0x%08x, ifp = %p",
2296                     __func__, ntohl(mreqs.imr_interface.s_addr), ifp);
2297
2298                 break;
2299
2300         case MCAST_LEAVE_GROUP:
2301         case MCAST_LEAVE_SOURCE_GROUP:
2302                 if (sopt->sopt_name == MCAST_LEAVE_GROUP) {
2303                         error = sooptcopyin(sopt, &gsr,
2304                             sizeof(struct group_req),
2305                             sizeof(struct group_req));
2306                 } else if (sopt->sopt_name == MCAST_LEAVE_SOURCE_GROUP) {
2307                         error = sooptcopyin(sopt, &gsr,
2308                             sizeof(struct group_source_req),
2309                             sizeof(struct group_source_req));
2310                 }
2311                 if (error)
2312                         return (error);
2313
2314                 if (gsa->sin.sin_family != AF_INET ||
2315                     gsa->sin.sin_len != sizeof(struct sockaddr_in))
2316                         return (EINVAL);
2317
2318                 if (sopt->sopt_name == MCAST_LEAVE_SOURCE_GROUP) {
2319                         if (ssa->sin.sin_family != AF_INET ||
2320                             ssa->sin.sin_len != sizeof(struct sockaddr_in))
2321                                 return (EINVAL);
2322                 }
2323
2324                 if (gsr.gsr_interface == 0 || V_if_index < gsr.gsr_interface)
2325                         return (EADDRNOTAVAIL);
2326
2327                 ifp = ifnet_byindex(gsr.gsr_interface);
2328
2329                 if (ifp == NULL)
2330                         return (EADDRNOTAVAIL);
2331                 break;
2332
2333         default:
2334                 CTR2(KTR_IGMPV3, "%s: unknown sopt_name %d",
2335                     __func__, sopt->sopt_name);
2336                 return (EOPNOTSUPP);
2337                 break;
2338         }
2339
2340         if (!IN_MULTICAST(ntohl(gsa->sin.sin_addr.s_addr)))
2341                 return (EINVAL);
2342
2343         /*
2344          * Find the membership in the membership array.
2345          */
2346         imo = inp_findmoptions(inp);
2347         idx = imo_match_group(imo, ifp, &gsa->sa);
2348         if (idx == -1) {
2349                 error = EADDRNOTAVAIL;
2350                 goto out_inp_locked;
2351         }
2352         inm = imo->imo_membership[idx];
2353         imf = &imo->imo_mfilters[idx];
2354
2355         if (ssa->ss.ss_family != AF_UNSPEC)
2356                 is_final = 0;
2357
2358         /*
2359          * Begin state merge transaction at socket layer.
2360          */
2361         INP_WLOCK_ASSERT(inp);
2362
2363         /*
2364          * If we were instructed only to leave a given source, do so.
2365          * MCAST_LEAVE_SOURCE_GROUP is only valid for inclusive memberships.
2366          */
2367         if (is_final) {
2368                 imf_leave(imf);
2369         } else {
2370                 if (imf->imf_st[0] == MCAST_EXCLUDE) {
2371                         error = EADDRNOTAVAIL;
2372                         goto out_inp_locked;
2373                 }
2374                 ims = imo_match_source(imo, idx, &ssa->sa);
2375                 if (ims == NULL) {
2376                         CTR3(KTR_IGMPV3, "%s: source 0x%08x %spresent",
2377                             __func__, ntohl(ssa->sin.sin_addr.s_addr), "not ");
2378                         error = EADDRNOTAVAIL;
2379                         goto out_inp_locked;
2380                 }
2381                 CTR2(KTR_IGMPV3, "%s: %s source", __func__, "block");
2382                 error = imf_prune(imf, &ssa->sin);
2383                 if (error) {
2384                         CTR1(KTR_IGMPV3, "%s: merge imf state failed",
2385                             __func__);
2386                         goto out_inp_locked;
2387                 }
2388         }
2389
2390         /*
2391          * Begin state merge transaction at IGMP layer.
2392          */
2393         IN_MULTI_LOCK();
2394
2395         if (is_final) {
2396                 /*
2397                  * Give up the multicast address record to which
2398                  * the membership points.
2399                  */
2400                 (void)in_leavegroup_locked(inm, imf);
2401         } else {
2402                 CTR1(KTR_IGMPV3, "%s: merge inm state", __func__);
2403                 error = inm_merge(inm, imf);
2404                 if (error) {
2405                         CTR1(KTR_IGMPV3, "%s: failed to merge inm state",
2406                             __func__);
2407                         goto out_in_multi_locked;
2408                 }
2409
2410                 CTR1(KTR_IGMPV3, "%s: doing igmp downcall", __func__);
2411                 error = igmp_change_state(inm);
2412                 if (error) {
2413                         CTR1(KTR_IGMPV3, "%s: failed igmp downcall",
2414                             __func__);
2415                 }
2416         }
2417
2418 out_in_multi_locked:
2419
2420         IN_MULTI_UNLOCK();
2421
2422         if (error)
2423                 imf_rollback(imf);
2424         else
2425                 imf_commit(imf);
2426
2427         imf_reap(imf);
2428
2429         if (is_final) {
2430                 /* Remove the gap in the membership and filter array. */
2431                 KASSERT(RB_EMPTY(&imf->imf_sources),
2432                     ("%s: imf_sources not empty", __func__));
2433                 for (++idx; idx < imo->imo_num_memberships; ++idx) {
2434                         imo->imo_membership[idx - 1] = imo->imo_membership[idx];
2435                         imo->imo_mfilters[idx - 1] = imo->imo_mfilters[idx];
2436                 }
2437                 imf_init(&imo->imo_mfilters[idx - 1], MCAST_UNDEFINED,
2438                     MCAST_EXCLUDE);
2439                 imo->imo_num_memberships--;
2440         }
2441
2442 out_inp_locked:
2443         INP_WUNLOCK(inp);
2444         return (error);
2445 }
2446
2447 /*
2448  * Select the interface for transmitting IPv4 multicast datagrams.
2449  *
2450  * Either an instance of struct in_addr or an instance of struct ip_mreqn
2451  * may be passed to this socket option. An address of INADDR_ANY or an
2452  * interface index of 0 is used to remove a previous selection.
2453  * When no interface is selected, one is chosen for every send.
2454  */
2455 static int
2456 inp_set_multicast_if(struct inpcb *inp, struct sockopt *sopt)
2457 {
2458         struct rm_priotracker    in_ifa_tracker;
2459         struct in_addr           addr;
2460         struct ip_mreqn          mreqn;
2461         struct ifnet            *ifp;
2462         struct ip_moptions      *imo;
2463         int                      error;
2464
2465         if (sopt->sopt_valsize == sizeof(struct ip_mreqn)) {
2466                 /*
2467                  * An interface index was specified using the
2468                  * Linux-derived ip_mreqn structure.
2469                  */
2470                 error = sooptcopyin(sopt, &mreqn, sizeof(struct ip_mreqn),
2471                     sizeof(struct ip_mreqn));
2472                 if (error)
2473                         return (error);
2474
2475                 if (mreqn.imr_ifindex < 0 || V_if_index < mreqn.imr_ifindex)
2476                         return (EINVAL);
2477
2478                 if (mreqn.imr_ifindex == 0) {
2479                         ifp = NULL;
2480                 } else {
2481                         ifp = ifnet_byindex(mreqn.imr_ifindex);
2482                         if (ifp == NULL)
2483                                 return (EADDRNOTAVAIL);
2484                 }
2485         } else {
2486                 /*
2487                  * An interface was specified by IPv4 address.
2488                  * This is the traditional BSD usage.
2489                  */
2490                 error = sooptcopyin(sopt, &addr, sizeof(struct in_addr),
2491                     sizeof(struct in_addr));
2492                 if (error)
2493                         return (error);
2494                 if (in_nullhost(addr)) {
2495                         ifp = NULL;
2496                 } else {
2497                         IN_IFADDR_RLOCK(&in_ifa_tracker);
2498                         INADDR_TO_IFP(addr, ifp);
2499                         IN_IFADDR_RUNLOCK(&in_ifa_tracker);
2500                         if (ifp == NULL)
2501                                 return (EADDRNOTAVAIL);
2502                 }
2503                 CTR3(KTR_IGMPV3, "%s: ifp = %p, addr = 0x%08x", __func__, ifp,
2504                     ntohl(addr.s_addr));
2505         }
2506
2507         /* Reject interfaces which do not support multicast. */
2508         if (ifp != NULL && (ifp->if_flags & IFF_MULTICAST) == 0)
2509                 return (EOPNOTSUPP);
2510
2511         imo = inp_findmoptions(inp);
2512         imo->imo_multicast_ifp = ifp;
2513         imo->imo_multicast_addr.s_addr = INADDR_ANY;
2514         INP_WUNLOCK(inp);
2515
2516         return (0);
2517 }
2518
2519 /*
2520  * Atomically set source filters on a socket for an IPv4 multicast group.
2521  *
2522  * SMPng: NOTE: Potentially calls malloc(M_WAITOK) with Giant held.
2523  */
2524 static int
2525 inp_set_source_filters(struct inpcb *inp, struct sockopt *sopt)
2526 {
2527         struct __msfilterreq     msfr;
2528         sockunion_t             *gsa;
2529         struct ifnet            *ifp;
2530         struct in_mfilter       *imf;
2531         struct ip_moptions      *imo;
2532         struct in_multi         *inm;
2533         size_t                   idx;
2534         int                      error;
2535
2536         error = sooptcopyin(sopt, &msfr, sizeof(struct __msfilterreq),
2537             sizeof(struct __msfilterreq));
2538         if (error)
2539                 return (error);
2540
2541         if (msfr.msfr_nsrcs > in_mcast_maxsocksrc)
2542                 return (ENOBUFS);
2543
2544         if ((msfr.msfr_fmode != MCAST_EXCLUDE &&
2545              msfr.msfr_fmode != MCAST_INCLUDE))
2546                 return (EINVAL);
2547
2548         if (msfr.msfr_group.ss_family != AF_INET ||
2549             msfr.msfr_group.ss_len != sizeof(struct sockaddr_in))
2550                 return (EINVAL);
2551
2552         gsa = (sockunion_t *)&msfr.msfr_group;
2553         if (!IN_MULTICAST(ntohl(gsa->sin.sin_addr.s_addr)))
2554                 return (EINVAL);
2555
2556         gsa->sin.sin_port = 0;  /* ignore port */
2557
2558         if (msfr.msfr_ifindex == 0 || V_if_index < msfr.msfr_ifindex)
2559                 return (EADDRNOTAVAIL);
2560
2561         ifp = ifnet_byindex(msfr.msfr_ifindex);
2562         if (ifp == NULL)
2563                 return (EADDRNOTAVAIL);
2564
2565         /*
2566          * Take the INP write lock.
2567          * Check if this socket is a member of this group.
2568          */
2569         imo = inp_findmoptions(inp);
2570         idx = imo_match_group(imo, ifp, &gsa->sa);
2571         if (idx == -1 || imo->imo_mfilters == NULL) {
2572                 error = EADDRNOTAVAIL;
2573                 goto out_inp_locked;
2574         }
2575         inm = imo->imo_membership[idx];
2576         imf = &imo->imo_mfilters[idx];
2577
2578         /*
2579          * Begin state merge transaction at socket layer.
2580          */
2581         INP_WLOCK_ASSERT(inp);
2582
2583         imf->imf_st[1] = msfr.msfr_fmode;
2584
2585         /*
2586          * Apply any new source filters, if present.
2587          * Make a copy of the user-space source vector so
2588          * that we may copy them with a single copyin. This
2589          * allows us to deal with page faults up-front.
2590          */
2591         if (msfr.msfr_nsrcs > 0) {
2592                 struct in_msource       *lims;
2593                 struct sockaddr_in      *psin;
2594                 struct sockaddr_storage *kss, *pkss;
2595                 int                      i;
2596
2597                 INP_WUNLOCK(inp);
2598  
2599                 CTR2(KTR_IGMPV3, "%s: loading %lu source list entries",
2600                     __func__, (unsigned long)msfr.msfr_nsrcs);
2601                 kss = malloc(sizeof(struct sockaddr_storage) * msfr.msfr_nsrcs,
2602                     M_TEMP, M_WAITOK);
2603                 error = copyin(msfr.msfr_srcs, kss,
2604                     sizeof(struct sockaddr_storage) * msfr.msfr_nsrcs);
2605                 if (error) {
2606                         free(kss, M_TEMP);
2607                         return (error);
2608                 }
2609
2610                 INP_WLOCK(inp);
2611
2612                 /*
2613                  * Mark all source filters as UNDEFINED at t1.
2614                  * Restore new group filter mode, as imf_leave()
2615                  * will set it to INCLUDE.
2616                  */
2617                 imf_leave(imf);
2618                 imf->imf_st[1] = msfr.msfr_fmode;
2619
2620                 /*
2621                  * Update socket layer filters at t1, lazy-allocating
2622                  * new entries. This saves a bunch of memory at the
2623                  * cost of one RB_FIND() per source entry; duplicate
2624                  * entries in the msfr_nsrcs vector are ignored.
2625                  * If we encounter an error, rollback transaction.
2626                  *
2627                  * XXX This too could be replaced with a set-symmetric
2628                  * difference like loop to avoid walking from root
2629                  * every time, as the key space is common.
2630                  */
2631                 for (i = 0, pkss = kss; i < msfr.msfr_nsrcs; i++, pkss++) {
2632                         psin = (struct sockaddr_in *)pkss;
2633                         if (psin->sin_family != AF_INET) {
2634                                 error = EAFNOSUPPORT;
2635                                 break;
2636                         }
2637                         if (psin->sin_len != sizeof(struct sockaddr_in)) {
2638                                 error = EINVAL;
2639                                 break;
2640                         }
2641                         error = imf_get_source(imf, psin, &lims);
2642                         if (error)
2643                                 break;
2644                         lims->imsl_st[1] = imf->imf_st[1];
2645                 }
2646                 free(kss, M_TEMP);
2647         }
2648
2649         if (error)
2650                 goto out_imf_rollback;
2651
2652         INP_WLOCK_ASSERT(inp);
2653         IN_MULTI_LOCK();
2654
2655         /*
2656          * Begin state merge transaction at IGMP layer.
2657          */
2658         CTR1(KTR_IGMPV3, "%s: merge inm state", __func__);
2659         error = inm_merge(inm, imf);
2660         if (error) {
2661                 CTR1(KTR_IGMPV3, "%s: failed to merge inm state", __func__);
2662                 goto out_in_multi_locked;
2663         }
2664
2665         CTR1(KTR_IGMPV3, "%s: doing igmp downcall", __func__);
2666         error = igmp_change_state(inm);
2667         if (error)
2668                 CTR1(KTR_IGMPV3, "%s: failed igmp downcall", __func__);
2669
2670 out_in_multi_locked:
2671
2672         IN_MULTI_UNLOCK();
2673
2674 out_imf_rollback:
2675         if (error)
2676                 imf_rollback(imf);
2677         else
2678                 imf_commit(imf);
2679
2680         imf_reap(imf);
2681
2682 out_inp_locked:
2683         INP_WUNLOCK(inp);
2684         return (error);
2685 }
2686
2687 /*
2688  * Set the IP multicast options in response to user setsockopt().
2689  *
2690  * Many of the socket options handled in this function duplicate the
2691  * functionality of socket options in the regular unicast API. However,
2692  * it is not possible to merge the duplicate code, because the idempotence
2693  * of the IPv4 multicast part of the BSD Sockets API must be preserved;
2694  * the effects of these options must be treated as separate and distinct.
2695  *
2696  * SMPng: XXX: Unlocked read of inp_socket believed OK.
2697  * FUTURE: The IP_MULTICAST_VIF option may be eliminated if MROUTING
2698  * is refactored to no longer use vifs.
2699  */
2700 int
2701 inp_setmoptions(struct inpcb *inp, struct sockopt *sopt)
2702 {
2703         struct ip_moptions      *imo;
2704         int                      error;
2705
2706         error = 0;
2707
2708         /*
2709          * If socket is neither of type SOCK_RAW or SOCK_DGRAM,
2710          * or is a divert socket, reject it.
2711          */
2712         if (inp->inp_socket->so_proto->pr_protocol == IPPROTO_DIVERT ||
2713             (inp->inp_socket->so_proto->pr_type != SOCK_RAW &&
2714              inp->inp_socket->so_proto->pr_type != SOCK_DGRAM))
2715                 return (EOPNOTSUPP);
2716
2717         switch (sopt->sopt_name) {
2718         case IP_MULTICAST_VIF: {
2719                 int vifi;
2720                 /*
2721                  * Select a multicast VIF for transmission.
2722                  * Only useful if multicast forwarding is active.
2723                  */
2724                 if (legal_vif_num == NULL) {
2725                         error = EOPNOTSUPP;
2726                         break;
2727                 }
2728                 error = sooptcopyin(sopt, &vifi, sizeof(int), sizeof(int));
2729                 if (error)
2730                         break;
2731                 if (!legal_vif_num(vifi) && (vifi != -1)) {
2732                         error = EINVAL;
2733                         break;
2734                 }
2735                 imo = inp_findmoptions(inp);
2736                 imo->imo_multicast_vif = vifi;
2737                 INP_WUNLOCK(inp);
2738                 break;
2739         }
2740
2741         case IP_MULTICAST_IF:
2742                 error = inp_set_multicast_if(inp, sopt);
2743                 break;
2744
2745         case IP_MULTICAST_TTL: {
2746                 u_char ttl;
2747
2748                 /*
2749                  * Set the IP time-to-live for outgoing multicast packets.
2750                  * The original multicast API required a char argument,
2751                  * which is inconsistent with the rest of the socket API.
2752                  * We allow either a char or an int.
2753                  */
2754                 if (sopt->sopt_valsize == sizeof(u_char)) {
2755                         error = sooptcopyin(sopt, &ttl, sizeof(u_char),
2756                             sizeof(u_char));
2757                         if (error)
2758                                 break;
2759                 } else {
2760                         u_int ittl;
2761
2762                         error = sooptcopyin(sopt, &ittl, sizeof(u_int),
2763                             sizeof(u_int));
2764                         if (error)
2765                                 break;
2766                         if (ittl > 255) {
2767                                 error = EINVAL;
2768                                 break;
2769                         }
2770                         ttl = (u_char)ittl;
2771                 }
2772                 imo = inp_findmoptions(inp);
2773                 imo->imo_multicast_ttl = ttl;
2774                 INP_WUNLOCK(inp);
2775                 break;
2776         }
2777
2778         case IP_MULTICAST_LOOP: {
2779                 u_char loop;
2780
2781                 /*
2782                  * Set the loopback flag for outgoing multicast packets.
2783                  * Must be zero or one.  The original multicast API required a
2784                  * char argument, which is inconsistent with the rest
2785                  * of the socket API.  We allow either a char or an int.
2786                  */
2787                 if (sopt->sopt_valsize == sizeof(u_char)) {
2788                         error = sooptcopyin(sopt, &loop, sizeof(u_char),
2789                             sizeof(u_char));
2790                         if (error)
2791                                 break;
2792                 } else {
2793                         u_int iloop;
2794
2795                         error = sooptcopyin(sopt, &iloop, sizeof(u_int),
2796                                             sizeof(u_int));
2797                         if (error)
2798                                 break;
2799                         loop = (u_char)iloop;
2800                 }
2801                 imo = inp_findmoptions(inp);
2802                 imo->imo_multicast_loop = !!loop;
2803                 INP_WUNLOCK(inp);
2804                 break;
2805         }
2806
2807         case IP_ADD_MEMBERSHIP:
2808         case IP_ADD_SOURCE_MEMBERSHIP:
2809         case MCAST_JOIN_GROUP:
2810         case MCAST_JOIN_SOURCE_GROUP:
2811                 error = inp_join_group(inp, sopt);
2812                 break;
2813
2814         case IP_DROP_MEMBERSHIP:
2815         case IP_DROP_SOURCE_MEMBERSHIP:
2816         case MCAST_LEAVE_GROUP:
2817         case MCAST_LEAVE_SOURCE_GROUP:
2818                 error = inp_leave_group(inp, sopt);
2819                 break;
2820
2821         case IP_BLOCK_SOURCE:
2822         case IP_UNBLOCK_SOURCE:
2823         case MCAST_BLOCK_SOURCE:
2824         case MCAST_UNBLOCK_SOURCE:
2825                 error = inp_block_unblock_source(inp, sopt);
2826                 break;
2827
2828         case IP_MSFILTER:
2829                 error = inp_set_source_filters(inp, sopt);
2830                 break;
2831
2832         default:
2833                 error = EOPNOTSUPP;
2834                 break;
2835         }
2836
2837         INP_UNLOCK_ASSERT(inp);
2838
2839         return (error);
2840 }
2841
2842 /*
2843  * Expose IGMP's multicast filter mode and source list(s) to userland,
2844  * keyed by (ifindex, group).
2845  * The filter mode is written out as a uint32_t, followed by
2846  * 0..n of struct in_addr.
2847  * For use by ifmcstat(8).
2848  * SMPng: NOTE: unlocked read of ifindex space.
2849  */
2850 static int
2851 sysctl_ip_mcast_filters(SYSCTL_HANDLER_ARGS)
2852 {
2853         struct in_addr                   src, group;
2854         struct ifnet                    *ifp;
2855         struct ifmultiaddr              *ifma;
2856         struct in_multi                 *inm;
2857         struct ip_msource               *ims;
2858         int                             *name;
2859         int                              retval;
2860         u_int                            namelen;
2861         uint32_t                         fmode, ifindex;
2862
2863         name = (int *)arg1;
2864         namelen = arg2;
2865
2866         if (req->newptr != NULL)
2867                 return (EPERM);
2868
2869         if (namelen != 2)
2870                 return (EINVAL);
2871
2872         ifindex = name[0];
2873         if (ifindex <= 0 || ifindex > V_if_index) {
2874                 CTR2(KTR_IGMPV3, "%s: ifindex %u out of range",
2875                     __func__, ifindex);
2876                 return (ENOENT);
2877         }
2878
2879         group.s_addr = name[1];
2880         if (!IN_MULTICAST(ntohl(group.s_addr))) {
2881                 CTR2(KTR_IGMPV3, "%s: group 0x%08x is not multicast",
2882                     __func__, ntohl(group.s_addr));
2883                 return (EINVAL);
2884         }
2885
2886         ifp = ifnet_byindex(ifindex);
2887         if (ifp == NULL) {
2888                 CTR2(KTR_IGMPV3, "%s: no ifp for ifindex %u",
2889                     __func__, ifindex);
2890                 return (ENOENT);
2891         }
2892
2893         retval = sysctl_wire_old_buffer(req,
2894             sizeof(uint32_t) + (in_mcast_maxgrpsrc * sizeof(struct in_addr)));
2895         if (retval)
2896                 return (retval);
2897
2898         IN_MULTI_LOCK();
2899
2900         IF_ADDR_RLOCK(ifp);
2901         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2902                 if (ifma->ifma_addr->sa_family != AF_INET ||
2903                     ifma->ifma_protospec == NULL)
2904                         continue;
2905                 inm = (struct in_multi *)ifma->ifma_protospec;
2906                 if (!in_hosteq(inm->inm_addr, group))
2907                         continue;
2908                 fmode = inm->inm_st[1].iss_fmode;
2909                 retval = SYSCTL_OUT(req, &fmode, sizeof(uint32_t));
2910                 if (retval != 0)
2911                         break;
2912                 RB_FOREACH(ims, ip_msource_tree, &inm->inm_srcs) {
2913                         CTR2(KTR_IGMPV3, "%s: visit node 0x%08x", __func__,
2914                             ims->ims_haddr);
2915                         /*
2916                          * Only copy-out sources which are in-mode.
2917                          */
2918                         if (fmode != ims_get_mode(inm, ims, 1)) {
2919                                 CTR1(KTR_IGMPV3, "%s: skip non-in-mode",
2920                                     __func__);
2921                                 continue;
2922                         }
2923                         src.s_addr = htonl(ims->ims_haddr);
2924                         retval = SYSCTL_OUT(req, &src, sizeof(struct in_addr));
2925                         if (retval != 0)
2926                                 break;
2927                 }
2928         }
2929         IF_ADDR_RUNLOCK(ifp);
2930
2931         IN_MULTI_UNLOCK();
2932
2933         return (retval);
2934 }
2935
2936 #if defined(KTR) && (KTR_COMPILE & KTR_IGMPV3)
2937
2938 static const char *inm_modestrs[] = {
2939         [MCAST_UNDEFINED] = "un",
2940         [MCAST_INCLUDE] = "in",
2941         [MCAST_EXCLUDE] = "ex",
2942 };
2943 _Static_assert(MCAST_UNDEFINED == 0 &&
2944                MCAST_EXCLUDE + 1 == nitems(inm_modestrs),
2945                "inm_modestrs: no longer matches #defines");
2946
2947 static const char *
2948 inm_mode_str(const int mode)
2949 {
2950
2951         if (mode >= MCAST_UNDEFINED && mode <= MCAST_EXCLUDE)
2952                 return (inm_modestrs[mode]);
2953         return ("??");
2954 }
2955
2956 static const char *inm_statestrs[] = {
2957         [IGMP_NOT_MEMBER] = "not-member",
2958         [IGMP_SILENT_MEMBER] = "silent",
2959         [IGMP_REPORTING_MEMBER] = "reporting",
2960         [IGMP_IDLE_MEMBER] = "idle",
2961         [IGMP_LAZY_MEMBER] = "lazy",
2962         [IGMP_SLEEPING_MEMBER] = "sleeping",
2963         [IGMP_AWAKENING_MEMBER] = "awakening",
2964         [IGMP_G_QUERY_PENDING_MEMBER] = "query-pending",
2965         [IGMP_SG_QUERY_PENDING_MEMBER] = "sg-query-pending",
2966         [IGMP_LEAVING_MEMBER] = "leaving",
2967 };
2968 _Static_assert(IGMP_NOT_MEMBER == 0 &&
2969                IGMP_LEAVING_MEMBER + 1 == nitems(inm_statestrs),
2970                "inm_statetrs: no longer matches #defines");
2971
2972 static const char *
2973 inm_state_str(const int state)
2974 {
2975
2976         if (state >= IGMP_NOT_MEMBER && state <= IGMP_LEAVING_MEMBER)
2977                 return (inm_statestrs[state]);
2978         return ("??");
2979 }
2980
2981 /*
2982  * Dump an in_multi structure to the console.
2983  */
2984 void
2985 inm_print(const struct in_multi *inm)
2986 {
2987         int t;
2988         char addrbuf[INET_ADDRSTRLEN];
2989
2990         if ((ktr_mask & KTR_IGMPV3) == 0)
2991                 return;
2992
2993         printf("%s: --- begin inm %p ---\n", __func__, inm);
2994         printf("addr %s ifp %p(%s) ifma %p\n",
2995             inet_ntoa_r(inm->inm_addr, addrbuf),
2996             inm->inm_ifp,
2997             inm->inm_ifp->if_xname,
2998             inm->inm_ifma);
2999         printf("timer %u state %s refcount %u scq.len %u\n",
3000             inm->inm_timer,
3001             inm_state_str(inm->inm_state),
3002             inm->inm_refcount,
3003             inm->inm_scq.mq_len);
3004         printf("igi %p nsrc %lu sctimer %u scrv %u\n",
3005             inm->inm_igi,
3006             inm->inm_nsrc,
3007             inm->inm_sctimer,
3008             inm->inm_scrv);
3009         for (t = 0; t < 2; t++) {
3010                 printf("t%d: fmode %s asm %u ex %u in %u rec %u\n", t,
3011                     inm_mode_str(inm->inm_st[t].iss_fmode),
3012                     inm->inm_st[t].iss_asm,
3013                     inm->inm_st[t].iss_ex,
3014                     inm->inm_st[t].iss_in,
3015                     inm->inm_st[t].iss_rec);
3016         }
3017         printf("%s: --- end inm %p ---\n", __func__, inm);
3018 }
3019
3020 #else /* !KTR || !(KTR_COMPILE & KTR_IGMPV3) */
3021
3022 void
3023 inm_print(const struct in_multi *inm)
3024 {
3025
3026 }
3027
3028 #endif /* KTR && (KTR_COMPILE & KTR_IGMPV3) */
3029
3030 RB_GENERATE(ip_msource_tree, ip_msource, ims_link, ip_msource_cmp);