]> git.saurik.com Git - apple/xnu.git/blame_incremental - bsd/netinet/in_mcast.c
xnu-6153.61.1.tar.gz
[apple/xnu.git] / bsd / netinet / in_mcast.c
... / ...
CommitLineData
1/*
2 * Copyright (c) 2010-2017 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28/*-
29 * Copyright (c) 2007-2009 Bruce Simpson.
30 * Copyright (c) 2005 Robert N. M. Watson.
31 * All rights reserved.
32 *
33 * Redistribution and use in source and binary forms, with or without
34 * modification, are permitted provided that the following conditions
35 * are met:
36 * 1. Redistributions of source code must retain the above copyright
37 * notice, this list of conditions and the following disclaimer.
38 * 2. Redistributions in binary form must reproduce the above copyright
39 * notice, this list of conditions and the following disclaimer in the
40 * documentation and/or other materials provided with the distribution.
41 * 3. The name of the author may not be used to endorse or promote
42 * products derived from this software without specific prior written
43 * permission.
44 *
45 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
46 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
49 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55 * SUCH DAMAGE.
56 */
57
58/*
59 * IPv4 multicast socket, group, and socket option processing module.
60 */
61
62#include <sys/cdefs.h>
63
64#include <sys/param.h>
65#include <sys/systm.h>
66#include <sys/kernel.h>
67#include <sys/malloc.h>
68#include <sys/mbuf.h>
69#include <sys/protosw.h>
70#include <sys/socket.h>
71#include <sys/socketvar.h>
72#include <sys/protosw.h>
73#include <sys/sysctl.h>
74#include <sys/tree.h>
75#include <sys/mcache.h>
76
77#include <kern/zalloc.h>
78
79#include <pexpert/pexpert.h>
80
81#include <net/if.h>
82#include <net/if_dl.h>
83#include <net/net_api_stats.h>
84#include <net/route.h>
85
86#include <netinet/in.h>
87#include <netinet/in_systm.h>
88#include <netinet/in_pcb.h>
89#include <netinet/in_var.h>
90#include <netinet/ip_var.h>
91#include <netinet/igmp_var.h>
92
93/*
94 * Functions with non-static linkage defined in this file should be
95 * declared in in_var.h:
96 * imo_multi_filter()
97 * in_addmulti()
98 * in_delmulti()
99 * in_joingroup()
100 * in_leavegroup()
101 * and ip_var.h:
102 * inp_freemoptions()
103 * inp_getmoptions()
104 * inp_setmoptions()
105 *
106 * XXX: Both carp and pf need to use the legacy (*,G) KPIs in_addmulti()
107 * and in_delmulti().
108 */
109static void imf_commit(struct in_mfilter *);
110static int imf_get_source(struct in_mfilter *imf,
111 const struct sockaddr_in *psin,
112 struct in_msource **);
113static struct in_msource *
114imf_graft(struct in_mfilter *, const uint8_t,
115 const struct sockaddr_in *);
116static int imf_prune(struct in_mfilter *, const struct sockaddr_in *);
117static void imf_rollback(struct in_mfilter *);
118static void imf_reap(struct in_mfilter *);
119static int imo_grow(struct ip_moptions *, size_t);
120static size_t imo_match_group(const struct ip_moptions *,
121 const struct ifnet *, const struct sockaddr_in *);
122static struct in_msource *
123imo_match_source(const struct ip_moptions *, const size_t,
124 const struct sockaddr_in *);
125static void ims_merge(struct ip_msource *ims,
126 const struct in_msource *lims, const int rollback);
127static int in_getmulti(struct ifnet *, const struct in_addr *,
128 struct in_multi **);
129static int in_joingroup(struct ifnet *, const struct in_addr *,
130 struct in_mfilter *, struct in_multi **);
131static int inm_get_source(struct in_multi *inm, const in_addr_t haddr,
132 const int noalloc, struct ip_msource **pims);
133static int inm_is_ifp_detached(const struct in_multi *);
134static int inm_merge(struct in_multi *, /*const*/ struct in_mfilter *);
135static void inm_reap(struct in_multi *);
136static struct ip_moptions *
137inp_findmoptions(struct inpcb *);
138static int inp_get_source_filters(struct inpcb *, struct sockopt *);
139static struct ifnet *
140inp_lookup_mcast_ifp(const struct inpcb *,
141 const struct sockaddr_in *, const struct in_addr);
142static int inp_block_unblock_source(struct inpcb *, struct sockopt *);
143static int inp_set_multicast_if(struct inpcb *, struct sockopt *);
144static int inp_set_source_filters(struct inpcb *, struct sockopt *);
145static int sysctl_ip_mcast_filters SYSCTL_HANDLER_ARGS;
146static struct ifnet * ip_multicast_if(struct in_addr *, unsigned int *);
147static __inline__ int ip_msource_cmp(const struct ip_msource *,
148 const struct ip_msource *);
149
150SYSCTL_NODE(_net_inet_ip, OID_AUTO, mcast, CTLFLAG_RW | CTLFLAG_LOCKED, 0, "IPv4 multicast");
151
152static u_long in_mcast_maxgrpsrc = IP_MAX_GROUP_SRC_FILTER;
153SYSCTL_LONG(_net_inet_ip_mcast, OID_AUTO, maxgrpsrc,
154 CTLFLAG_RW | CTLFLAG_LOCKED, &in_mcast_maxgrpsrc, "Max source filters per group");
155
156static u_long in_mcast_maxsocksrc = IP_MAX_SOCK_SRC_FILTER;
157SYSCTL_LONG(_net_inet_ip_mcast, OID_AUTO, maxsocksrc,
158 CTLFLAG_RW | CTLFLAG_LOCKED, &in_mcast_maxsocksrc,
159 "Max source filters per socket");
160
161int in_mcast_loop = IP_DEFAULT_MULTICAST_LOOP;
162SYSCTL_INT(_net_inet_ip_mcast, OID_AUTO, loop, CTLFLAG_RW | CTLFLAG_LOCKED,
163 &in_mcast_loop, 0, "Loopback multicast datagrams by default");
164
165SYSCTL_NODE(_net_inet_ip_mcast, OID_AUTO, filters,
166 CTLFLAG_RD | CTLFLAG_LOCKED, sysctl_ip_mcast_filters,
167 "Per-interface stack-wide source filters");
168
169RB_GENERATE_PREV(ip_msource_tree, ip_msource, ims_link, ip_msource_cmp);
170
171#define INM_TRACE_HIST_SIZE 32 /* size of trace history */
172
173/* For gdb */
174__private_extern__ unsigned int inm_trace_hist_size = INM_TRACE_HIST_SIZE;
175
176struct in_multi_dbg {
177 struct in_multi inm; /* in_multi */
178 u_int16_t inm_refhold_cnt; /* # of ref */
179 u_int16_t inm_refrele_cnt; /* # of rele */
180 /*
181 * Circular lists of inm_addref and inm_remref callers.
182 */
183 ctrace_t inm_refhold[INM_TRACE_HIST_SIZE];
184 ctrace_t inm_refrele[INM_TRACE_HIST_SIZE];
185 /*
186 * Trash list linkage
187 */
188 TAILQ_ENTRY(in_multi_dbg) inm_trash_link;
189};
190
191/* List of trash in_multi entries protected by inm_trash_lock */
192static TAILQ_HEAD(, in_multi_dbg) inm_trash_head;
193static decl_lck_mtx_data(, inm_trash_lock);
194
195#define INM_ZONE_MAX 64 /* maximum elements in zone */
196#define INM_ZONE_NAME "in_multi" /* zone name */
197
198#if DEBUG
199static unsigned int inm_debug = 1; /* debugging (enabled) */
200#else
201static unsigned int inm_debug; /* debugging (disabled) */
202#endif /* !DEBUG */
203static unsigned int inm_size; /* size of zone element */
204static struct zone *inm_zone; /* zone for in_multi */
205
206#define IPMS_ZONE_MAX 64 /* maximum elements in zone */
207#define IPMS_ZONE_NAME "ip_msource" /* zone name */
208
209static unsigned int ipms_size; /* size of zone element */
210static struct zone *ipms_zone; /* zone for ip_msource */
211
212#define INMS_ZONE_MAX 64 /* maximum elements in zone */
213#define INMS_ZONE_NAME "in_msource" /* zone name */
214
215static unsigned int inms_size; /* size of zone element */
216static struct zone *inms_zone; /* zone for in_msource */
217
218/* Lock group and attribute for in_multihead_lock lock */
219static lck_attr_t *in_multihead_lock_attr;
220static lck_grp_t *in_multihead_lock_grp;
221static lck_grp_attr_t *in_multihead_lock_grp_attr;
222
223static decl_lck_rw_data(, in_multihead_lock);
224struct in_multihead in_multihead;
225
226static struct in_multi *in_multi_alloc(int);
227static void in_multi_free(struct in_multi *);
228static void in_multi_attach(struct in_multi *);
229static void inm_trace(struct in_multi *, int);
230
231static struct ip_msource *ipms_alloc(int);
232static void ipms_free(struct ip_msource *);
233static struct in_msource *inms_alloc(int);
234static void inms_free(struct in_msource *);
235
236static __inline int
237ip_msource_cmp(const struct ip_msource *a, const struct ip_msource *b)
238{
239 if (a->ims_haddr < b->ims_haddr) {
240 return -1;
241 }
242 if (a->ims_haddr == b->ims_haddr) {
243 return 0;
244 }
245 return 1;
246}
247
248/*
249 * Inline function which wraps assertions for a valid ifp.
250 */
251static __inline__ int
252inm_is_ifp_detached(const struct in_multi *inm)
253{
254 VERIFY(inm->inm_ifma != NULL);
255 VERIFY(inm->inm_ifp == inm->inm_ifma->ifma_ifp);
256
257 return !ifnet_is_attached(inm->inm_ifp, 0);
258}
259
260/*
261 * Initialize an in_mfilter structure to a known state at t0, t1
262 * with an empty source filter list.
263 */
264static __inline__ void
265imf_init(struct in_mfilter *imf, const int st0, const int st1)
266{
267 memset(imf, 0, sizeof(struct in_mfilter));
268 RB_INIT(&imf->imf_sources);
269 imf->imf_st[0] = st0;
270 imf->imf_st[1] = st1;
271}
272
273/*
274 * Resize the ip_moptions vector to the next power-of-two minus 1.
275 */
276static int
277imo_grow(struct ip_moptions *imo, size_t newmax)
278{
279 struct in_multi **nmships;
280 struct in_multi **omships;
281 struct in_mfilter *nmfilters;
282 struct in_mfilter *omfilters;
283 size_t idx;
284 size_t oldmax;
285
286 IMO_LOCK_ASSERT_HELD(imo);
287
288 nmships = NULL;
289 nmfilters = NULL;
290 omships = imo->imo_membership;
291 omfilters = imo->imo_mfilters;
292 oldmax = imo->imo_max_memberships;
293 if (newmax == 0) {
294 newmax = ((oldmax + 1) * 2) - 1;
295 }
296
297 if (newmax > IP_MAX_MEMBERSHIPS) {
298 return ETOOMANYREFS;
299 }
300
301 if ((nmships = (struct in_multi **)_REALLOC(omships,
302 sizeof(struct in_multi *) * newmax, M_IPMOPTS,
303 M_WAITOK | M_ZERO)) == NULL) {
304 return ENOMEM;
305 }
306
307 imo->imo_membership = nmships;
308
309 if ((nmfilters = (struct in_mfilter *)_REALLOC(omfilters,
310 sizeof(struct in_mfilter) * newmax, M_INMFILTER,
311 M_WAITOK | M_ZERO)) == NULL) {
312 return ENOMEM;
313 }
314
315 imo->imo_mfilters = nmfilters;
316
317 /* Initialize newly allocated source filter heads. */
318 for (idx = oldmax; idx < newmax; idx++) {
319 imf_init(&nmfilters[idx], MCAST_UNDEFINED, MCAST_EXCLUDE);
320 }
321
322 imo->imo_max_memberships = newmax;
323
324 return 0;
325}
326
327/*
328 * Find an IPv4 multicast group entry for this ip_moptions instance
329 * which matches the specified group, and optionally an interface.
330 * Return its index into the array, or -1 if not found.
331 */
332static size_t
333imo_match_group(const struct ip_moptions *imo, const struct ifnet *ifp,
334 const struct sockaddr_in *group)
335{
336 struct in_multi *pinm;
337 int idx;
338 int nmships;
339
340 IMO_LOCK_ASSERT_HELD(__DECONST(struct ip_moptions *, imo));
341
342
343 /* The imo_membership array may be lazy allocated. */
344 if (imo->imo_membership == NULL || imo->imo_num_memberships == 0) {
345 return -1;
346 }
347
348 nmships = imo->imo_num_memberships;
349 for (idx = 0; idx < nmships; idx++) {
350 pinm = imo->imo_membership[idx];
351 if (pinm == NULL) {
352 continue;
353 }
354 INM_LOCK(pinm);
355 if ((ifp == NULL || (pinm->inm_ifp == ifp)) &&
356 in_hosteq(pinm->inm_addr, group->sin_addr)) {
357 INM_UNLOCK(pinm);
358 break;
359 }
360 INM_UNLOCK(pinm);
361 }
362 if (idx >= nmships) {
363 idx = -1;
364 }
365
366 return idx;
367}
368
369/*
370 * Find an IPv4 multicast source entry for this imo which matches
371 * the given group index for this socket, and source address.
372 *
373 * NOTE: This does not check if the entry is in-mode, merely if
374 * it exists, which may not be the desired behaviour.
375 */
376static struct in_msource *
377imo_match_source(const struct ip_moptions *imo, const size_t gidx,
378 const struct sockaddr_in *src)
379{
380 struct ip_msource find;
381 struct in_mfilter *imf;
382 struct ip_msource *ims;
383
384 IMO_LOCK_ASSERT_HELD(__DECONST(struct ip_moptions *, imo));
385
386 VERIFY(src->sin_family == AF_INET);
387 VERIFY(gidx != (size_t)-1 && gidx < imo->imo_num_memberships);
388
389 /* The imo_mfilters array may be lazy allocated. */
390 if (imo->imo_mfilters == NULL) {
391 return NULL;
392 }
393 imf = &imo->imo_mfilters[gidx];
394
395 /* Source trees are keyed in host byte order. */
396 find.ims_haddr = ntohl(src->sin_addr.s_addr);
397 ims = RB_FIND(ip_msource_tree, &imf->imf_sources, &find);
398
399 return (struct in_msource *)ims;
400}
401
402/*
403 * Perform filtering for multicast datagrams on a socket by group and source.
404 *
405 * Returns 0 if a datagram should be allowed through, or various error codes
406 * if the socket was not a member of the group, or the source was muted, etc.
407 */
408int
409imo_multi_filter(const struct ip_moptions *imo, const struct ifnet *ifp,
410 const struct sockaddr_in *group, const struct sockaddr_in *src)
411{
412 size_t gidx;
413 struct in_msource *ims;
414 int mode;
415
416 IMO_LOCK_ASSERT_HELD(__DECONST(struct ip_moptions *, imo));
417 VERIFY(ifp != NULL);
418
419 gidx = imo_match_group(imo, ifp, group);
420 if (gidx == (size_t)-1) {
421 return MCAST_NOTGMEMBER;
422 }
423
424 /*
425 * Check if the source was included in an (S,G) join.
426 * Allow reception on exclusive memberships by default,
427 * reject reception on inclusive memberships by default.
428 * Exclude source only if an in-mode exclude filter exists.
429 * Include source only if an in-mode include filter exists.
430 * NOTE: We are comparing group state here at IGMP t1 (now)
431 * with socket-layer t0 (since last downcall).
432 */
433 mode = imo->imo_mfilters[gidx].imf_st[1];
434 ims = imo_match_source(imo, gidx, src);
435
436 if ((ims == NULL && mode == MCAST_INCLUDE) ||
437 (ims != NULL && ims->imsl_st[0] != mode)) {
438 return MCAST_NOTSMEMBER;
439 }
440
441 return MCAST_PASS;
442}
443
444int
445imo_clone(struct inpcb *from_inp, struct inpcb *to_inp)
446{
447 int i, err = 0;
448 struct ip_moptions *from;
449 struct ip_moptions *to;
450
451 from = inp_findmoptions(from_inp);
452 if (from == NULL) {
453 return ENOMEM;
454 }
455
456 to = inp_findmoptions(to_inp);
457 if (to == NULL) {
458 IMO_REMREF(from);
459 return ENOMEM;
460 }
461
462 IMO_LOCK(from);
463 IMO_LOCK(to);
464
465 to->imo_multicast_ifp = from->imo_multicast_ifp;
466 to->imo_multicast_vif = from->imo_multicast_vif;
467 to->imo_multicast_ttl = from->imo_multicast_ttl;
468 to->imo_multicast_loop = from->imo_multicast_loop;
469
470 /*
471 * We're cloning, so drop any existing memberships and source
472 * filters on the destination ip_moptions.
473 */
474 for (i = 0; i < to->imo_num_memberships; ++i) {
475 struct in_mfilter *imf;
476
477 imf = to->imo_mfilters ? &to->imo_mfilters[i] : NULL;
478 if (imf != NULL) {
479 imf_leave(imf);
480 }
481
482 (void) in_leavegroup(to->imo_membership[i], imf);
483
484 if (imf != NULL) {
485 imf_purge(imf);
486 }
487
488 INM_REMREF(to->imo_membership[i]);
489 to->imo_membership[i] = NULL;
490 }
491 to->imo_num_memberships = 0;
492
493 VERIFY(to->imo_max_memberships != 0 && from->imo_max_memberships != 0);
494 if (to->imo_max_memberships < from->imo_max_memberships) {
495 /*
496 * Ensure source and destination ip_moptions memberships
497 * and source filters arrays are at least equal in size.
498 */
499 err = imo_grow(to, from->imo_max_memberships);
500 if (err != 0) {
501 goto done;
502 }
503 }
504 VERIFY(to->imo_max_memberships >= from->imo_max_memberships);
505
506 /*
507 * Source filtering doesn't apply to OpenTransport socket,
508 * so simply hold additional reference count per membership.
509 */
510 for (i = 0; i < from->imo_num_memberships; i++) {
511 to->imo_membership[i] =
512 in_addmulti(&from->imo_membership[i]->inm_addr,
513 from->imo_membership[i]->inm_ifp);
514 if (to->imo_membership[i] == NULL) {
515 break;
516 }
517 to->imo_num_memberships++;
518 }
519 VERIFY(to->imo_num_memberships == from->imo_num_memberships);
520
521done:
522 IMO_UNLOCK(to);
523 IMO_REMREF(to);
524 IMO_UNLOCK(from);
525 IMO_REMREF(from);
526
527 return err;
528}
529
530/*
531 * Find and return a reference to an in_multi record for (ifp, group),
532 * and bump its reference count.
533 * If one does not exist, try to allocate it, and update link-layer multicast
534 * filters on ifp to listen for group.
535 * Return 0 if successful, otherwise return an appropriate error code.
536 */
537static int
538in_getmulti(struct ifnet *ifp, const struct in_addr *group,
539 struct in_multi **pinm)
540{
541 struct sockaddr_in gsin;
542 struct ifmultiaddr *ifma;
543 struct in_multi *inm;
544 int error;
545
546 in_multihead_lock_shared();
547 IN_LOOKUP_MULTI(group, ifp, inm);
548 if (inm != NULL) {
549 INM_LOCK(inm);
550 VERIFY(inm->inm_reqcnt >= 1);
551 inm->inm_reqcnt++;
552 VERIFY(inm->inm_reqcnt != 0);
553 *pinm = inm;
554 INM_UNLOCK(inm);
555 in_multihead_lock_done();
556 /*
557 * We already joined this group; return the inm
558 * with a refcount held (via lookup) for caller.
559 */
560 return 0;
561 }
562 in_multihead_lock_done();
563
564 bzero(&gsin, sizeof(gsin));
565 gsin.sin_family = AF_INET;
566 gsin.sin_len = sizeof(struct sockaddr_in);
567 gsin.sin_addr = *group;
568
569 /*
570 * Check if a link-layer group is already associated
571 * with this network-layer group on the given ifnet.
572 */
573 error = if_addmulti(ifp, (struct sockaddr *)&gsin, &ifma);
574 if (error != 0) {
575 return error;
576 }
577
578 /*
579 * See comments in inm_remref() for access to ifma_protospec.
580 */
581 in_multihead_lock_exclusive();
582 IFMA_LOCK(ifma);
583 if ((inm = ifma->ifma_protospec) != NULL) {
584 VERIFY(ifma->ifma_addr != NULL);
585 VERIFY(ifma->ifma_addr->sa_family == AF_INET);
586 INM_ADDREF(inm); /* for caller */
587 IFMA_UNLOCK(ifma);
588 INM_LOCK(inm);
589 VERIFY(inm->inm_ifma == ifma);
590 VERIFY(inm->inm_ifp == ifp);
591 VERIFY(in_hosteq(inm->inm_addr, *group));
592 if (inm->inm_debug & IFD_ATTACHED) {
593 VERIFY(inm->inm_reqcnt >= 1);
594 inm->inm_reqcnt++;
595 VERIFY(inm->inm_reqcnt != 0);
596 *pinm = inm;
597 INM_UNLOCK(inm);
598 in_multihead_lock_done();
599 IFMA_REMREF(ifma);
600 /*
601 * We lost the race with another thread doing
602 * in_getmulti(); since this group has already
603 * been joined; return the inm with a refcount
604 * held for caller.
605 */
606 return 0;
607 }
608 /*
609 * We lost the race with another thread doing in_delmulti();
610 * the inm referring to the ifma has been detached, thus we
611 * reattach it back to the in_multihead list and return the
612 * inm with a refcount held for the caller.
613 */
614 in_multi_attach(inm);
615 VERIFY((inm->inm_debug &
616 (IFD_ATTACHED | IFD_TRASHED)) == IFD_ATTACHED);
617 *pinm = inm;
618 INM_UNLOCK(inm);
619 in_multihead_lock_done();
620 IFMA_REMREF(ifma);
621 return 0;
622 }
623 IFMA_UNLOCK(ifma);
624
625 /*
626 * A new in_multi record is needed; allocate and initialize it.
627 * We DO NOT perform an IGMP join as the in_ layer may need to
628 * push an initial source list down to IGMP to support SSM.
629 *
630 * The initial source filter state is INCLUDE, {} as per the RFC.
631 */
632 inm = in_multi_alloc(M_WAITOK);
633 if (inm == NULL) {
634 in_multihead_lock_done();
635 IFMA_REMREF(ifma);
636 return ENOMEM;
637 }
638 INM_LOCK(inm);
639 inm->inm_addr = *group;
640 inm->inm_ifp = ifp;
641 inm->inm_igi = IGMP_IFINFO(ifp);
642 VERIFY(inm->inm_igi != NULL);
643 IGI_ADDREF(inm->inm_igi);
644 inm->inm_ifma = ifma; /* keep refcount from if_addmulti() */
645 inm->inm_state = IGMP_NOT_MEMBER;
646 /*
647 * Pending state-changes per group are subject to a bounds check.
648 */
649 inm->inm_scq.ifq_maxlen = IGMP_MAX_STATE_CHANGES;
650 inm->inm_st[0].iss_fmode = MCAST_UNDEFINED;
651 inm->inm_st[1].iss_fmode = MCAST_UNDEFINED;
652 RB_INIT(&inm->inm_srcs);
653 *pinm = inm;
654 in_multi_attach(inm);
655 VERIFY((inm->inm_debug & (IFD_ATTACHED | IFD_TRASHED)) == IFD_ATTACHED);
656 INM_ADDREF_LOCKED(inm); /* for caller */
657 INM_UNLOCK(inm);
658
659 IFMA_LOCK(ifma);
660 VERIFY(ifma->ifma_protospec == NULL);
661 ifma->ifma_protospec = inm;
662 IFMA_UNLOCK(ifma);
663 in_multihead_lock_done();
664
665 return 0;
666}
667
668/*
669 * Clear recorded source entries for a group.
670 * Used by the IGMP code.
671 * FIXME: Should reap.
672 */
673void
674inm_clear_recorded(struct in_multi *inm)
675{
676 struct ip_msource *ims;
677
678 INM_LOCK_ASSERT_HELD(inm);
679
680 RB_FOREACH(ims, ip_msource_tree, &inm->inm_srcs) {
681 if (ims->ims_stp) {
682 ims->ims_stp = 0;
683 --inm->inm_st[1].iss_rec;
684 }
685 }
686 VERIFY(inm->inm_st[1].iss_rec == 0);
687}
688
689/*
690 * Record a source as pending for a Source-Group IGMPv3 query.
691 * This lives here as it modifies the shared tree.
692 *
693 * inm is the group descriptor.
694 * naddr is the address of the source to record in network-byte order.
695 *
696 * If the net.inet.igmp.sgalloc sysctl is non-zero, we will
697 * lazy-allocate a source node in response to an SG query.
698 * Otherwise, no allocation is performed. This saves some memory
699 * with the trade-off that the source will not be reported to the
700 * router if joined in the window between the query response and
701 * the group actually being joined on the local host.
702 *
703 * Return 0 if the source didn't exist or was already marked as recorded.
704 * Return 1 if the source was marked as recorded by this function.
705 * Return <0 if any error occured (negated errno code).
706 */
707int
708inm_record_source(struct in_multi *inm, const in_addr_t naddr)
709{
710 struct ip_msource find;
711 struct ip_msource *ims, *nims;
712
713 INM_LOCK_ASSERT_HELD(inm);
714
715 find.ims_haddr = ntohl(naddr);
716 ims = RB_FIND(ip_msource_tree, &inm->inm_srcs, &find);
717 if (ims && ims->ims_stp) {
718 return 0;
719 }
720 if (ims == NULL) {
721 if (inm->inm_nsrc == in_mcast_maxgrpsrc) {
722 return -ENOSPC;
723 }
724 nims = ipms_alloc(M_WAITOK);
725 if (nims == NULL) {
726 return -ENOMEM;
727 }
728 nims->ims_haddr = find.ims_haddr;
729 RB_INSERT(ip_msource_tree, &inm->inm_srcs, nims);
730 ++inm->inm_nsrc;
731 ims = nims;
732 }
733
734 /*
735 * Mark the source as recorded and update the recorded
736 * source count.
737 */
738 ++ims->ims_stp;
739 ++inm->inm_st[1].iss_rec;
740
741 return 1;
742}
743
744/*
745 * Return a pointer to an in_msource owned by an in_mfilter,
746 * given its source address.
747 * Lazy-allocate if needed. If this is a new entry its filter state is
748 * undefined at t0.
749 *
750 * imf is the filter set being modified.
751 * haddr is the source address in *host* byte-order.
752 *
753 * Caller is expected to be holding imo_lock.
754 */
755static int
756imf_get_source(struct in_mfilter *imf, const struct sockaddr_in *psin,
757 struct in_msource **plims)
758{
759 struct ip_msource find;
760 struct ip_msource *ims;
761 struct in_msource *lims;
762 int error;
763
764 error = 0;
765 ims = NULL;
766 lims = NULL;
767
768 /* key is host byte order */
769 find.ims_haddr = ntohl(psin->sin_addr.s_addr);
770 ims = RB_FIND(ip_msource_tree, &imf->imf_sources, &find);
771 lims = (struct in_msource *)ims;
772 if (lims == NULL) {
773 if (imf->imf_nsrc == in_mcast_maxsocksrc) {
774 return ENOSPC;
775 }
776 lims = inms_alloc(M_WAITOK);
777 if (lims == NULL) {
778 return ENOMEM;
779 }
780 lims->ims_haddr = find.ims_haddr;
781 lims->imsl_st[0] = MCAST_UNDEFINED;
782 RB_INSERT(ip_msource_tree, &imf->imf_sources,
783 (struct ip_msource *)lims);
784 ++imf->imf_nsrc;
785 }
786
787 *plims = lims;
788
789 return error;
790}
791
792/*
793 * Graft a source entry into an existing socket-layer filter set,
794 * maintaining any required invariants and checking allocations.
795 *
796 * The source is marked as being in the new filter mode at t1.
797 *
798 * Return the pointer to the new node, otherwise return NULL.
799 *
800 * Caller is expected to be holding imo_lock.
801 */
802static struct in_msource *
803imf_graft(struct in_mfilter *imf, const uint8_t st1,
804 const struct sockaddr_in *psin)
805{
806 struct in_msource *lims;
807
808 lims = inms_alloc(M_WAITOK);
809 if (lims == NULL) {
810 return NULL;
811 }
812 lims->ims_haddr = ntohl(psin->sin_addr.s_addr);
813 lims->imsl_st[0] = MCAST_UNDEFINED;
814 lims->imsl_st[1] = st1;
815 RB_INSERT(ip_msource_tree, &imf->imf_sources,
816 (struct ip_msource *)lims);
817 ++imf->imf_nsrc;
818
819 return lims;
820}
821
822/*
823 * Prune a source entry from an existing socket-layer filter set,
824 * maintaining any required invariants and checking allocations.
825 *
826 * The source is marked as being left at t1, it is not freed.
827 *
828 * Return 0 if no error occurred, otherwise return an errno value.
829 *
830 * Caller is expected to be holding imo_lock.
831 */
832static int
833imf_prune(struct in_mfilter *imf, const struct sockaddr_in *psin)
834{
835 struct ip_msource find;
836 struct ip_msource *ims;
837 struct in_msource *lims;
838
839 /* key is host byte order */
840 find.ims_haddr = ntohl(psin->sin_addr.s_addr);
841 ims = RB_FIND(ip_msource_tree, &imf->imf_sources, &find);
842 if (ims == NULL) {
843 return ENOENT;
844 }
845 lims = (struct in_msource *)ims;
846 lims->imsl_st[1] = MCAST_UNDEFINED;
847 return 0;
848}
849
850/*
851 * Revert socket-layer filter set deltas at t1 to t0 state.
852 *
853 * Caller is expected to be holding imo_lock.
854 */
855static void
856imf_rollback(struct in_mfilter *imf)
857{
858 struct ip_msource *ims, *tims;
859 struct in_msource *lims;
860
861 RB_FOREACH_SAFE(ims, ip_msource_tree, &imf->imf_sources, tims) {
862 lims = (struct in_msource *)ims;
863 if (lims->imsl_st[0] == lims->imsl_st[1]) {
864 /* no change at t1 */
865 continue;
866 } else if (lims->imsl_st[0] != MCAST_UNDEFINED) {
867 /* revert change to existing source at t1 */
868 lims->imsl_st[1] = lims->imsl_st[0];
869 } else {
870 /* revert source added t1 */
871 IGMP_PRINTF(("%s: free inms 0x%llx\n", __func__,
872 (uint64_t)VM_KERNEL_ADDRPERM(lims)));
873 RB_REMOVE(ip_msource_tree, &imf->imf_sources, ims);
874 inms_free(lims);
875 imf->imf_nsrc--;
876 }
877 }
878 imf->imf_st[1] = imf->imf_st[0];
879}
880
881/*
882 * Mark socket-layer filter set as INCLUDE {} at t1.
883 *
884 * Caller is expected to be holding imo_lock.
885 */
886void
887imf_leave(struct in_mfilter *imf)
888{
889 struct ip_msource *ims;
890 struct in_msource *lims;
891
892 RB_FOREACH(ims, ip_msource_tree, &imf->imf_sources) {
893 lims = (struct in_msource *)ims;
894 lims->imsl_st[1] = MCAST_UNDEFINED;
895 }
896 imf->imf_st[1] = MCAST_INCLUDE;
897}
898
899/*
900 * Mark socket-layer filter set deltas as committed.
901 *
902 * Caller is expected to be holding imo_lock.
903 */
904static void
905imf_commit(struct in_mfilter *imf)
906{
907 struct ip_msource *ims;
908 struct in_msource *lims;
909
910 RB_FOREACH(ims, ip_msource_tree, &imf->imf_sources) {
911 lims = (struct in_msource *)ims;
912 lims->imsl_st[0] = lims->imsl_st[1];
913 }
914 imf->imf_st[0] = imf->imf_st[1];
915}
916
917/*
918 * Reap unreferenced sources from socket-layer filter set.
919 *
920 * Caller is expected to be holding imo_lock.
921 */
922static void
923imf_reap(struct in_mfilter *imf)
924{
925 struct ip_msource *ims, *tims;
926 struct in_msource *lims;
927
928 RB_FOREACH_SAFE(ims, ip_msource_tree, &imf->imf_sources, tims) {
929 lims = (struct in_msource *)ims;
930 if ((lims->imsl_st[0] == MCAST_UNDEFINED) &&
931 (lims->imsl_st[1] == MCAST_UNDEFINED)) {
932 IGMP_PRINTF(("%s: free inms 0x%llx\n", __func__,
933 (uint64_t)VM_KERNEL_ADDRPERM(lims)));
934 RB_REMOVE(ip_msource_tree, &imf->imf_sources, ims);
935 inms_free(lims);
936 imf->imf_nsrc--;
937 }
938 }
939}
940
941/*
942 * Purge socket-layer filter set.
943 *
944 * Caller is expected to be holding imo_lock.
945 */
946void
947imf_purge(struct in_mfilter *imf)
948{
949 struct ip_msource *ims, *tims;
950 struct in_msource *lims;
951
952 RB_FOREACH_SAFE(ims, ip_msource_tree, &imf->imf_sources, tims) {
953 lims = (struct in_msource *)ims;
954 IGMP_PRINTF(("%s: free inms 0x%llx\n", __func__,
955 (uint64_t)VM_KERNEL_ADDRPERM(lims)));
956 RB_REMOVE(ip_msource_tree, &imf->imf_sources, ims);
957 inms_free(lims);
958 imf->imf_nsrc--;
959 }
960 imf->imf_st[0] = imf->imf_st[1] = MCAST_UNDEFINED;
961 VERIFY(RB_EMPTY(&imf->imf_sources));
962}
963
964/*
965 * Look up a source filter entry for a multicast group.
966 *
967 * inm is the group descriptor to work with.
968 * haddr is the host-byte-order IPv4 address to look up.
969 * noalloc may be non-zero to suppress allocation of sources.
970 * *pims will be set to the address of the retrieved or allocated source.
971 *
972 * Return 0 if successful, otherwise return a non-zero error code.
973 */
974static int
975inm_get_source(struct in_multi *inm, const in_addr_t haddr,
976 const int noalloc, struct ip_msource **pims)
977{
978 struct ip_msource find;
979 struct ip_msource *ims, *nims;
980#ifdef IGMP_DEBUG
981 struct in_addr ia;
982 char buf[MAX_IPv4_STR_LEN];
983#endif
984 INM_LOCK_ASSERT_HELD(inm);
985
986 find.ims_haddr = haddr;
987 ims = RB_FIND(ip_msource_tree, &inm->inm_srcs, &find);
988 if (ims == NULL && !noalloc) {
989 if (inm->inm_nsrc == in_mcast_maxgrpsrc) {
990 return ENOSPC;
991 }
992 nims = ipms_alloc(M_WAITOK);
993 if (nims == NULL) {
994 return ENOMEM;
995 }
996 nims->ims_haddr = haddr;
997 RB_INSERT(ip_msource_tree, &inm->inm_srcs, nims);
998 ++inm->inm_nsrc;
999 ims = nims;
1000#ifdef IGMP_DEBUG
1001 ia.s_addr = htonl(haddr);
1002 inet_ntop(AF_INET, &ia, buf, sizeof(buf));
1003 IGMP_PRINTF(("%s: allocated %s as 0x%llx\n", __func__,
1004 buf, (uint64_t)VM_KERNEL_ADDRPERM(ims)));
1005#endif
1006 }
1007
1008 *pims = ims;
1009 return 0;
1010}
1011
1012/*
1013 * Helper function to derive the filter mode on a source entry
1014 * from its internal counters. Predicates are:
1015 * A source is only excluded if all listeners exclude it.
1016 * A source is only included if no listeners exclude it,
1017 * and at least one listener includes it.
1018 * May be used by ifmcstat(8).
1019 */
1020uint8_t
1021ims_get_mode(const struct in_multi *inm, const struct ip_msource *ims,
1022 uint8_t t)
1023{
1024 INM_LOCK_ASSERT_HELD(__DECONST(struct in_multi *, inm));
1025
1026 t = !!t;
1027 if (inm->inm_st[t].iss_ex > 0 &&
1028 inm->inm_st[t].iss_ex == ims->ims_st[t].ex) {
1029 return MCAST_EXCLUDE;
1030 } else if (ims->ims_st[t].in > 0 && ims->ims_st[t].ex == 0) {
1031 return MCAST_INCLUDE;
1032 }
1033 return MCAST_UNDEFINED;
1034}
1035
1036/*
1037 * Merge socket-layer source into IGMP-layer source.
1038 * If rollback is non-zero, perform the inverse of the merge.
1039 */
1040static void
1041ims_merge(struct ip_msource *ims, const struct in_msource *lims,
1042 const int rollback)
1043{
1044 int n = rollback ? -1 : 1;
1045#ifdef IGMP_DEBUG
1046 struct in_addr ia;
1047
1048 ia.s_addr = htonl(ims->ims_haddr);
1049#endif
1050
1051 if (lims->imsl_st[0] == MCAST_EXCLUDE) {
1052 IGMP_INET_PRINTF(ia,
1053 ("%s: t1 ex -= %d on %s\n",
1054 __func__, n, _igmp_inet_buf));
1055 ims->ims_st[1].ex -= n;
1056 } else if (lims->imsl_st[0] == MCAST_INCLUDE) {
1057 IGMP_INET_PRINTF(ia,
1058 ("%s: t1 in -= %d on %s\n",
1059 __func__, n, _igmp_inet_buf));
1060 ims->ims_st[1].in -= n;
1061 }
1062
1063 if (lims->imsl_st[1] == MCAST_EXCLUDE) {
1064 IGMP_INET_PRINTF(ia,
1065 ("%s: t1 ex += %d on %s\n",
1066 __func__, n, _igmp_inet_buf));
1067 ims->ims_st[1].ex += n;
1068 } else if (lims->imsl_st[1] == MCAST_INCLUDE) {
1069 IGMP_INET_PRINTF(ia,
1070 ("%s: t1 in += %d on %s\n",
1071 __func__, n, _igmp_inet_buf));
1072 ims->ims_st[1].in += n;
1073 }
1074}
1075
1076/*
1077 * Atomically update the global in_multi state, when a membership's
1078 * filter list is being updated in any way.
1079 *
1080 * imf is the per-inpcb-membership group filter pointer.
1081 * A fake imf may be passed for in-kernel consumers.
1082 *
1083 * XXX This is a candidate for a set-symmetric-difference style loop
1084 * which would eliminate the repeated lookup from root of ims nodes,
1085 * as they share the same key space.
1086 *
1087 * If any error occurred this function will back out of refcounts
1088 * and return a non-zero value.
1089 */
1090static int
1091inm_merge(struct in_multi *inm, /*const*/ struct in_mfilter *imf)
1092{
1093 struct ip_msource *ims, *nims = NULL;
1094 struct in_msource *lims;
1095 int schanged, error;
1096 int nsrc0, nsrc1;
1097
1098 INM_LOCK_ASSERT_HELD(inm);
1099
1100 schanged = 0;
1101 error = 0;
1102 nsrc1 = nsrc0 = 0;
1103
1104 /*
1105 * Update the source filters first, as this may fail.
1106 * Maintain count of in-mode filters at t0, t1. These are
1107 * used to work out if we transition into ASM mode or not.
1108 * Maintain a count of source filters whose state was
1109 * actually modified by this operation.
1110 */
1111 RB_FOREACH(ims, ip_msource_tree, &imf->imf_sources) {
1112 lims = (struct in_msource *)ims;
1113 if (lims->imsl_st[0] == imf->imf_st[0]) {
1114 nsrc0++;
1115 }
1116 if (lims->imsl_st[1] == imf->imf_st[1]) {
1117 nsrc1++;
1118 }
1119 if (lims->imsl_st[0] == lims->imsl_st[1]) {
1120 continue;
1121 }
1122 error = inm_get_source(inm, lims->ims_haddr, 0, &nims);
1123 ++schanged;
1124 if (error) {
1125 break;
1126 }
1127 ims_merge(nims, lims, 0);
1128 }
1129 if (error) {
1130 struct ip_msource *bims;
1131
1132 RB_FOREACH_REVERSE_FROM(ims, ip_msource_tree, nims) {
1133 lims = (struct in_msource *)ims;
1134 if (lims->imsl_st[0] == lims->imsl_st[1]) {
1135 continue;
1136 }
1137 (void) inm_get_source(inm, lims->ims_haddr, 1, &bims);
1138 if (bims == NULL) {
1139 continue;
1140 }
1141 ims_merge(bims, lims, 1);
1142 }
1143 goto out_reap;
1144 }
1145
1146 IGMP_PRINTF(("%s: imf filters in-mode: %d at t0, %d at t1\n",
1147 __func__, nsrc0, nsrc1));
1148
1149 /* Handle transition between INCLUDE {n} and INCLUDE {} on socket. */
1150 if (imf->imf_st[0] == imf->imf_st[1] &&
1151 imf->imf_st[1] == MCAST_INCLUDE) {
1152 if (nsrc1 == 0) {
1153 IGMP_PRINTF(("%s: --in on inm at t1\n", __func__));
1154 --inm->inm_st[1].iss_in;
1155 }
1156 }
1157
1158 /* Handle filter mode transition on socket. */
1159 if (imf->imf_st[0] != imf->imf_st[1]) {
1160 IGMP_PRINTF(("%s: imf transition %d to %d\n",
1161 __func__, imf->imf_st[0], imf->imf_st[1]));
1162
1163 if (imf->imf_st[0] == MCAST_EXCLUDE) {
1164 IGMP_PRINTF(("%s: --ex on inm at t1\n", __func__));
1165 --inm->inm_st[1].iss_ex;
1166 } else if (imf->imf_st[0] == MCAST_INCLUDE) {
1167 IGMP_PRINTF(("%s: --in on inm at t1\n", __func__));
1168 --inm->inm_st[1].iss_in;
1169 }
1170
1171 if (imf->imf_st[1] == MCAST_EXCLUDE) {
1172 IGMP_PRINTF(("%s: ex++ on inm at t1\n", __func__));
1173 inm->inm_st[1].iss_ex++;
1174 } else if (imf->imf_st[1] == MCAST_INCLUDE && nsrc1 > 0) {
1175 IGMP_PRINTF(("%s: in++ on inm at t1\n", __func__));
1176 inm->inm_st[1].iss_in++;
1177 }
1178 }
1179
1180 /*
1181 * Track inm filter state in terms of listener counts.
1182 * If there are any exclusive listeners, stack-wide
1183 * membership is exclusive.
1184 * Otherwise, if only inclusive listeners, stack-wide is inclusive.
1185 * If no listeners remain, state is undefined at t1,
1186 * and the IGMP lifecycle for this group should finish.
1187 */
1188 if (inm->inm_st[1].iss_ex > 0) {
1189 IGMP_PRINTF(("%s: transition to EX\n", __func__));
1190 inm->inm_st[1].iss_fmode = MCAST_EXCLUDE;
1191 } else if (inm->inm_st[1].iss_in > 0) {
1192 IGMP_PRINTF(("%s: transition to IN\n", __func__));
1193 inm->inm_st[1].iss_fmode = MCAST_INCLUDE;
1194 } else {
1195 IGMP_PRINTF(("%s: transition to UNDEF\n", __func__));
1196 inm->inm_st[1].iss_fmode = MCAST_UNDEFINED;
1197 }
1198
1199 /* Decrement ASM listener count on transition out of ASM mode. */
1200 if (imf->imf_st[0] == MCAST_EXCLUDE && nsrc0 == 0) {
1201 if ((imf->imf_st[1] != MCAST_EXCLUDE) ||
1202 (imf->imf_st[1] == MCAST_EXCLUDE && nsrc1 > 0)) {
1203 IGMP_PRINTF(("%s: --asm on inm at t1\n", __func__));
1204 --inm->inm_st[1].iss_asm;
1205 }
1206 }
1207
1208 /* Increment ASM listener count on transition to ASM mode. */
1209 if (imf->imf_st[1] == MCAST_EXCLUDE && nsrc1 == 0) {
1210 IGMP_PRINTF(("%s: asm++ on inm at t1\n", __func__));
1211 inm->inm_st[1].iss_asm++;
1212 }
1213
1214 IGMP_PRINTF(("%s: merged imf 0x%llx to inm 0x%llx\n", __func__,
1215 (uint64_t)VM_KERNEL_ADDRPERM(imf),
1216 (uint64_t)VM_KERNEL_ADDRPERM(inm)));
1217 inm_print(inm);
1218
1219out_reap:
1220 if (schanged > 0) {
1221 IGMP_PRINTF(("%s: sources changed; reaping\n", __func__));
1222 inm_reap(inm);
1223 }
1224 return error;
1225}
1226
1227/*
1228 * Mark an in_multi's filter set deltas as committed.
1229 * Called by IGMP after a state change has been enqueued.
1230 */
1231void
1232inm_commit(struct in_multi *inm)
1233{
1234 struct ip_msource *ims;
1235
1236 INM_LOCK_ASSERT_HELD(inm);
1237
1238 IGMP_PRINTF(("%s: commit inm 0x%llx\n", __func__,
1239 (uint64_t)VM_KERNEL_ADDRPERM(inm)));
1240 IGMP_PRINTF(("%s: pre commit:\n", __func__));
1241 inm_print(inm);
1242
1243 RB_FOREACH(ims, ip_msource_tree, &inm->inm_srcs) {
1244 ims->ims_st[0] = ims->ims_st[1];
1245 }
1246 inm->inm_st[0] = inm->inm_st[1];
1247}
1248
1249/*
1250 * Reap unreferenced nodes from an in_multi's filter set.
1251 */
1252static void
1253inm_reap(struct in_multi *inm)
1254{
1255 struct ip_msource *ims, *tims;
1256
1257 INM_LOCK_ASSERT_HELD(inm);
1258
1259 RB_FOREACH_SAFE(ims, ip_msource_tree, &inm->inm_srcs, tims) {
1260 if (ims->ims_st[0].ex > 0 || ims->ims_st[0].in > 0 ||
1261 ims->ims_st[1].ex > 0 || ims->ims_st[1].in > 0 ||
1262 ims->ims_stp != 0) {
1263 continue;
1264 }
1265 IGMP_PRINTF(("%s: free ims 0x%llx\n", __func__,
1266 (uint64_t)VM_KERNEL_ADDRPERM(ims)));
1267 RB_REMOVE(ip_msource_tree, &inm->inm_srcs, ims);
1268 ipms_free(ims);
1269 inm->inm_nsrc--;
1270 }
1271}
1272
1273/*
1274 * Purge all source nodes from an in_multi's filter set.
1275 */
1276void
1277inm_purge(struct in_multi *inm)
1278{
1279 struct ip_msource *ims, *tims;
1280
1281 INM_LOCK_ASSERT_HELD(inm);
1282
1283 RB_FOREACH_SAFE(ims, ip_msource_tree, &inm->inm_srcs, tims) {
1284 IGMP_PRINTF(("%s: free ims 0x%llx\n", __func__,
1285 (uint64_t)VM_KERNEL_ADDRPERM(ims)));
1286 RB_REMOVE(ip_msource_tree, &inm->inm_srcs, ims);
1287 ipms_free(ims);
1288 inm->inm_nsrc--;
1289 }
1290}
1291
1292/*
1293 * Join a multicast group; real entry point.
1294 *
1295 * Only preserves atomicity at inm level.
1296 * NOTE: imf argument cannot be const due to sys/tree.h limitations.
1297 *
1298 * If the IGMP downcall fails, the group is not joined, and an error
1299 * code is returned.
1300 */
1301static int
1302in_joingroup(struct ifnet *ifp, const struct in_addr *gina,
1303 /*const*/ struct in_mfilter *imf, struct in_multi **pinm)
1304{
1305 struct in_mfilter timf;
1306 struct in_multi *inm = NULL;
1307 int error = 0;
1308 struct igmp_tparams itp;
1309
1310 IGMP_INET_PRINTF(*gina, ("%s: join %s on 0x%llx(%s))\n", __func__,
1311 _igmp_inet_buf, (uint64_t)VM_KERNEL_ADDRPERM(ifp), if_name(ifp)));
1312
1313 bzero(&itp, sizeof(itp));
1314 *pinm = NULL;
1315
1316 /*
1317 * If no imf was specified (i.e. kernel consumer),
1318 * fake one up and assume it is an ASM join.
1319 */
1320 if (imf == NULL) {
1321 imf_init(&timf, MCAST_UNDEFINED, MCAST_EXCLUDE);
1322 imf = &timf;
1323 }
1324
1325 error = in_getmulti(ifp, gina, &inm);
1326 if (error) {
1327 IGMP_PRINTF(("%s: in_getmulti() failure\n", __func__));
1328 return error;
1329 }
1330
1331 IGMP_PRINTF(("%s: merge inm state\n", __func__));
1332
1333 INM_LOCK(inm);
1334 error = inm_merge(inm, imf);
1335 if (error) {
1336 IGMP_PRINTF(("%s: failed to merge inm state\n", __func__));
1337 goto out_inm_release;
1338 }
1339
1340 IGMP_PRINTF(("%s: doing igmp downcall\n", __func__));
1341 error = igmp_change_state(inm, &itp);
1342 if (error) {
1343 IGMP_PRINTF(("%s: failed to update source\n", __func__));
1344 imf_rollback(imf);
1345 goto out_inm_release;
1346 }
1347
1348out_inm_release:
1349 if (error) {
1350 IGMP_PRINTF(("%s: dropping ref on 0x%llx\n", __func__,
1351 (uint64_t)VM_KERNEL_ADDRPERM(inm)));
1352 INM_UNLOCK(inm);
1353 INM_REMREF(inm);
1354 } else {
1355 INM_UNLOCK(inm);
1356 *pinm = inm; /* keep refcount from in_getmulti() */
1357 }
1358
1359 /* schedule timer now that we've dropped the lock(s) */
1360 igmp_set_timeout(&itp);
1361
1362 return error;
1363}
1364
1365/*
1366 * Leave a multicast group; real entry point.
1367 * All source filters will be expunged.
1368 *
1369 * Only preserves atomicity at inm level.
1370 *
1371 * Note: This is not the same as inm_release(*) as this function also
1372 * makes a state change downcall into IGMP.
1373 */
1374int
1375in_leavegroup(struct in_multi *inm, /*const*/ struct in_mfilter *imf)
1376{
1377 struct in_mfilter timf;
1378 int error, lastref;
1379 struct igmp_tparams itp;
1380
1381 bzero(&itp, sizeof(itp));
1382 error = 0;
1383
1384 INM_LOCK_ASSERT_NOTHELD(inm);
1385
1386 in_multihead_lock_exclusive();
1387 INM_LOCK(inm);
1388
1389 IGMP_INET_PRINTF(inm->inm_addr,
1390 ("%s: leave inm 0x%llx, %s/%s%d, imf 0x%llx\n", __func__,
1391 (uint64_t)VM_KERNEL_ADDRPERM(inm), _igmp_inet_buf,
1392 (inm_is_ifp_detached(inm) ? "null" : inm->inm_ifp->if_name),
1393 inm->inm_ifp->if_unit, (uint64_t)VM_KERNEL_ADDRPERM(imf)));
1394
1395 /*
1396 * If no imf was specified (i.e. kernel consumer),
1397 * fake one up and assume it is an ASM join.
1398 */
1399 if (imf == NULL) {
1400 imf_init(&timf, MCAST_EXCLUDE, MCAST_UNDEFINED);
1401 imf = &timf;
1402 }
1403
1404 /*
1405 * Begin state merge transaction at IGMP layer.
1406 *
1407 * As this particular invocation should not cause any memory
1408 * to be allocated, and there is no opportunity to roll back
1409 * the transaction, it MUST NOT fail.
1410 */
1411 IGMP_PRINTF(("%s: merge inm state\n", __func__));
1412
1413 error = inm_merge(inm, imf);
1414 KASSERT(error == 0, ("%s: failed to merge inm state\n", __func__));
1415
1416 IGMP_PRINTF(("%s: doing igmp downcall\n", __func__));
1417 error = igmp_change_state(inm, &itp);
1418#if IGMP_DEBUG
1419 if (error) {
1420 IGMP_PRINTF(("%s: failed igmp downcall\n", __func__));
1421 }
1422#endif
1423 lastref = in_multi_detach(inm);
1424 VERIFY(!lastref || (!(inm->inm_debug & IFD_ATTACHED) &&
1425 inm->inm_reqcnt == 0));
1426 INM_UNLOCK(inm);
1427 in_multihead_lock_done();
1428
1429 if (lastref) {
1430 INM_REMREF(inm); /* for in_multihead list */
1431 }
1432 /* schedule timer now that we've dropped the lock(s) */
1433 igmp_set_timeout(&itp);
1434
1435 return error;
1436}
1437
1438/*
1439 * Join an IPv4 multicast group in (*,G) exclusive mode.
1440 * The group must be a 224.0.0.0/24 link-scope group.
1441 * This KPI is for legacy kernel consumers only.
1442 */
1443struct in_multi *
1444in_addmulti(struct in_addr *ap, struct ifnet *ifp)
1445{
1446 struct in_multi *pinm = NULL;
1447 int error;
1448
1449 KASSERT(IN_LOCAL_GROUP(ntohl(ap->s_addr)),
1450 ("%s: %s not in 224.0.0.0/24\n", __func__, inet_ntoa(*ap)));
1451
1452 error = in_joingroup(ifp, ap, NULL, &pinm);
1453 VERIFY(pinm != NULL || error != 0);
1454
1455 return pinm;
1456}
1457
1458/*
1459 * Leave an IPv4 multicast group, assumed to be in exclusive (*,G) mode.
1460 * This KPI is for legacy kernel consumers only.
1461 */
1462void
1463in_delmulti(struct in_multi *inm)
1464{
1465 (void) in_leavegroup(inm, NULL);
1466}
1467
1468/*
1469 * Block or unblock an ASM multicast source on an inpcb.
1470 * This implements the delta-based API described in RFC 3678.
1471 *
1472 * The delta-based API applies only to exclusive-mode memberships.
1473 * An IGMP downcall will be performed.
1474 *
1475 * Return 0 if successful, otherwise return an appropriate error code.
1476 */
1477static int
1478inp_block_unblock_source(struct inpcb *inp, struct sockopt *sopt)
1479{
1480 struct group_source_req gsr;
1481 struct sockaddr_in *gsa, *ssa;
1482 struct ifnet *ifp;
1483 struct in_mfilter *imf;
1484 struct ip_moptions *imo;
1485 struct in_msource *ims;
1486 struct in_multi *inm;
1487 size_t idx;
1488 uint16_t fmode;
1489 int error, doblock;
1490 unsigned int ifindex = 0;
1491 struct igmp_tparams itp;
1492
1493 bzero(&itp, sizeof(itp));
1494 ifp = NULL;
1495 error = 0;
1496 doblock = 0;
1497
1498 memset(&gsr, 0, sizeof(struct group_source_req));
1499 gsa = (struct sockaddr_in *)&gsr.gsr_group;
1500 ssa = (struct sockaddr_in *)&gsr.gsr_source;
1501
1502 switch (sopt->sopt_name) {
1503 case IP_BLOCK_SOURCE:
1504 case IP_UNBLOCK_SOURCE: {
1505 struct ip_mreq_source mreqs;
1506
1507 error = sooptcopyin(sopt, &mreqs,
1508 sizeof(struct ip_mreq_source),
1509 sizeof(struct ip_mreq_source));
1510 if (error) {
1511 return error;
1512 }
1513
1514 gsa->sin_family = AF_INET;
1515 gsa->sin_len = sizeof(struct sockaddr_in);
1516 gsa->sin_addr = mreqs.imr_multiaddr;
1517
1518 ssa->sin_family = AF_INET;
1519 ssa->sin_len = sizeof(struct sockaddr_in);
1520 ssa->sin_addr = mreqs.imr_sourceaddr;
1521
1522 if (!in_nullhost(mreqs.imr_interface)) {
1523 ifp = ip_multicast_if(&mreqs.imr_interface, &ifindex);
1524 }
1525
1526 if (sopt->sopt_name == IP_BLOCK_SOURCE) {
1527 doblock = 1;
1528 }
1529
1530 IGMP_INET_PRINTF(mreqs.imr_interface,
1531 ("%s: imr_interface = %s, ifp = 0x%llx\n", __func__,
1532 _igmp_inet_buf, (uint64_t)VM_KERNEL_ADDRPERM(ifp)));
1533 break;
1534 }
1535
1536 case MCAST_BLOCK_SOURCE:
1537 case MCAST_UNBLOCK_SOURCE:
1538 error = sooptcopyin(sopt, &gsr,
1539 sizeof(struct group_source_req),
1540 sizeof(struct group_source_req));
1541 if (error) {
1542 return error;
1543 }
1544
1545 if (gsa->sin_family != AF_INET ||
1546 gsa->sin_len != sizeof(struct sockaddr_in)) {
1547 return EINVAL;
1548 }
1549
1550 if (ssa->sin_family != AF_INET ||
1551 ssa->sin_len != sizeof(struct sockaddr_in)) {
1552 return EINVAL;
1553 }
1554
1555 ifnet_head_lock_shared();
1556 if (gsr.gsr_interface == 0 ||
1557 (u_int)if_index < gsr.gsr_interface) {
1558 ifnet_head_done();
1559 return EADDRNOTAVAIL;
1560 }
1561
1562 ifp = ifindex2ifnet[gsr.gsr_interface];
1563 ifnet_head_done();
1564
1565 if (ifp == NULL) {
1566 return EADDRNOTAVAIL;
1567 }
1568
1569 if (sopt->sopt_name == MCAST_BLOCK_SOURCE) {
1570 doblock = 1;
1571 }
1572 break;
1573
1574 default:
1575 IGMP_PRINTF(("%s: unknown sopt_name %d\n",
1576 __func__, sopt->sopt_name));
1577 return EOPNOTSUPP;
1578 }
1579
1580 if (!IN_MULTICAST(ntohl(gsa->sin_addr.s_addr))) {
1581 return EINVAL;
1582 }
1583
1584 /*
1585 * Check if we are actually a member of this group.
1586 */
1587 imo = inp_findmoptions(inp);
1588 if (imo == NULL) {
1589 return ENOMEM;
1590 }
1591
1592 IMO_LOCK(imo);
1593 idx = imo_match_group(imo, ifp, gsa);
1594 if (idx == (size_t)-1 || imo->imo_mfilters == NULL) {
1595 error = EADDRNOTAVAIL;
1596 goto out_imo_locked;
1597 }
1598
1599 VERIFY(imo->imo_mfilters != NULL);
1600 imf = &imo->imo_mfilters[idx];
1601 inm = imo->imo_membership[idx];
1602
1603 /*
1604 * Attempting to use the delta-based API on an
1605 * non exclusive-mode membership is an error.
1606 */
1607 fmode = imf->imf_st[0];
1608 if (fmode != MCAST_EXCLUDE) {
1609 error = EINVAL;
1610 goto out_imo_locked;
1611 }
1612
1613 /*
1614 * Deal with error cases up-front:
1615 * Asked to block, but already blocked; or
1616 * Asked to unblock, but nothing to unblock.
1617 * If adding a new block entry, allocate it.
1618 */
1619 ims = imo_match_source(imo, idx, ssa);
1620 if ((ims != NULL && doblock) || (ims == NULL && !doblock)) {
1621 IGMP_INET_PRINTF(ssa->sin_addr,
1622 ("%s: source %s %spresent\n", __func__,
1623 _igmp_inet_buf, doblock ? "" : "not "));
1624 error = EADDRNOTAVAIL;
1625 goto out_imo_locked;
1626 }
1627
1628 /*
1629 * Begin state merge transaction at socket layer.
1630 */
1631 if (doblock) {
1632 IGMP_PRINTF(("%s: %s source\n", __func__, "block"));
1633 ims = imf_graft(imf, fmode, ssa);
1634 if (ims == NULL) {
1635 error = ENOMEM;
1636 }
1637 } else {
1638 IGMP_PRINTF(("%s: %s source\n", __func__, "allow"));
1639 error = imf_prune(imf, ssa);
1640 }
1641
1642 if (error) {
1643 IGMP_PRINTF(("%s: merge imf state failed\n", __func__));
1644 goto out_imf_rollback;
1645 }
1646
1647 /*
1648 * Begin state merge transaction at IGMP layer.
1649 */
1650 INM_LOCK(inm);
1651 IGMP_PRINTF(("%s: merge inm state\n", __func__));
1652 error = inm_merge(inm, imf);
1653 if (error) {
1654 IGMP_PRINTF(("%s: failed to merge inm state\n", __func__));
1655 INM_UNLOCK(inm);
1656 goto out_imf_rollback;
1657 }
1658
1659 IGMP_PRINTF(("%s: doing igmp downcall\n", __func__));
1660 error = igmp_change_state(inm, &itp);
1661 INM_UNLOCK(inm);
1662#if IGMP_DEBUG
1663 if (error) {
1664 IGMP_PRINTF(("%s: failed igmp downcall\n", __func__));
1665 }
1666#endif
1667
1668out_imf_rollback:
1669 if (error) {
1670 imf_rollback(imf);
1671 } else {
1672 imf_commit(imf);
1673 }
1674
1675 imf_reap(imf);
1676
1677out_imo_locked:
1678 IMO_UNLOCK(imo);
1679 IMO_REMREF(imo); /* from inp_findmoptions() */
1680
1681 /* schedule timer now that we've dropped the lock(s) */
1682 igmp_set_timeout(&itp);
1683
1684 return error;
1685}
1686
1687/*
1688 * Given an inpcb, return its multicast options structure pointer.
1689 *
1690 * Caller is responsible for locking the inpcb, and releasing the
1691 * extra reference held on the imo, upon a successful return.
1692 */
1693static struct ip_moptions *
1694inp_findmoptions(struct inpcb *inp)
1695{
1696 struct ip_moptions *imo;
1697 struct in_multi **immp;
1698 struct in_mfilter *imfp;
1699 size_t idx;
1700
1701 if ((imo = inp->inp_moptions) != NULL) {
1702 IMO_ADDREF(imo); /* for caller */
1703 return imo;
1704 }
1705
1706 imo = ip_allocmoptions(M_WAITOK);
1707 if (imo == NULL) {
1708 return NULL;
1709 }
1710
1711 immp = _MALLOC(sizeof(*immp) * IP_MIN_MEMBERSHIPS, M_IPMOPTS,
1712 M_WAITOK | M_ZERO);
1713 if (immp == NULL) {
1714 IMO_REMREF(imo);
1715 return NULL;
1716 }
1717
1718 imfp = _MALLOC(sizeof(struct in_mfilter) * IP_MIN_MEMBERSHIPS,
1719 M_INMFILTER, M_WAITOK | M_ZERO);
1720 if (imfp == NULL) {
1721 _FREE(immp, M_IPMOPTS);
1722 IMO_REMREF(imo);
1723 return NULL;
1724 }
1725
1726 imo->imo_multicast_ifp = NULL;
1727 imo->imo_multicast_addr.s_addr = INADDR_ANY;
1728 imo->imo_multicast_vif = -1;
1729 imo->imo_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1730 imo->imo_multicast_loop = in_mcast_loop;
1731 imo->imo_num_memberships = 0;
1732 imo->imo_max_memberships = IP_MIN_MEMBERSHIPS;
1733 imo->imo_membership = immp;
1734
1735 /* Initialize per-group source filters. */
1736 for (idx = 0; idx < IP_MIN_MEMBERSHIPS; idx++) {
1737 imf_init(&imfp[idx], MCAST_UNDEFINED, MCAST_EXCLUDE);
1738 }
1739
1740 imo->imo_mfilters = imfp;
1741 inp->inp_moptions = imo; /* keep reference from ip_allocmoptions() */
1742 IMO_ADDREF(imo); /* for caller */
1743
1744 return imo;
1745}
1746/*
1747 * Atomically get source filters on a socket for an IPv4 multicast group.
1748 */
1749static int
1750inp_get_source_filters(struct inpcb *inp, struct sockopt *sopt)
1751{
1752 struct __msfilterreq64 msfr = {}, msfr64;
1753 struct __msfilterreq32 msfr32;
1754 struct sockaddr_in *gsa;
1755 struct ifnet *ifp;
1756 struct ip_moptions *imo;
1757 struct in_mfilter *imf;
1758 struct ip_msource *ims;
1759 struct in_msource *lims;
1760 struct sockaddr_in *psin;
1761 struct sockaddr_storage *ptss;
1762 struct sockaddr_storage *tss;
1763 int error;
1764 size_t idx, nsrcs, ncsrcs;
1765 user_addr_t tmp_ptr;
1766
1767 imo = inp->inp_moptions;
1768 VERIFY(imo != NULL);
1769
1770 if (IS_64BIT_PROCESS(current_proc())) {
1771 error = sooptcopyin(sopt, &msfr64,
1772 sizeof(struct __msfilterreq64),
1773 sizeof(struct __msfilterreq64));
1774 if (error) {
1775 return error;
1776 }
1777 /* we never use msfr.msfr_srcs; */
1778 memcpy(&msfr, &msfr64, sizeof(msfr64));
1779 } else {
1780 error = sooptcopyin(sopt, &msfr32,
1781 sizeof(struct __msfilterreq32),
1782 sizeof(struct __msfilterreq32));
1783 if (error) {
1784 return error;
1785 }
1786 /* we never use msfr.msfr_srcs; */
1787 memcpy(&msfr, &msfr32, sizeof(msfr32));
1788 }
1789
1790 ifnet_head_lock_shared();
1791 if (msfr.msfr_ifindex == 0 || (u_int)if_index < msfr.msfr_ifindex) {
1792 ifnet_head_done();
1793 return EADDRNOTAVAIL;
1794 }
1795
1796 ifp = ifindex2ifnet[msfr.msfr_ifindex];
1797 ifnet_head_done();
1798
1799 if (ifp == NULL) {
1800 return EADDRNOTAVAIL;
1801 }
1802
1803 if ((size_t) msfr.msfr_nsrcs >
1804 UINT32_MAX / sizeof(struct sockaddr_storage)) {
1805 msfr.msfr_nsrcs = UINT32_MAX / sizeof(struct sockaddr_storage);
1806 }
1807
1808 if (msfr.msfr_nsrcs > in_mcast_maxsocksrc) {
1809 msfr.msfr_nsrcs = in_mcast_maxsocksrc;
1810 }
1811
1812 IMO_LOCK(imo);
1813 /*
1814 * Lookup group on the socket.
1815 */
1816 gsa = (struct sockaddr_in *)&msfr.msfr_group;
1817
1818 idx = imo_match_group(imo, ifp, gsa);
1819 if (idx == (size_t)-1 || imo->imo_mfilters == NULL) {
1820 IMO_UNLOCK(imo);
1821 return EADDRNOTAVAIL;
1822 }
1823 imf = &imo->imo_mfilters[idx];
1824
1825 /*
1826 * Ignore memberships which are in limbo.
1827 */
1828 if (imf->imf_st[1] == MCAST_UNDEFINED) {
1829 IMO_UNLOCK(imo);
1830 return EAGAIN;
1831 }
1832 msfr.msfr_fmode = imf->imf_st[1];
1833
1834 /*
1835 * If the user specified a buffer, copy out the source filter
1836 * entries to userland gracefully.
1837 * We only copy out the number of entries which userland
1838 * has asked for, but we always tell userland how big the
1839 * buffer really needs to be.
1840 */
1841
1842 if (IS_64BIT_PROCESS(current_proc())) {
1843 tmp_ptr = msfr64.msfr_srcs;
1844 } else {
1845 tmp_ptr = CAST_USER_ADDR_T(msfr32.msfr_srcs);
1846 }
1847
1848 tss = NULL;
1849 if (tmp_ptr != USER_ADDR_NULL && msfr.msfr_nsrcs > 0) {
1850 tss = _MALLOC((size_t) msfr.msfr_nsrcs * sizeof(*tss),
1851 M_TEMP, M_WAITOK | M_ZERO);
1852 if (tss == NULL) {
1853 IMO_UNLOCK(imo);
1854 return ENOBUFS;
1855 }
1856 }
1857
1858 /*
1859 * Count number of sources in-mode at t0.
1860 * If buffer space exists and remains, copy out source entries.
1861 */
1862 nsrcs = msfr.msfr_nsrcs;
1863 ncsrcs = 0;
1864 ptss = tss;
1865 RB_FOREACH(ims, ip_msource_tree, &imf->imf_sources) {
1866 lims = (struct in_msource *)ims;
1867 if (lims->imsl_st[0] == MCAST_UNDEFINED ||
1868 lims->imsl_st[0] != imf->imf_st[0]) {
1869 continue;
1870 }
1871 if (tss != NULL && nsrcs > 0) {
1872 psin = (struct sockaddr_in *)ptss;
1873 psin->sin_family = AF_INET;
1874 psin->sin_len = sizeof(struct sockaddr_in);
1875 psin->sin_addr.s_addr = htonl(lims->ims_haddr);
1876 psin->sin_port = 0;
1877 ++ptss;
1878 --nsrcs;
1879 ++ncsrcs;
1880 }
1881 }
1882
1883 IMO_UNLOCK(imo);
1884
1885 if (tss != NULL) {
1886 error = copyout(tss, tmp_ptr, ncsrcs * sizeof(*tss));
1887 FREE(tss, M_TEMP);
1888 if (error) {
1889 return error;
1890 }
1891 }
1892
1893 msfr.msfr_nsrcs = ncsrcs;
1894 if (IS_64BIT_PROCESS(current_proc())) {
1895 msfr64.msfr_ifindex = msfr.msfr_ifindex;
1896 msfr64.msfr_fmode = msfr.msfr_fmode;
1897 msfr64.msfr_nsrcs = msfr.msfr_nsrcs;
1898 memcpy(&msfr64.msfr_group, &msfr.msfr_group,
1899 sizeof(struct sockaddr_storage));
1900 error = sooptcopyout(sopt, &msfr64,
1901 sizeof(struct __msfilterreq64));
1902 } else {
1903 msfr32.msfr_ifindex = msfr.msfr_ifindex;
1904 msfr32.msfr_fmode = msfr.msfr_fmode;
1905 msfr32.msfr_nsrcs = msfr.msfr_nsrcs;
1906 memcpy(&msfr32.msfr_group, &msfr.msfr_group,
1907 sizeof(struct sockaddr_storage));
1908 error = sooptcopyout(sopt, &msfr32,
1909 sizeof(struct __msfilterreq32));
1910 }
1911
1912 return error;
1913}
1914
1915/*
1916 * Return the IP multicast options in response to user getsockopt().
1917 */
1918int
1919inp_getmoptions(struct inpcb *inp, struct sockopt *sopt)
1920{
1921 struct ip_mreqn mreqn;
1922 struct ip_moptions *imo;
1923 struct ifnet *ifp;
1924 struct in_ifaddr *ia;
1925 int error, optval;
1926 unsigned int ifindex;
1927 u_char coptval;
1928
1929 imo = inp->inp_moptions;
1930 /*
1931 * If socket is neither of type SOCK_RAW or SOCK_DGRAM,
1932 * or is a divert socket, reject it.
1933 */
1934 if (SOCK_PROTO(inp->inp_socket) == IPPROTO_DIVERT ||
1935 (SOCK_TYPE(inp->inp_socket) != SOCK_RAW &&
1936 SOCK_TYPE(inp->inp_socket) != SOCK_DGRAM)) {
1937 return EOPNOTSUPP;
1938 }
1939
1940 error = 0;
1941 switch (sopt->sopt_name) {
1942 case IP_MULTICAST_IF:
1943 memset(&mreqn, 0, sizeof(struct ip_mreqn));
1944 if (imo != NULL) {
1945 IMO_LOCK(imo);
1946 ifp = imo->imo_multicast_ifp;
1947 if (!in_nullhost(imo->imo_multicast_addr)) {
1948 mreqn.imr_address = imo->imo_multicast_addr;
1949 } else if (ifp != NULL) {
1950 mreqn.imr_ifindex = ifp->if_index;
1951 IFP_TO_IA(ifp, ia);
1952 if (ia != NULL) {
1953 IFA_LOCK_SPIN(&ia->ia_ifa);
1954 mreqn.imr_address =
1955 IA_SIN(ia)->sin_addr;
1956 IFA_UNLOCK(&ia->ia_ifa);
1957 IFA_REMREF(&ia->ia_ifa);
1958 }
1959 }
1960 IMO_UNLOCK(imo);
1961 }
1962 if (sopt->sopt_valsize == sizeof(struct ip_mreqn)) {
1963 error = sooptcopyout(sopt, &mreqn,
1964 sizeof(struct ip_mreqn));
1965 } else {
1966 error = sooptcopyout(sopt, &mreqn.imr_address,
1967 sizeof(struct in_addr));
1968 }
1969 break;
1970
1971 case IP_MULTICAST_IFINDEX:
1972 if (imo != NULL) {
1973 IMO_LOCK(imo);
1974 }
1975 if (imo == NULL || imo->imo_multicast_ifp == NULL) {
1976 ifindex = 0;
1977 } else {
1978 ifindex = imo->imo_multicast_ifp->if_index;
1979 }
1980 if (imo != NULL) {
1981 IMO_UNLOCK(imo);
1982 }
1983 error = sooptcopyout(sopt, &ifindex, sizeof(ifindex));
1984 break;
1985
1986 case IP_MULTICAST_TTL:
1987 if (imo == NULL) {
1988 optval = coptval = IP_DEFAULT_MULTICAST_TTL;
1989 } else {
1990 IMO_LOCK(imo);
1991 optval = coptval = imo->imo_multicast_ttl;
1992 IMO_UNLOCK(imo);
1993 }
1994 if (sopt->sopt_valsize == sizeof(u_char)) {
1995 error = sooptcopyout(sopt, &coptval, sizeof(u_char));
1996 } else {
1997 error = sooptcopyout(sopt, &optval, sizeof(int));
1998 }
1999 break;
2000
2001 case IP_MULTICAST_LOOP:
2002 if (imo == 0) {
2003 optval = coptval = IP_DEFAULT_MULTICAST_LOOP;
2004 } else {
2005 IMO_LOCK(imo);
2006 optval = coptval = imo->imo_multicast_loop;
2007 IMO_UNLOCK(imo);
2008 }
2009 if (sopt->sopt_valsize == sizeof(u_char)) {
2010 error = sooptcopyout(sopt, &coptval, sizeof(u_char));
2011 } else {
2012 error = sooptcopyout(sopt, &optval, sizeof(int));
2013 }
2014 break;
2015
2016 case IP_MSFILTER:
2017 if (imo == NULL) {
2018 error = EADDRNOTAVAIL;
2019 } else {
2020 error = inp_get_source_filters(inp, sopt);
2021 }
2022 break;
2023
2024 default:
2025 error = ENOPROTOOPT;
2026 break;
2027 }
2028
2029 return error;
2030}
2031
2032/*
2033 * Look up the ifnet to use for a multicast group membership,
2034 * given the IPv4 address of an interface, and the IPv4 group address.
2035 *
2036 * This routine exists to support legacy multicast applications
2037 * which do not understand that multicast memberships are scoped to
2038 * specific physical links in the networking stack, or which need
2039 * to join link-scope groups before IPv4 addresses are configured.
2040 *
2041 * If inp is non-NULL and is bound to an interface, use this socket's
2042 * inp_boundif for any required routing table lookup.
2043 *
2044 * If the route lookup fails, attempt to use the first non-loopback
2045 * interface with multicast capability in the system as a
2046 * last resort. The legacy IPv4 ASM API requires that we do
2047 * this in order to allow groups to be joined when the routing
2048 * table has not yet been populated during boot.
2049 *
2050 * Returns NULL if no ifp could be found.
2051 *
2052 */
2053static struct ifnet *
2054inp_lookup_mcast_ifp(const struct inpcb *inp,
2055 const struct sockaddr_in *gsin, const struct in_addr ina)
2056{
2057 struct ifnet *ifp;
2058 unsigned int ifindex = 0;
2059
2060 VERIFY(gsin->sin_family == AF_INET);
2061 VERIFY(IN_MULTICAST(ntohl(gsin->sin_addr.s_addr)));
2062
2063 ifp = NULL;
2064 if (!in_nullhost(ina)) {
2065 struct in_addr new_ina;
2066 memcpy(&new_ina, &ina, sizeof(struct in_addr));
2067 ifp = ip_multicast_if(&new_ina, &ifindex);
2068 } else {
2069 struct route ro;
2070 unsigned int ifscope = IFSCOPE_NONE;
2071
2072 if (inp != NULL && (inp->inp_flags & INP_BOUND_IF)) {
2073 ifscope = inp->inp_boundifp->if_index;
2074 }
2075
2076 bzero(&ro, sizeof(ro));
2077 memcpy(&ro.ro_dst, gsin, sizeof(struct sockaddr_in));
2078 rtalloc_scoped_ign(&ro, 0, ifscope);
2079 if (ro.ro_rt != NULL) {
2080 ifp = ro.ro_rt->rt_ifp;
2081 VERIFY(ifp != NULL);
2082 } else {
2083 struct in_ifaddr *ia;
2084 struct ifnet *mifp;
2085
2086 mifp = NULL;
2087 lck_rw_lock_shared(in_ifaddr_rwlock);
2088 TAILQ_FOREACH(ia, &in_ifaddrhead, ia_link) {
2089 IFA_LOCK_SPIN(&ia->ia_ifa);
2090 mifp = ia->ia_ifp;
2091 IFA_UNLOCK(&ia->ia_ifa);
2092 if (!(mifp->if_flags & IFF_LOOPBACK) &&
2093 (mifp->if_flags & IFF_MULTICAST)) {
2094 ifp = mifp;
2095 break;
2096 }
2097 }
2098 lck_rw_done(in_ifaddr_rwlock);
2099 }
2100 ROUTE_RELEASE(&ro);
2101 }
2102
2103 return ifp;
2104}
2105
2106/*
2107 * Join an IPv4 multicast group, possibly with a source.
2108 *
2109 * NB: sopt->sopt_val might point to the kernel address space. This means that
2110 * we were called by the IPv6 stack due to the presence of an IPv6 v4 mapped
2111 * address. In this scenario, sopt_p points to kernproc and sooptcopyin() will
2112 * just issue an in-kernel memcpy.
2113 */
2114int
2115inp_join_group(struct inpcb *inp, struct sockopt *sopt)
2116{
2117 struct group_source_req gsr;
2118 struct sockaddr_in *gsa, *ssa;
2119 struct ifnet *ifp;
2120 struct in_mfilter *imf;
2121 struct ip_moptions *imo;
2122 struct in_multi *inm = NULL;
2123 struct in_msource *lims;
2124 size_t idx;
2125 int error, is_new;
2126 struct igmp_tparams itp;
2127
2128 bzero(&itp, sizeof(itp));
2129 ifp = NULL;
2130 imf = NULL;
2131 error = 0;
2132 is_new = 0;
2133
2134 memset(&gsr, 0, sizeof(struct group_source_req));
2135 gsa = (struct sockaddr_in *)&gsr.gsr_group;
2136 gsa->sin_family = AF_UNSPEC;
2137 ssa = (struct sockaddr_in *)&gsr.gsr_source;
2138 ssa->sin_family = AF_UNSPEC;
2139
2140 switch (sopt->sopt_name) {
2141 case IP_ADD_MEMBERSHIP:
2142 case IP_ADD_SOURCE_MEMBERSHIP: {
2143 struct ip_mreq_source mreqs;
2144
2145 if (sopt->sopt_name == IP_ADD_MEMBERSHIP) {
2146 error = sooptcopyin(sopt, &mreqs,
2147 sizeof(struct ip_mreq),
2148 sizeof(struct ip_mreq));
2149 /*
2150 * Do argument switcharoo from ip_mreq into
2151 * ip_mreq_source to avoid using two instances.
2152 */
2153 mreqs.imr_interface = mreqs.imr_sourceaddr;
2154 mreqs.imr_sourceaddr.s_addr = INADDR_ANY;
2155 } else if (sopt->sopt_name == IP_ADD_SOURCE_MEMBERSHIP) {
2156 error = sooptcopyin(sopt, &mreqs,
2157 sizeof(struct ip_mreq_source),
2158 sizeof(struct ip_mreq_source));
2159 }
2160 if (error) {
2161 IGMP_PRINTF(("%s: error copyin IP_ADD_MEMBERSHIP/"
2162 "IP_ADD_SOURCE_MEMBERSHIP %d err=%d\n",
2163 __func__, sopt->sopt_name, error));
2164 return error;
2165 }
2166
2167 gsa->sin_family = AF_INET;
2168 gsa->sin_len = sizeof(struct sockaddr_in);
2169 gsa->sin_addr = mreqs.imr_multiaddr;
2170
2171 if (sopt->sopt_name == IP_ADD_SOURCE_MEMBERSHIP) {
2172 ssa->sin_family = AF_INET;
2173 ssa->sin_len = sizeof(struct sockaddr_in);
2174 ssa->sin_addr = mreqs.imr_sourceaddr;
2175 }
2176
2177 if (!IN_MULTICAST(ntohl(gsa->sin_addr.s_addr))) {
2178 return EINVAL;
2179 }
2180
2181 ifp = inp_lookup_mcast_ifp(inp, gsa, mreqs.imr_interface);
2182 IGMP_INET_PRINTF(mreqs.imr_interface,
2183 ("%s: imr_interface = %s, ifp = 0x%llx\n", __func__,
2184 _igmp_inet_buf, (uint64_t)VM_KERNEL_ADDRPERM(ifp)));
2185 break;
2186 }
2187
2188 case MCAST_JOIN_GROUP:
2189 case MCAST_JOIN_SOURCE_GROUP:
2190 if (sopt->sopt_name == MCAST_JOIN_GROUP) {
2191 error = sooptcopyin(sopt, &gsr,
2192 sizeof(struct group_req),
2193 sizeof(struct group_req));
2194 } else if (sopt->sopt_name == MCAST_JOIN_SOURCE_GROUP) {
2195 error = sooptcopyin(sopt, &gsr,
2196 sizeof(struct group_source_req),
2197 sizeof(struct group_source_req));
2198 }
2199 if (error) {
2200 return error;
2201 }
2202
2203 if (gsa->sin_family != AF_INET ||
2204 gsa->sin_len != sizeof(struct sockaddr_in)) {
2205 return EINVAL;
2206 }
2207
2208 /*
2209 * Overwrite the port field if present, as the sockaddr
2210 * being copied in may be matched with a binary comparison.
2211 */
2212 gsa->sin_port = 0;
2213 if (sopt->sopt_name == MCAST_JOIN_SOURCE_GROUP) {
2214 if (ssa->sin_family != AF_INET ||
2215 ssa->sin_len != sizeof(struct sockaddr_in)) {
2216 return EINVAL;
2217 }
2218 ssa->sin_port = 0;
2219 }
2220
2221 if (!IN_MULTICAST(ntohl(gsa->sin_addr.s_addr))) {
2222 return EINVAL;
2223 }
2224
2225 ifnet_head_lock_shared();
2226 if (gsr.gsr_interface == 0 ||
2227 (u_int)if_index < gsr.gsr_interface) {
2228 ifnet_head_done();
2229 return EADDRNOTAVAIL;
2230 }
2231 ifp = ifindex2ifnet[gsr.gsr_interface];
2232 ifnet_head_done();
2233
2234 break;
2235
2236 default:
2237 IGMP_PRINTF(("%s: unknown sopt_name %d\n",
2238 __func__, sopt->sopt_name));
2239 return EOPNOTSUPP;
2240 }
2241
2242 if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
2243 return EADDRNOTAVAIL;
2244 }
2245
2246 INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_mcast_join_total);
2247 /*
2248 * TBD: revisit the criteria for non-OS initiated joins
2249 */
2250 if (inp->inp_lport == htons(5353)) {
2251 INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_mcast_join_os_total);
2252 }
2253
2254 imo = inp_findmoptions(inp);
2255 if (imo == NULL) {
2256 return ENOMEM;
2257 }
2258
2259 IMO_LOCK(imo);
2260 idx = imo_match_group(imo, ifp, gsa);
2261 if (idx == (size_t)-1) {
2262 is_new = 1;
2263 } else {
2264 inm = imo->imo_membership[idx];
2265 imf = &imo->imo_mfilters[idx];
2266 if (ssa->sin_family != AF_UNSPEC) {
2267 /*
2268 * MCAST_JOIN_SOURCE_GROUP on an exclusive membership
2269 * is an error. On an existing inclusive membership,
2270 * it just adds the source to the filter list.
2271 */
2272 if (imf->imf_st[1] != MCAST_INCLUDE) {
2273 error = EINVAL;
2274 goto out_imo_locked;
2275 }
2276 /*
2277 * Throw out duplicates.
2278 *
2279 * XXX FIXME: This makes a naive assumption that
2280 * even if entries exist for *ssa in this imf,
2281 * they will be rejected as dupes, even if they
2282 * are not valid in the current mode (in-mode).
2283 *
2284 * in_msource is transactioned just as for anything
2285 * else in SSM -- but note naive use of inm_graft()
2286 * below for allocating new filter entries.
2287 *
2288 * This is only an issue if someone mixes the
2289 * full-state SSM API with the delta-based API,
2290 * which is discouraged in the relevant RFCs.
2291 */
2292 lims = imo_match_source(imo, idx, ssa);
2293 if (lims != NULL /*&&
2294 * lims->imsl_st[1] == MCAST_INCLUDE*/) {
2295 error = EADDRNOTAVAIL;
2296 goto out_imo_locked;
2297 }
2298 } else {
2299 /*
2300 * MCAST_JOIN_GROUP on an existing exclusive
2301 * membership is an error; return EADDRINUSE
2302 * to preserve 4.4BSD API idempotence, and
2303 * avoid tedious detour to code below.
2304 * NOTE: This is bending RFC 3678 a bit.
2305 *
2306 * On an existing inclusive membership, this is also
2307 * an error; if you want to change filter mode,
2308 * you must use the userland API setsourcefilter().
2309 * XXX We don't reject this for imf in UNDEFINED
2310 * state at t1, because allocation of a filter
2311 * is atomic with allocation of a membership.
2312 */
2313 error = EINVAL;
2314 /* See comments above for EADDRINUSE */
2315 if (imf->imf_st[1] == MCAST_EXCLUDE) {
2316 error = EADDRINUSE;
2317 }
2318 goto out_imo_locked;
2319 }
2320 }
2321
2322 /*
2323 * Begin state merge transaction at socket layer.
2324 */
2325
2326 if (is_new) {
2327 if (imo->imo_num_memberships == imo->imo_max_memberships) {
2328 error = imo_grow(imo, 0);
2329 if (error) {
2330 goto out_imo_locked;
2331 }
2332 }
2333 /*
2334 * Allocate the new slot upfront so we can deal with
2335 * grafting the new source filter in same code path
2336 * as for join-source on existing membership.
2337 */
2338 idx = imo->imo_num_memberships;
2339 imo->imo_membership[idx] = NULL;
2340 imo->imo_num_memberships++;
2341 VERIFY(imo->imo_mfilters != NULL);
2342 imf = &imo->imo_mfilters[idx];
2343 VERIFY(RB_EMPTY(&imf->imf_sources));
2344 }
2345
2346 /*
2347 * Graft new source into filter list for this inpcb's
2348 * membership of the group. The in_multi may not have
2349 * been allocated yet if this is a new membership, however,
2350 * the in_mfilter slot will be allocated and must be initialized.
2351 */
2352 if (ssa->sin_family != AF_UNSPEC) {
2353 /* Membership starts in IN mode */
2354 if (is_new) {
2355 IGMP_PRINTF(("%s: new join w/source\n", __func__));
2356 imf_init(imf, MCAST_UNDEFINED, MCAST_INCLUDE);
2357 } else {
2358 IGMP_PRINTF(("%s: %s source\n", __func__, "allow"));
2359 }
2360 lims = imf_graft(imf, MCAST_INCLUDE, ssa);
2361 if (lims == NULL) {
2362 IGMP_PRINTF(("%s: merge imf state failed\n",
2363 __func__));
2364 error = ENOMEM;
2365 goto out_imo_free;
2366 }
2367 } else {
2368 /* No address specified; Membership starts in EX mode */
2369 if (is_new) {
2370 IGMP_PRINTF(("%s: new join w/o source\n", __func__));
2371 imf_init(imf, MCAST_UNDEFINED, MCAST_EXCLUDE);
2372 }
2373 }
2374
2375 /*
2376 * Begin state merge transaction at IGMP layer.
2377 */
2378 if (is_new) {
2379 /*
2380 * Unlock socket as we may end up calling ifnet_ioctl() to join (or leave)
2381 * the multicast group and we run the risk of a lock ordering issue
2382 * if the ifnet thread calls into the socket layer to acquire the pcb list
2383 * lock while the input thread delivers multicast packets
2384 */
2385 IMO_ADDREF_LOCKED(imo);
2386 IMO_UNLOCK(imo);
2387 socket_unlock(inp->inp_socket, 0);
2388
2389 VERIFY(inm == NULL);
2390 error = in_joingroup(ifp, &gsa->sin_addr, imf, &inm);
2391
2392 socket_lock(inp->inp_socket, 0);
2393 IMO_REMREF(imo);
2394 IMO_LOCK(imo);
2395
2396 VERIFY(inm != NULL || error != 0);
2397 if (error) {
2398 goto out_imo_free;
2399 }
2400 imo->imo_membership[idx] = inm; /* from in_joingroup() */
2401 } else {
2402 IGMP_PRINTF(("%s: merge inm state\n", __func__));
2403 INM_LOCK(inm);
2404 error = inm_merge(inm, imf);
2405 if (error) {
2406 IGMP_PRINTF(("%s: failed to merge inm state\n",
2407 __func__));
2408 INM_UNLOCK(inm);
2409 goto out_imf_rollback;
2410 }
2411 IGMP_PRINTF(("%s: doing igmp downcall\n", __func__));
2412 error = igmp_change_state(inm, &itp);
2413 INM_UNLOCK(inm);
2414 if (error) {
2415 IGMP_PRINTF(("%s: failed igmp downcall\n",
2416 __func__));
2417 goto out_imf_rollback;
2418 }
2419 }
2420
2421out_imf_rollback:
2422 if (error) {
2423 imf_rollback(imf);
2424 if (is_new) {
2425 imf_purge(imf);
2426 } else {
2427 imf_reap(imf);
2428 }
2429 } else {
2430 imf_commit(imf);
2431 }
2432
2433out_imo_free:
2434 if (error && is_new) {
2435 VERIFY(inm == NULL);
2436 imo->imo_membership[idx] = NULL;
2437 --imo->imo_num_memberships;
2438 }
2439
2440out_imo_locked:
2441 IMO_UNLOCK(imo);
2442 IMO_REMREF(imo); /* from inp_findmoptions() */
2443
2444 /* schedule timer now that we've dropped the lock(s) */
2445 igmp_set_timeout(&itp);
2446
2447 return error;
2448}
2449
2450/*
2451 * Leave an IPv4 multicast group on an inpcb, possibly with a source.
2452 *
2453 * NB: sopt->sopt_val might point to the kernel address space. Refer to the
2454 * block comment on top of inp_join_group() for more information.
2455 */
2456int
2457inp_leave_group(struct inpcb *inp, struct sockopt *sopt)
2458{
2459 struct group_source_req gsr;
2460 struct ip_mreq_source mreqs;
2461 struct sockaddr_in *gsa, *ssa;
2462 struct ifnet *ifp;
2463 struct in_mfilter *imf;
2464 struct ip_moptions *imo;
2465 struct in_msource *ims;
2466 struct in_multi *inm = NULL;
2467 size_t idx;
2468 int error, is_final;
2469 unsigned int ifindex = 0;
2470 struct igmp_tparams itp;
2471
2472 bzero(&itp, sizeof(itp));
2473 ifp = NULL;
2474 error = 0;
2475 is_final = 1;
2476
2477 memset(&gsr, 0, sizeof(struct group_source_req));
2478 gsa = (struct sockaddr_in *)&gsr.gsr_group;
2479 ssa = (struct sockaddr_in *)&gsr.gsr_source;
2480
2481 switch (sopt->sopt_name) {
2482 case IP_DROP_MEMBERSHIP:
2483 case IP_DROP_SOURCE_MEMBERSHIP:
2484 if (sopt->sopt_name == IP_DROP_MEMBERSHIP) {
2485 error = sooptcopyin(sopt, &mreqs,
2486 sizeof(struct ip_mreq),
2487 sizeof(struct ip_mreq));
2488 /*
2489 * Swap interface and sourceaddr arguments,
2490 * as ip_mreq and ip_mreq_source are laid
2491 * out differently.
2492 */
2493 mreqs.imr_interface = mreqs.imr_sourceaddr;
2494 mreqs.imr_sourceaddr.s_addr = INADDR_ANY;
2495 } else if (sopt->sopt_name == IP_DROP_SOURCE_MEMBERSHIP) {
2496 error = sooptcopyin(sopt, &mreqs,
2497 sizeof(struct ip_mreq_source),
2498 sizeof(struct ip_mreq_source));
2499 }
2500 if (error) {
2501 return error;
2502 }
2503
2504 gsa->sin_family = AF_INET;
2505 gsa->sin_len = sizeof(struct sockaddr_in);
2506 gsa->sin_addr = mreqs.imr_multiaddr;
2507
2508 if (sopt->sopt_name == IP_DROP_SOURCE_MEMBERSHIP) {
2509 ssa->sin_family = AF_INET;
2510 ssa->sin_len = sizeof(struct sockaddr_in);
2511 ssa->sin_addr = mreqs.imr_sourceaddr;
2512 }
2513 /*
2514 * Attempt to look up hinted ifp from interface address.
2515 * Fallthrough with null ifp iff lookup fails, to
2516 * preserve 4.4BSD mcast API idempotence.
2517 * XXX NOTE WELL: The RFC 3678 API is preferred because
2518 * using an IPv4 address as a key is racy.
2519 */
2520 if (!in_nullhost(mreqs.imr_interface)) {
2521 ifp = ip_multicast_if(&mreqs.imr_interface, &ifindex);
2522 }
2523
2524 IGMP_INET_PRINTF(mreqs.imr_interface,
2525 ("%s: imr_interface = %s, ifp = 0x%llx\n", __func__,
2526 _igmp_inet_buf, (uint64_t)VM_KERNEL_ADDRPERM(ifp)));
2527
2528 break;
2529
2530 case MCAST_LEAVE_GROUP:
2531 case MCAST_LEAVE_SOURCE_GROUP:
2532 if (sopt->sopt_name == MCAST_LEAVE_GROUP) {
2533 error = sooptcopyin(sopt, &gsr,
2534 sizeof(struct group_req),
2535 sizeof(struct group_req));
2536 } else if (sopt->sopt_name == MCAST_LEAVE_SOURCE_GROUP) {
2537 error = sooptcopyin(sopt, &gsr,
2538 sizeof(struct group_source_req),
2539 sizeof(struct group_source_req));
2540 }
2541 if (error) {
2542 return error;
2543 }
2544
2545 if (gsa->sin_family != AF_INET ||
2546 gsa->sin_len != sizeof(struct sockaddr_in)) {
2547 return EINVAL;
2548 }
2549
2550 if (sopt->sopt_name == MCAST_LEAVE_SOURCE_GROUP) {
2551 if (ssa->sin_family != AF_INET ||
2552 ssa->sin_len != sizeof(struct sockaddr_in)) {
2553 return EINVAL;
2554 }
2555 }
2556
2557 ifnet_head_lock_shared();
2558 if (gsr.gsr_interface == 0 ||
2559 (u_int)if_index < gsr.gsr_interface) {
2560 ifnet_head_done();
2561 return EADDRNOTAVAIL;
2562 }
2563
2564 ifp = ifindex2ifnet[gsr.gsr_interface];
2565 ifnet_head_done();
2566 break;
2567
2568 default:
2569 IGMP_PRINTF(("%s: unknown sopt_name %d\n",
2570 __func__, sopt->sopt_name));
2571 return EOPNOTSUPP;
2572 }
2573
2574 if (!IN_MULTICAST(ntohl(gsa->sin_addr.s_addr))) {
2575 return EINVAL;
2576 }
2577
2578 /*
2579 * Find the membership in the membership array.
2580 */
2581 imo = inp_findmoptions(inp);
2582 if (imo == NULL) {
2583 return ENOMEM;
2584 }
2585
2586 IMO_LOCK(imo);
2587 idx = imo_match_group(imo, ifp, gsa);
2588 if (idx == (size_t)-1) {
2589 error = EADDRNOTAVAIL;
2590 goto out_locked;
2591 }
2592 inm = imo->imo_membership[idx];
2593 imf = &imo->imo_mfilters[idx];
2594
2595 if (ssa->sin_family != AF_UNSPEC) {
2596 IGMP_PRINTF(("%s: opt=%d is_final=0\n", __func__,
2597 sopt->sopt_name));
2598 is_final = 0;
2599 }
2600
2601 /*
2602 * Begin state merge transaction at socket layer.
2603 */
2604
2605 /*
2606 * If we were instructed only to leave a given source, do so.
2607 * MCAST_LEAVE_SOURCE_GROUP is only valid for inclusive memberships.
2608 */
2609 if (is_final) {
2610 imf_leave(imf);
2611 } else {
2612 if (imf->imf_st[0] == MCAST_EXCLUDE) {
2613 error = EADDRNOTAVAIL;
2614 goto out_locked;
2615 }
2616 ims = imo_match_source(imo, idx, ssa);
2617 if (ims == NULL) {
2618 IGMP_INET_PRINTF(ssa->sin_addr,
2619 ("%s: source %s %spresent\n", __func__,
2620 _igmp_inet_buf, "not "));
2621 error = EADDRNOTAVAIL;
2622 goto out_locked;
2623 }
2624 IGMP_PRINTF(("%s: %s source\n", __func__, "block"));
2625 error = imf_prune(imf, ssa);
2626 if (error) {
2627 IGMP_PRINTF(("%s: merge imf state failed\n",
2628 __func__));
2629 goto out_locked;
2630 }
2631 }
2632
2633 /*
2634 * Begin state merge transaction at IGMP layer.
2635 */
2636
2637
2638 if (is_final) {
2639 /*
2640 * Give up the multicast address record to which
2641 * the membership points. Reference held in imo
2642 * will be released below.
2643 */
2644 (void) in_leavegroup(inm, imf);
2645 } else {
2646 IGMP_PRINTF(("%s: merge inm state\n", __func__));
2647 INM_LOCK(inm);
2648 error = inm_merge(inm, imf);
2649 if (error) {
2650 IGMP_PRINTF(("%s: failed to merge inm state\n",
2651 __func__));
2652 INM_UNLOCK(inm);
2653 goto out_imf_rollback;
2654 }
2655
2656 IGMP_PRINTF(("%s: doing igmp downcall\n", __func__));
2657 error = igmp_change_state(inm, &itp);
2658 if (error) {
2659 IGMP_PRINTF(("%s: failed igmp downcall\n", __func__));
2660 }
2661 INM_UNLOCK(inm);
2662 }
2663
2664out_imf_rollback:
2665 if (error) {
2666 imf_rollback(imf);
2667 } else {
2668 imf_commit(imf);
2669 }
2670
2671 imf_reap(imf);
2672
2673 if (is_final) {
2674 /* Remove the gap in the membership array. */
2675 VERIFY(inm == imo->imo_membership[idx]);
2676 imo->imo_membership[idx] = NULL;
2677
2678 /*
2679 * See inp_join_group() for why we need to unlock
2680 */
2681 IMO_ADDREF_LOCKED(imo);
2682 IMO_UNLOCK(imo);
2683 socket_unlock(inp->inp_socket, 0);
2684
2685 INM_REMREF(inm);
2686
2687 socket_lock(inp->inp_socket, 0);
2688 IMO_REMREF(imo);
2689 IMO_LOCK(imo);
2690
2691 for (++idx; idx < imo->imo_num_memberships; ++idx) {
2692 imo->imo_membership[idx - 1] = imo->imo_membership[idx];
2693 imo->imo_mfilters[idx - 1] = imo->imo_mfilters[idx];
2694 }
2695 imo->imo_num_memberships--;
2696 }
2697
2698out_locked:
2699 IMO_UNLOCK(imo);
2700 IMO_REMREF(imo); /* from inp_findmoptions() */
2701
2702 /* schedule timer now that we've dropped the lock(s) */
2703 igmp_set_timeout(&itp);
2704
2705 return error;
2706}
2707
2708/*
2709 * Select the interface for transmitting IPv4 multicast datagrams.
2710 *
2711 * Either an instance of struct in_addr or an instance of struct ip_mreqn
2712 * may be passed to this socket option. An address of INADDR_ANY or an
2713 * interface index of 0 is used to remove a previous selection.
2714 * When no interface is selected, one is chosen for every send.
2715 */
2716static int
2717inp_set_multicast_if(struct inpcb *inp, struct sockopt *sopt)
2718{
2719 struct in_addr addr;
2720 struct ip_mreqn mreqn;
2721 struct ifnet *ifp;
2722 struct ip_moptions *imo;
2723 int error = 0;
2724 unsigned int ifindex = 0;
2725
2726 bzero(&addr, sizeof(addr));
2727 if (sopt->sopt_valsize == sizeof(struct ip_mreqn)) {
2728 /*
2729 * An interface index was specified using the
2730 * Linux-derived ip_mreqn structure.
2731 */
2732 error = sooptcopyin(sopt, &mreqn, sizeof(struct ip_mreqn),
2733 sizeof(struct ip_mreqn));
2734 if (error) {
2735 return error;
2736 }
2737
2738 ifnet_head_lock_shared();
2739 if (mreqn.imr_ifindex < 0 || if_index < mreqn.imr_ifindex) {
2740 ifnet_head_done();
2741 return EINVAL;
2742 }
2743
2744 if (mreqn.imr_ifindex == 0) {
2745 ifp = NULL;
2746 } else {
2747 ifp = ifindex2ifnet[mreqn.imr_ifindex];
2748 if (ifp == NULL) {
2749 ifnet_head_done();
2750 return EADDRNOTAVAIL;
2751 }
2752 }
2753 ifnet_head_done();
2754 } else {
2755 /*
2756 * An interface was specified by IPv4 address.
2757 * This is the traditional BSD usage.
2758 */
2759 error = sooptcopyin(sopt, &addr, sizeof(struct in_addr),
2760 sizeof(struct in_addr));
2761 if (error) {
2762 return error;
2763 }
2764 if (in_nullhost(addr)) {
2765 ifp = NULL;
2766 } else {
2767 ifp = ip_multicast_if(&addr, &ifindex);
2768 if (ifp == NULL) {
2769 IGMP_INET_PRINTF(addr,
2770 ("%s: can't find ifp for addr=%s\n",
2771 __func__, _igmp_inet_buf));
2772 return EADDRNOTAVAIL;
2773 }
2774 }
2775 }
2776
2777 /* Reject interfaces which do not support multicast. */
2778 if (ifp != NULL && (ifp->if_flags & IFF_MULTICAST) == 0) {
2779 return EOPNOTSUPP;
2780 }
2781
2782 imo = inp_findmoptions(inp);
2783 if (imo == NULL) {
2784 return ENOMEM;
2785 }
2786
2787 IMO_LOCK(imo);
2788 imo->imo_multicast_ifp = ifp;
2789 if (ifindex) {
2790 imo->imo_multicast_addr = addr;
2791 } else {
2792 imo->imo_multicast_addr.s_addr = INADDR_ANY;
2793 }
2794 IMO_UNLOCK(imo);
2795 IMO_REMREF(imo); /* from inp_findmoptions() */
2796
2797 return 0;
2798}
2799
2800/*
2801 * Atomically set source filters on a socket for an IPv4 multicast group.
2802 */
2803static int
2804inp_set_source_filters(struct inpcb *inp, struct sockopt *sopt)
2805{
2806 struct __msfilterreq64 msfr = {}, msfr64;
2807 struct __msfilterreq32 msfr32;
2808 struct sockaddr_in *gsa;
2809 struct ifnet *ifp;
2810 struct in_mfilter *imf;
2811 struct ip_moptions *imo;
2812 struct in_multi *inm;
2813 size_t idx;
2814 int error;
2815 user_addr_t tmp_ptr;
2816 struct igmp_tparams itp;
2817
2818 bzero(&itp, sizeof(itp));
2819
2820 if (IS_64BIT_PROCESS(current_proc())) {
2821 error = sooptcopyin(sopt, &msfr64,
2822 sizeof(struct __msfilterreq64),
2823 sizeof(struct __msfilterreq64));
2824 if (error) {
2825 return error;
2826 }
2827 /* we never use msfr.msfr_srcs; */
2828 memcpy(&msfr, &msfr64, sizeof(msfr64));
2829 } else {
2830 error = sooptcopyin(sopt, &msfr32,
2831 sizeof(struct __msfilterreq32),
2832 sizeof(struct __msfilterreq32));
2833 if (error) {
2834 return error;
2835 }
2836 /* we never use msfr.msfr_srcs; */
2837 memcpy(&msfr, &msfr32, sizeof(msfr32));
2838 }
2839
2840 if ((size_t) msfr.msfr_nsrcs >
2841 UINT32_MAX / sizeof(struct sockaddr_storage)) {
2842 msfr.msfr_nsrcs = UINT32_MAX / sizeof(struct sockaddr_storage);
2843 }
2844
2845 if (msfr.msfr_nsrcs > in_mcast_maxsocksrc) {
2846 return ENOBUFS;
2847 }
2848
2849 if ((msfr.msfr_fmode != MCAST_EXCLUDE &&
2850 msfr.msfr_fmode != MCAST_INCLUDE)) {
2851 return EINVAL;
2852 }
2853
2854 if (msfr.msfr_group.ss_family != AF_INET ||
2855 msfr.msfr_group.ss_len != sizeof(struct sockaddr_in)) {
2856 return EINVAL;
2857 }
2858
2859 gsa = (struct sockaddr_in *)&msfr.msfr_group;
2860 if (!IN_MULTICAST(ntohl(gsa->sin_addr.s_addr))) {
2861 return EINVAL;
2862 }
2863
2864 gsa->sin_port = 0; /* ignore port */
2865
2866 ifnet_head_lock_shared();
2867 if (msfr.msfr_ifindex == 0 || (u_int)if_index < msfr.msfr_ifindex) {
2868 ifnet_head_done();
2869 return EADDRNOTAVAIL;
2870 }
2871
2872 ifp = ifindex2ifnet[msfr.msfr_ifindex];
2873 ifnet_head_done();
2874 if (ifp == NULL) {
2875 return EADDRNOTAVAIL;
2876 }
2877
2878 /*
2879 * Check if this socket is a member of this group.
2880 */
2881 imo = inp_findmoptions(inp);
2882 if (imo == NULL) {
2883 return ENOMEM;
2884 }
2885
2886 IMO_LOCK(imo);
2887 idx = imo_match_group(imo, ifp, gsa);
2888 if (idx == (size_t)-1 || imo->imo_mfilters == NULL) {
2889 error = EADDRNOTAVAIL;
2890 goto out_imo_locked;
2891 }
2892 inm = imo->imo_membership[idx];
2893 imf = &imo->imo_mfilters[idx];
2894
2895 /*
2896 * Begin state merge transaction at socket layer.
2897 */
2898
2899 imf->imf_st[1] = msfr.msfr_fmode;
2900
2901 /*
2902 * Apply any new source filters, if present.
2903 * Make a copy of the user-space source vector so
2904 * that we may copy them with a single copyin. This
2905 * allows us to deal with page faults up-front.
2906 */
2907 if (msfr.msfr_nsrcs > 0) {
2908 struct in_msource *lims;
2909 struct sockaddr_in *psin;
2910 struct sockaddr_storage *kss, *pkss;
2911 int i;
2912
2913 if (IS_64BIT_PROCESS(current_proc())) {
2914 tmp_ptr = msfr64.msfr_srcs;
2915 } else {
2916 tmp_ptr = CAST_USER_ADDR_T(msfr32.msfr_srcs);
2917 }
2918
2919 IGMP_PRINTF(("%s: loading %lu source list entries\n",
2920 __func__, (unsigned long)msfr.msfr_nsrcs));
2921 kss = _MALLOC((size_t) msfr.msfr_nsrcs * sizeof(*kss),
2922 M_TEMP, M_WAITOK);
2923 if (kss == NULL) {
2924 error = ENOMEM;
2925 goto out_imo_locked;
2926 }
2927 error = copyin(tmp_ptr, kss,
2928 (size_t) msfr.msfr_nsrcs * sizeof(*kss));
2929 if (error) {
2930 FREE(kss, M_TEMP);
2931 goto out_imo_locked;
2932 }
2933
2934 /*
2935 * Mark all source filters as UNDEFINED at t1.
2936 * Restore new group filter mode, as imf_leave()
2937 * will set it to INCLUDE.
2938 */
2939 imf_leave(imf);
2940 imf->imf_st[1] = msfr.msfr_fmode;
2941
2942 /*
2943 * Update socket layer filters at t1, lazy-allocating
2944 * new entries. This saves a bunch of memory at the
2945 * cost of one RB_FIND() per source entry; duplicate
2946 * entries in the msfr_nsrcs vector are ignored.
2947 * If we encounter an error, rollback transaction.
2948 *
2949 * XXX This too could be replaced with a set-symmetric
2950 * difference like loop to avoid walking from root
2951 * every time, as the key space is common.
2952 */
2953 for (i = 0, pkss = kss; (u_int)i < msfr.msfr_nsrcs;
2954 i++, pkss++) {
2955 psin = (struct sockaddr_in *)pkss;
2956 if (psin->sin_family != AF_INET) {
2957 error = EAFNOSUPPORT;
2958 break;
2959 }
2960 if (psin->sin_len != sizeof(struct sockaddr_in)) {
2961 error = EINVAL;
2962 break;
2963 }
2964 error = imf_get_source(imf, psin, &lims);
2965 if (error) {
2966 break;
2967 }
2968 lims->imsl_st[1] = imf->imf_st[1];
2969 }
2970 FREE(kss, M_TEMP);
2971 }
2972
2973 if (error) {
2974 goto out_imf_rollback;
2975 }
2976
2977 /*
2978 * Begin state merge transaction at IGMP layer.
2979 */
2980 INM_LOCK(inm);
2981 IGMP_PRINTF(("%s: merge inm state\n", __func__));
2982 error = inm_merge(inm, imf);
2983 if (error) {
2984 IGMP_PRINTF(("%s: failed to merge inm state\n", __func__));
2985 INM_UNLOCK(inm);
2986 goto out_imf_rollback;
2987 }
2988
2989 IGMP_PRINTF(("%s: doing igmp downcall\n", __func__));
2990 error = igmp_change_state(inm, &itp);
2991 INM_UNLOCK(inm);
2992#ifdef IGMP_DEBUG
2993 if (error) {
2994 IGMP_PRINTF(("%s: failed igmp downcall\n", __func__));
2995 }
2996#endif
2997
2998out_imf_rollback:
2999 if (error) {
3000 imf_rollback(imf);
3001 } else {
3002 imf_commit(imf);
3003 }
3004
3005 imf_reap(imf);
3006
3007out_imo_locked:
3008 IMO_UNLOCK(imo);
3009 IMO_REMREF(imo); /* from inp_findmoptions() */
3010
3011 /* schedule timer now that we've dropped the lock(s) */
3012 igmp_set_timeout(&itp);
3013
3014 return error;
3015}
3016
3017/*
3018 * Set the IP multicast options in response to user setsockopt().
3019 *
3020 * Many of the socket options handled in this function duplicate the
3021 * functionality of socket options in the regular unicast API. However,
3022 * it is not possible to merge the duplicate code, because the idempotence
3023 * of the IPv4 multicast part of the BSD Sockets API must be preserved;
3024 * the effects of these options must be treated as separate and distinct.
3025 */
3026int
3027inp_setmoptions(struct inpcb *inp, struct sockopt *sopt)
3028{
3029 struct ip_moptions *imo;
3030 int error;
3031 unsigned int ifindex;
3032 struct ifnet *ifp;
3033
3034 error = 0;
3035
3036 /*
3037 * If socket is neither of type SOCK_RAW or SOCK_DGRAM,
3038 * or is a divert socket, reject it.
3039 */
3040 if (SOCK_PROTO(inp->inp_socket) == IPPROTO_DIVERT ||
3041 (SOCK_TYPE(inp->inp_socket) != SOCK_RAW &&
3042 SOCK_TYPE(inp->inp_socket) != SOCK_DGRAM)) {
3043 return EOPNOTSUPP;
3044 }
3045
3046 switch (sopt->sopt_name) {
3047 case IP_MULTICAST_IF:
3048 error = inp_set_multicast_if(inp, sopt);
3049 break;
3050
3051 case IP_MULTICAST_IFINDEX:
3052 /*
3053 * Select the interface for outgoing multicast packets.
3054 */
3055 error = sooptcopyin(sopt, &ifindex, sizeof(ifindex),
3056 sizeof(ifindex));
3057 if (error) {
3058 break;
3059 }
3060
3061 imo = inp_findmoptions(inp);
3062 if (imo == NULL) {
3063 error = ENOMEM;
3064 break;
3065 }
3066 /*
3067 * Index 0 is used to remove a previous selection.
3068 * When no interface is selected, a default one is
3069 * chosen every time a multicast packet is sent.
3070 */
3071 if (ifindex == 0) {
3072 IMO_LOCK(imo);
3073 imo->imo_multicast_ifp = NULL;
3074 IMO_UNLOCK(imo);
3075 IMO_REMREF(imo); /* from inp_findmoptions() */
3076 break;
3077 }
3078
3079 ifnet_head_lock_shared();
3080 /* Don't need to check is ifindex is < 0 since it's unsigned */
3081 if ((unsigned int)if_index < ifindex) {
3082 ifnet_head_done();
3083 IMO_REMREF(imo); /* from inp_findmoptions() */
3084 error = ENXIO; /* per IPV6_MULTICAST_IF */
3085 break;
3086 }
3087 ifp = ifindex2ifnet[ifindex];
3088 ifnet_head_done();
3089
3090 /* If it's detached or isn't a multicast interface, bail out */
3091 if (ifp == NULL || !(ifp->if_flags & IFF_MULTICAST)) {
3092 IMO_REMREF(imo); /* from inp_findmoptions() */
3093 error = EADDRNOTAVAIL;
3094 break;
3095 }
3096 IMO_LOCK(imo);
3097 imo->imo_multicast_ifp = ifp;
3098 /*
3099 * Clear out any remnants of past IP_MULTICAST_IF. The addr
3100 * isn't really used anywhere in the kernel; we could have
3101 * iterated thru the addresses of the interface and pick one
3102 * here, but that is redundant since ip_getmoptions() already
3103 * takes care of that for INADDR_ANY.
3104 */
3105 imo->imo_multicast_addr.s_addr = INADDR_ANY;
3106 IMO_UNLOCK(imo);
3107 IMO_REMREF(imo); /* from inp_findmoptions() */
3108 break;
3109
3110 case IP_MULTICAST_TTL: {
3111 u_char ttl;
3112
3113 /*
3114 * Set the IP time-to-live for outgoing multicast packets.
3115 * The original multicast API required a char argument,
3116 * which is inconsistent with the rest of the socket API.
3117 * We allow either a char or an int.
3118 */
3119 if (sopt->sopt_valsize == sizeof(u_char)) {
3120 error = sooptcopyin(sopt, &ttl, sizeof(u_char),
3121 sizeof(u_char));
3122 if (error) {
3123 break;
3124 }
3125 } else {
3126 u_int ittl;
3127
3128 error = sooptcopyin(sopt, &ittl, sizeof(u_int),
3129 sizeof(u_int));
3130 if (error) {
3131 break;
3132 }
3133 if (ittl > 255) {
3134 error = EINVAL;
3135 break;
3136 }
3137 ttl = (u_char)ittl;
3138 }
3139 imo = inp_findmoptions(inp);
3140 if (imo == NULL) {
3141 error = ENOMEM;
3142 break;
3143 }
3144 IMO_LOCK(imo);
3145 imo->imo_multicast_ttl = ttl;
3146 IMO_UNLOCK(imo);
3147 IMO_REMREF(imo); /* from inp_findmoptions() */
3148 break;
3149 }
3150
3151 case IP_MULTICAST_LOOP: {
3152 u_char loop;
3153
3154 /*
3155 * Set the loopback flag for outgoing multicast packets.
3156 * Must be zero or one. The original multicast API required a
3157 * char argument, which is inconsistent with the rest
3158 * of the socket API. We allow either a char or an int.
3159 */
3160 if (sopt->sopt_valsize == sizeof(u_char)) {
3161 error = sooptcopyin(sopt, &loop, sizeof(u_char),
3162 sizeof(u_char));
3163 if (error) {
3164 break;
3165 }
3166 } else {
3167 u_int iloop;
3168
3169 error = sooptcopyin(sopt, &iloop, sizeof(u_int),
3170 sizeof(u_int));
3171 if (error) {
3172 break;
3173 }
3174 loop = (u_char)iloop;
3175 }
3176 imo = inp_findmoptions(inp);
3177 if (imo == NULL) {
3178 error = ENOMEM;
3179 break;
3180 }
3181 IMO_LOCK(imo);
3182 imo->imo_multicast_loop = !!loop;
3183 IMO_UNLOCK(imo);
3184 IMO_REMREF(imo); /* from inp_findmoptions() */
3185 break;
3186 }
3187
3188 case IP_ADD_MEMBERSHIP:
3189 case IP_ADD_SOURCE_MEMBERSHIP:
3190 case MCAST_JOIN_GROUP:
3191 case MCAST_JOIN_SOURCE_GROUP:
3192 error = inp_join_group(inp, sopt);
3193 break;
3194
3195 case IP_DROP_MEMBERSHIP:
3196 case IP_DROP_SOURCE_MEMBERSHIP:
3197 case MCAST_LEAVE_GROUP:
3198 case MCAST_LEAVE_SOURCE_GROUP:
3199 error = inp_leave_group(inp, sopt);
3200 break;
3201
3202 case IP_BLOCK_SOURCE:
3203 case IP_UNBLOCK_SOURCE:
3204 case MCAST_BLOCK_SOURCE:
3205 case MCAST_UNBLOCK_SOURCE:
3206 error = inp_block_unblock_source(inp, sopt);
3207 break;
3208
3209 case IP_MSFILTER:
3210 error = inp_set_source_filters(inp, sopt);
3211 break;
3212
3213 default:
3214 error = EOPNOTSUPP;
3215 break;
3216 }
3217
3218 return error;
3219}
3220
3221/*
3222 * Expose IGMP's multicast filter mode and source list(s) to userland,
3223 * keyed by (ifindex, group).
3224 * The filter mode is written out as a uint32_t, followed by
3225 * 0..n of struct in_addr.
3226 * For use by ifmcstat(8).
3227 */
3228static int
3229sysctl_ip_mcast_filters SYSCTL_HANDLER_ARGS
3230{
3231#pragma unused(oidp)
3232
3233 struct in_addr src = {}, group;
3234 struct ifnet *ifp;
3235 struct in_multi *inm;
3236 struct in_multistep step;
3237 struct ip_msource *ims;
3238 int *name;
3239 int retval = 0;
3240 u_int namelen;
3241 uint32_t fmode, ifindex;
3242
3243 name = (int *)arg1;
3244 namelen = (u_int)arg2;
3245
3246 if (req->newptr != USER_ADDR_NULL) {
3247 return EPERM;
3248 }
3249
3250 if (namelen != 2) {
3251 return EINVAL;
3252 }
3253
3254 ifindex = name[0];
3255 ifnet_head_lock_shared();
3256 if (ifindex <= 0 || ifindex > (u_int)if_index) {
3257 IGMP_PRINTF(("%s: ifindex %u out of range\n",
3258 __func__, ifindex));
3259 ifnet_head_done();
3260 return ENOENT;
3261 }
3262
3263 group.s_addr = name[1];
3264 if (!IN_MULTICAST(ntohl(group.s_addr))) {
3265 IGMP_INET_PRINTF(group,
3266 ("%s: group %s is not multicast\n",
3267 __func__, _igmp_inet_buf));
3268 ifnet_head_done();
3269 return EINVAL;
3270 }
3271
3272 ifp = ifindex2ifnet[ifindex];
3273 ifnet_head_done();
3274 if (ifp == NULL) {
3275 IGMP_PRINTF(("%s: no ifp for ifindex %u\n", __func__, ifindex));
3276 return ENOENT;
3277 }
3278
3279 in_multihead_lock_shared();
3280 IN_FIRST_MULTI(step, inm);
3281 while (inm != NULL) {
3282 INM_LOCK(inm);
3283 if (inm->inm_ifp != ifp) {
3284 goto next;
3285 }
3286
3287 if (!in_hosteq(inm->inm_addr, group)) {
3288 goto next;
3289 }
3290
3291 fmode = inm->inm_st[1].iss_fmode;
3292 retval = SYSCTL_OUT(req, &fmode, sizeof(uint32_t));
3293 if (retval != 0) {
3294 INM_UNLOCK(inm);
3295 break; /* abort */
3296 }
3297 RB_FOREACH(ims, ip_msource_tree, &inm->inm_srcs) {
3298#ifdef IGMP_DEBUG
3299 struct in_addr ina;
3300 ina.s_addr = htonl(ims->ims_haddr);
3301 IGMP_INET_PRINTF(ina,
3302 ("%s: visit node %s\n", __func__, _igmp_inet_buf));
3303#endif
3304 /*
3305 * Only copy-out sources which are in-mode.
3306 */
3307 if (fmode != ims_get_mode(inm, ims, 1)) {
3308 IGMP_PRINTF(("%s: skip non-in-mode\n",
3309 __func__));
3310 continue; /* process next source */
3311 }
3312 src.s_addr = htonl(ims->ims_haddr);
3313 retval = SYSCTL_OUT(req, &src, sizeof(struct in_addr));
3314 if (retval != 0) {
3315 break; /* process next inm */
3316 }
3317 }
3318next:
3319 INM_UNLOCK(inm);
3320 IN_NEXT_MULTI(step, inm);
3321 }
3322 in_multihead_lock_done();
3323
3324 return retval;
3325}
3326
3327/*
3328 * XXX
3329 * The whole multicast option thing needs to be re-thought.
3330 * Several of these options are equally applicable to non-multicast
3331 * transmission, and one (IP_MULTICAST_TTL) totally duplicates a
3332 * standard option (IP_TTL).
3333 */
3334/*
3335 * following RFC1724 section 3.3, 0.0.0.0/8 is interpreted as interface index.
3336 */
3337static struct ifnet *
3338ip_multicast_if(struct in_addr *a, unsigned int *ifindexp)
3339{
3340 unsigned int ifindex;
3341 struct ifnet *ifp;
3342
3343 if (ifindexp != NULL) {
3344 *ifindexp = 0;
3345 }
3346 if (ntohl(a->s_addr) >> 24 == 0) {
3347 ifindex = ntohl(a->s_addr) & 0xffffff;
3348 ifnet_head_lock_shared();
3349 /* Don't need to check is ifindex is < 0 since it's unsigned */
3350 if ((unsigned int)if_index < ifindex) {
3351 ifnet_head_done();
3352 return NULL;
3353 }
3354 ifp = ifindex2ifnet[ifindex];
3355 ifnet_head_done();
3356 if (ifp != NULL && ifindexp != NULL) {
3357 *ifindexp = ifindex;
3358 }
3359 } else {
3360 INADDR_TO_IFP(*a, ifp);
3361 }
3362 return ifp;
3363}
3364
3365void
3366in_multi_init(void)
3367{
3368 PE_parse_boot_argn("ifa_debug", &inm_debug, sizeof(inm_debug));
3369
3370 /* Setup lock group and attribute for in_multihead */
3371 in_multihead_lock_grp_attr = lck_grp_attr_alloc_init();
3372 in_multihead_lock_grp = lck_grp_alloc_init("in_multihead",
3373 in_multihead_lock_grp_attr);
3374 in_multihead_lock_attr = lck_attr_alloc_init();
3375 lck_rw_init(&in_multihead_lock, in_multihead_lock_grp,
3376 in_multihead_lock_attr);
3377
3378 lck_mtx_init(&inm_trash_lock, in_multihead_lock_grp,
3379 in_multihead_lock_attr);
3380 TAILQ_INIT(&inm_trash_head);
3381
3382 inm_size = (inm_debug == 0) ? sizeof(struct in_multi) :
3383 sizeof(struct in_multi_dbg);
3384 inm_zone = zinit(inm_size, INM_ZONE_MAX * inm_size,
3385 0, INM_ZONE_NAME);
3386 if (inm_zone == NULL) {
3387 panic("%s: failed allocating %s", __func__, INM_ZONE_NAME);
3388 /* NOTREACHED */
3389 }
3390 zone_change(inm_zone, Z_EXPAND, TRUE);
3391
3392 ipms_size = sizeof(struct ip_msource);
3393 ipms_zone = zinit(ipms_size, IPMS_ZONE_MAX * ipms_size,
3394 0, IPMS_ZONE_NAME);
3395 if (ipms_zone == NULL) {
3396 panic("%s: failed allocating %s", __func__, IPMS_ZONE_NAME);
3397 /* NOTREACHED */
3398 }
3399 zone_change(ipms_zone, Z_EXPAND, TRUE);
3400
3401 inms_size = sizeof(struct in_msource);
3402 inms_zone = zinit(inms_size, INMS_ZONE_MAX * inms_size,
3403 0, INMS_ZONE_NAME);
3404 if (inms_zone == NULL) {
3405 panic("%s: failed allocating %s", __func__, INMS_ZONE_NAME);
3406 /* NOTREACHED */
3407 }
3408 zone_change(inms_zone, Z_EXPAND, TRUE);
3409}
3410
3411static struct in_multi *
3412in_multi_alloc(int how)
3413{
3414 struct in_multi *inm;
3415
3416 inm = (how == M_WAITOK) ? zalloc(inm_zone) : zalloc_noblock(inm_zone);
3417 if (inm != NULL) {
3418 bzero(inm, inm_size);
3419 lck_mtx_init(&inm->inm_lock, in_multihead_lock_grp,
3420 in_multihead_lock_attr);
3421 inm->inm_debug |= IFD_ALLOC;
3422 if (inm_debug != 0) {
3423 inm->inm_debug |= IFD_DEBUG;
3424 inm->inm_trace = inm_trace;
3425 }
3426 }
3427 return inm;
3428}
3429
3430static void
3431in_multi_free(struct in_multi *inm)
3432{
3433 INM_LOCK(inm);
3434 if (inm->inm_debug & IFD_ATTACHED) {
3435 panic("%s: attached inm=%p is being freed", __func__, inm);
3436 /* NOTREACHED */
3437 } else if (inm->inm_ifma != NULL) {
3438 panic("%s: ifma not NULL for inm=%p", __func__, inm);
3439 /* NOTREACHED */
3440 } else if (!(inm->inm_debug & IFD_ALLOC)) {
3441 panic("%s: inm %p cannot be freed", __func__, inm);
3442 /* NOTREACHED */
3443 } else if (inm->inm_refcount != 0) {
3444 panic("%s: non-zero refcount inm=%p", __func__, inm);
3445 /* NOTREACHED */
3446 } else if (inm->inm_reqcnt != 0) {
3447 panic("%s: non-zero reqcnt inm=%p", __func__, inm);
3448 /* NOTREACHED */
3449 }
3450
3451 /* Free any pending IGMPv3 state-change records */
3452 IF_DRAIN(&inm->inm_scq);
3453
3454 inm->inm_debug &= ~IFD_ALLOC;
3455 if ((inm->inm_debug & (IFD_DEBUG | IFD_TRASHED)) ==
3456 (IFD_DEBUG | IFD_TRASHED)) {
3457 lck_mtx_lock(&inm_trash_lock);
3458 TAILQ_REMOVE(&inm_trash_head, (struct in_multi_dbg *)inm,
3459 inm_trash_link);
3460 lck_mtx_unlock(&inm_trash_lock);
3461 inm->inm_debug &= ~IFD_TRASHED;
3462 }
3463 INM_UNLOCK(inm);
3464
3465 lck_mtx_destroy(&inm->inm_lock, in_multihead_lock_grp);
3466 zfree(inm_zone, inm);
3467}
3468
3469static void
3470in_multi_attach(struct in_multi *inm)
3471{
3472 in_multihead_lock_assert(LCK_RW_ASSERT_EXCLUSIVE);
3473 INM_LOCK_ASSERT_HELD(inm);
3474
3475 if (inm->inm_debug & IFD_ATTACHED) {
3476 panic("%s: Attempt to attach an already attached inm=%p",
3477 __func__, inm);
3478 /* NOTREACHED */
3479 } else if (inm->inm_debug & IFD_TRASHED) {
3480 panic("%s: Attempt to reattach a detached inm=%p",
3481 __func__, inm);
3482 /* NOTREACHED */
3483 }
3484
3485 inm->inm_reqcnt++;
3486 VERIFY(inm->inm_reqcnt == 1);
3487 INM_ADDREF_LOCKED(inm);
3488 inm->inm_debug |= IFD_ATTACHED;
3489 /*
3490 * Reattach case: If debugging is enabled, take it
3491 * out of the trash list and clear IFD_TRASHED.
3492 */
3493 if ((inm->inm_debug & (IFD_DEBUG | IFD_TRASHED)) ==
3494 (IFD_DEBUG | IFD_TRASHED)) {
3495 /* Become a regular mutex, just in case */
3496 INM_CONVERT_LOCK(inm);
3497 lck_mtx_lock(&inm_trash_lock);
3498 TAILQ_REMOVE(&inm_trash_head, (struct in_multi_dbg *)inm,
3499 inm_trash_link);
3500 lck_mtx_unlock(&inm_trash_lock);
3501 inm->inm_debug &= ~IFD_TRASHED;
3502 }
3503
3504 LIST_INSERT_HEAD(&in_multihead, inm, inm_link);
3505}
3506
3507int
3508in_multi_detach(struct in_multi *inm)
3509{
3510 in_multihead_lock_assert(LCK_RW_ASSERT_EXCLUSIVE);
3511 INM_LOCK_ASSERT_HELD(inm);
3512
3513 if (inm->inm_reqcnt == 0) {
3514 panic("%s: inm=%p negative reqcnt", __func__, inm);
3515 /* NOTREACHED */
3516 }
3517
3518 --inm->inm_reqcnt;
3519 if (inm->inm_reqcnt > 0) {
3520 return 0;
3521 }
3522
3523 if (!(inm->inm_debug & IFD_ATTACHED)) {
3524 panic("%s: Attempt to detach an unattached record inm=%p",
3525 __func__, inm);
3526 /* NOTREACHED */
3527 } else if (inm->inm_debug & IFD_TRASHED) {
3528 panic("%s: inm %p is already in trash list", __func__, inm);
3529 /* NOTREACHED */
3530 }
3531
3532 /*
3533 * NOTE: Caller calls IFMA_REMREF
3534 */
3535 inm->inm_debug &= ~IFD_ATTACHED;
3536 LIST_REMOVE(inm, inm_link);
3537
3538 if (inm->inm_debug & IFD_DEBUG) {
3539 /* Become a regular mutex, just in case */
3540 INM_CONVERT_LOCK(inm);
3541 lck_mtx_lock(&inm_trash_lock);
3542 TAILQ_INSERT_TAIL(&inm_trash_head,
3543 (struct in_multi_dbg *)inm, inm_trash_link);
3544 lck_mtx_unlock(&inm_trash_lock);
3545 inm->inm_debug |= IFD_TRASHED;
3546 }
3547
3548 return 1;
3549}
3550
3551void
3552inm_addref(struct in_multi *inm, int locked)
3553{
3554 if (!locked) {
3555 INM_LOCK_SPIN(inm);
3556 } else {
3557 INM_LOCK_ASSERT_HELD(inm);
3558 }
3559
3560 if (++inm->inm_refcount == 0) {
3561 panic("%s: inm=%p wraparound refcnt", __func__, inm);
3562 /* NOTREACHED */
3563 } else if (inm->inm_trace != NULL) {
3564 (*inm->inm_trace)(inm, TRUE);
3565 }
3566 if (!locked) {
3567 INM_UNLOCK(inm);
3568 }
3569}
3570
3571void
3572inm_remref(struct in_multi *inm, int locked)
3573{
3574 struct ifmultiaddr *ifma;
3575 struct igmp_ifinfo *igi;
3576
3577 if (!locked) {
3578 INM_LOCK_SPIN(inm);
3579 } else {
3580 INM_LOCK_ASSERT_HELD(inm);
3581 }
3582
3583 if (inm->inm_refcount == 0 || (inm->inm_refcount == 1 && locked)) {
3584 panic("%s: inm=%p negative/missing refcnt", __func__, inm);
3585 /* NOTREACHED */
3586 } else if (inm->inm_trace != NULL) {
3587 (*inm->inm_trace)(inm, FALSE);
3588 }
3589
3590 --inm->inm_refcount;
3591 if (inm->inm_refcount > 0) {
3592 if (!locked) {
3593 INM_UNLOCK(inm);
3594 }
3595 return;
3596 }
3597
3598 /*
3599 * Synchronization with in_getmulti(). In the event the inm has been
3600 * detached, the underlying ifma would still be in the if_multiaddrs
3601 * list, and thus can be looked up via if_addmulti(). At that point,
3602 * the only way to find this inm is via ifma_protospec. To avoid
3603 * race conditions between the last inm_remref() of that inm and its
3604 * use via ifma_protospec, in_multihead lock is used for serialization.
3605 * In order to avoid violating the lock order, we must drop inm_lock
3606 * before acquiring in_multihead lock. To prevent the inm from being
3607 * freed prematurely, we hold an extra reference.
3608 */
3609 ++inm->inm_refcount;
3610 INM_UNLOCK(inm);
3611 in_multihead_lock_shared();
3612 INM_LOCK_SPIN(inm);
3613 --inm->inm_refcount;
3614 if (inm->inm_refcount > 0) {
3615 /* We've lost the race, so abort since inm is still in use */
3616 INM_UNLOCK(inm);
3617 in_multihead_lock_done();
3618 /* If it was locked, return it as such */
3619 if (locked) {
3620 INM_LOCK(inm);
3621 }
3622 return;
3623 }
3624 inm_purge(inm);
3625 ifma = inm->inm_ifma;
3626 inm->inm_ifma = NULL;
3627 inm->inm_ifp = NULL;
3628 igi = inm->inm_igi;
3629 inm->inm_igi = NULL;
3630 INM_UNLOCK(inm);
3631 IFMA_LOCK_SPIN(ifma);
3632 ifma->ifma_protospec = NULL;
3633 IFMA_UNLOCK(ifma);
3634 in_multihead_lock_done();
3635
3636 in_multi_free(inm);
3637 if_delmulti_ifma(ifma);
3638 /* Release reference held to the underlying ifmultiaddr */
3639 IFMA_REMREF(ifma);
3640
3641 if (igi != NULL) {
3642 IGI_REMREF(igi);
3643 }
3644}
3645
3646static void
3647inm_trace(struct in_multi *inm, int refhold)
3648{
3649 struct in_multi_dbg *inm_dbg = (struct in_multi_dbg *)inm;
3650 ctrace_t *tr;
3651 u_int32_t idx;
3652 u_int16_t *cnt;
3653
3654 if (!(inm->inm_debug & IFD_DEBUG)) {
3655 panic("%s: inm %p has no debug structure", __func__, inm);
3656 /* NOTREACHED */
3657 }
3658 if (refhold) {
3659 cnt = &inm_dbg->inm_refhold_cnt;
3660 tr = inm_dbg->inm_refhold;
3661 } else {
3662 cnt = &inm_dbg->inm_refrele_cnt;
3663 tr = inm_dbg->inm_refrele;
3664 }
3665
3666 idx = atomic_add_16_ov(cnt, 1) % INM_TRACE_HIST_SIZE;
3667 ctrace_record(&tr[idx]);
3668}
3669
3670void
3671in_multihead_lock_exclusive(void)
3672{
3673 lck_rw_lock_exclusive(&in_multihead_lock);
3674}
3675
3676void
3677in_multihead_lock_shared(void)
3678{
3679 lck_rw_lock_shared(&in_multihead_lock);
3680}
3681
3682void
3683in_multihead_lock_assert(int what)
3684{
3685#if !MACH_ASSERT
3686#pragma unused(what)
3687#endif
3688 LCK_RW_ASSERT(&in_multihead_lock, what);
3689}
3690
3691void
3692in_multihead_lock_done(void)
3693{
3694 lck_rw_done(&in_multihead_lock);
3695}
3696
3697static struct ip_msource *
3698ipms_alloc(int how)
3699{
3700 struct ip_msource *ims;
3701
3702 ims = (how == M_WAITOK) ? zalloc(ipms_zone) : zalloc_noblock(ipms_zone);
3703 if (ims != NULL) {
3704 bzero(ims, ipms_size);
3705 }
3706
3707 return ims;
3708}
3709
3710static void
3711ipms_free(struct ip_msource *ims)
3712{
3713 zfree(ipms_zone, ims);
3714}
3715
3716static struct in_msource *
3717inms_alloc(int how)
3718{
3719 struct in_msource *inms;
3720
3721 inms = (how == M_WAITOK) ? zalloc(inms_zone) :
3722 zalloc_noblock(inms_zone);
3723 if (inms != NULL) {
3724 bzero(inms, inms_size);
3725 }
3726
3727 return inms;
3728}
3729
3730static void
3731inms_free(struct in_msource *inms)
3732{
3733 zfree(inms_zone, inms);
3734}
3735
3736#ifdef IGMP_DEBUG
3737
3738static const char *inm_modestrs[] = { "un\n", "in", "ex" };
3739
3740static const char *
3741inm_mode_str(const int mode)
3742{
3743 if (mode >= MCAST_UNDEFINED && mode <= MCAST_EXCLUDE) {
3744 return inm_modestrs[mode];
3745 }
3746 return "??";
3747}
3748
3749static const char *inm_statestrs[] = {
3750 "not-member\n",
3751 "silent\n",
3752 "reporting\n",
3753 "idle\n",
3754 "lazy\n",
3755 "sleeping\n",
3756 "awakening\n",
3757 "query-pending\n",
3758 "sg-query-pending\n",
3759 "leaving"
3760};
3761
3762static const char *
3763inm_state_str(const int state)
3764{
3765 if (state >= IGMP_NOT_MEMBER && state <= IGMP_LEAVING_MEMBER) {
3766 return inm_statestrs[state];
3767 }
3768 return "??";
3769}
3770
3771/*
3772 * Dump an in_multi structure to the console.
3773 */
3774void
3775inm_print(const struct in_multi *inm)
3776{
3777 int t;
3778 char buf[MAX_IPv4_STR_LEN];
3779
3780 INM_LOCK_ASSERT_HELD(__DECONST(struct in_multi *, inm));
3781
3782 if (igmp_debug == 0) {
3783 return;
3784 }
3785
3786 inet_ntop(AF_INET, &inm->inm_addr, buf, sizeof(buf));
3787 printf("%s: --- begin inm 0x%llx ---\n", __func__,
3788 (uint64_t)VM_KERNEL_ADDRPERM(inm));
3789 printf("addr %s ifp 0x%llx(%s) ifma 0x%llx\n",
3790 buf,
3791 (uint64_t)VM_KERNEL_ADDRPERM(inm->inm_ifp),
3792 if_name(inm->inm_ifp),
3793 (uint64_t)VM_KERNEL_ADDRPERM(inm->inm_ifma));
3794 printf("timer %u state %s refcount %u scq.len %u\n",
3795 inm->inm_timer,
3796 inm_state_str(inm->inm_state),
3797 inm->inm_refcount,
3798 inm->inm_scq.ifq_len);
3799 printf("igi 0x%llx nsrc %lu sctimer %u scrv %u\n",
3800 (uint64_t)VM_KERNEL_ADDRPERM(inm->inm_igi),
3801 inm->inm_nsrc,
3802 inm->inm_sctimer,
3803 inm->inm_scrv);
3804 for (t = 0; t < 2; t++) {
3805 printf("t%d: fmode %s asm %u ex %u in %u rec %u\n", t,
3806 inm_mode_str(inm->inm_st[t].iss_fmode),
3807 inm->inm_st[t].iss_asm,
3808 inm->inm_st[t].iss_ex,
3809 inm->inm_st[t].iss_in,
3810 inm->inm_st[t].iss_rec);
3811 }
3812 printf("%s: --- end inm 0x%llx ---\n", __func__,
3813 (uint64_t)VM_KERNEL_ADDRPERM(inm));
3814}
3815
3816#else
3817
3818void
3819inm_print(__unused const struct in_multi *inm)
3820{
3821}
3822
3823#endif