]> git.saurik.com Git - apple/xnu.git/blob - bsd/netinet/in_mcast.c
03532eaa3314b06a22e03219c594a9d2f198a6b1
[apple/xnu.git] / bsd / netinet / in_mcast.c
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 */
109 static void imf_commit(struct in_mfilter *);
110 static int imf_get_source(struct in_mfilter *imf,
111 const struct sockaddr_in *psin,
112 struct in_msource **);
113 static struct in_msource *
114 imf_graft(struct in_mfilter *, const uint8_t,
115 const struct sockaddr_in *);
116 static int imf_prune(struct in_mfilter *, const struct sockaddr_in *);
117 static void imf_rollback(struct in_mfilter *);
118 static void imf_reap(struct in_mfilter *);
119 static int imo_grow(struct ip_moptions *, size_t);
120 static size_t imo_match_group(const struct ip_moptions *,
121 const struct ifnet *, const struct sockaddr_in *);
122 static struct in_msource *
123 imo_match_source(const struct ip_moptions *, const size_t,
124 const struct sockaddr_in *);
125 static void ims_merge(struct ip_msource *ims,
126 const struct in_msource *lims, const int rollback);
127 static int in_getmulti(struct ifnet *, const struct in_addr *,
128 struct in_multi **);
129 static int in_joingroup(struct ifnet *, const struct in_addr *,
130 struct in_mfilter *, struct in_multi **);
131 static int inm_get_source(struct in_multi *inm, const in_addr_t haddr,
132 const int noalloc, struct ip_msource **pims);
133 static int inm_is_ifp_detached(const struct in_multi *);
134 static int inm_merge(struct in_multi *, /*const*/ struct in_mfilter *);
135 static void inm_reap(struct in_multi *);
136 static struct ip_moptions *
137 inp_findmoptions(struct inpcb *);
138 static int inp_get_source_filters(struct inpcb *, struct sockopt *);
139 static struct ifnet *
140 inp_lookup_mcast_ifp(const struct inpcb *,
141 const struct sockaddr_in *, const struct in_addr);
142 static int inp_block_unblock_source(struct inpcb *, struct sockopt *);
143 static int inp_set_multicast_if(struct inpcb *, struct sockopt *);
144 static int inp_set_source_filters(struct inpcb *, struct sockopt *);
145 static int sysctl_ip_mcast_filters SYSCTL_HANDLER_ARGS;
146 static struct ifnet * ip_multicast_if(struct in_addr *, unsigned int *);
147 static __inline__ int ip_msource_cmp(const struct ip_msource *,
148 const struct ip_msource *);
149
150 SYSCTL_NODE(_net_inet_ip, OID_AUTO, mcast, CTLFLAG_RW | CTLFLAG_LOCKED, 0, "IPv4 multicast");
151
152 static u_long in_mcast_maxgrpsrc = IP_MAX_GROUP_SRC_FILTER;
153 SYSCTL_LONG(_net_inet_ip_mcast, OID_AUTO, maxgrpsrc,
154 CTLFLAG_RW | CTLFLAG_LOCKED, &in_mcast_maxgrpsrc, "Max source filters per group");
155
156 static u_long in_mcast_maxsocksrc = IP_MAX_SOCK_SRC_FILTER;
157 SYSCTL_LONG(_net_inet_ip_mcast, OID_AUTO, maxsocksrc,
158 CTLFLAG_RW | CTLFLAG_LOCKED, &in_mcast_maxsocksrc,
159 "Max source filters per socket");
160
161 int in_mcast_loop = IP_DEFAULT_MULTICAST_LOOP;
162 SYSCTL_INT(_net_inet_ip_mcast, OID_AUTO, loop, CTLFLAG_RW | CTLFLAG_LOCKED,
163 &in_mcast_loop, 0, "Loopback multicast datagrams by default");
164
165 SYSCTL_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
169 RB_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
176 struct 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 */
192 static TAILQ_HEAD(, in_multi_dbg) inm_trash_head;
193 static 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
199 static unsigned int inm_debug = 1; /* debugging (enabled) */
200 #else
201 static unsigned int inm_debug; /* debugging (disabled) */
202 #endif /* !DEBUG */
203 static unsigned int inm_size; /* size of zone element */
204 static 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
209 static unsigned int ipms_size; /* size of zone element */
210 static 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
215 static unsigned int inms_size; /* size of zone element */
216 static struct zone *inms_zone; /* zone for in_msource */
217
218 /* Lock group and attribute for in_multihead_lock lock */
219 static lck_attr_t *in_multihead_lock_attr;
220 static lck_grp_t *in_multihead_lock_grp;
221 static lck_grp_attr_t *in_multihead_lock_grp_attr;
222
223 static decl_lck_rw_data(, in_multihead_lock);
224 struct in_multihead in_multihead;
225
226 static struct in_multi *in_multi_alloc(int);
227 static void in_multi_free(struct in_multi *);
228 static void in_multi_attach(struct in_multi *);
229 static void inm_trace(struct in_multi *, int);
230
231 static struct ip_msource *ipms_alloc(int);
232 static void ipms_free(struct ip_msource *);
233 static struct in_msource *inms_alloc(int);
234 static void inms_free(struct in_msource *);
235
236 static __inline int
237 ip_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 */
251 static __inline__ int
252 inm_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 */
264 static __inline__ void
265 imf_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 */
276 static int
277 imo_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 */
332 static size_t
333 imo_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 */
376 static struct in_msource *
377 imo_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 */
408 int
409 imo_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
444 int
445 imo_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
521 done:
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 */
537 static int
538 in_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 */
673 void
674 inm_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 */
707 int
708 inm_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 */
755 static int
756 imf_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 */
802 static struct in_msource *
803 imf_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 */
832 static int
833 imf_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 */
855 static void
856 imf_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 */
886 void
887 imf_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 */
904 static void
905 imf_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 */
922 static void
923 imf_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 */
946 void
947 imf_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 */
974 static int
975 inm_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 */
1020 uint8_t
1021 ims_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 */
1040 static void
1041 ims_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 */
1090 static int
1091 inm_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
1219 out_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 */
1231 void
1232 inm_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 */
1252 static void
1253 inm_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 */
1276 void
1277 inm_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 */
1301 static int
1302 in_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
1348 out_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 */
1374 int
1375 in_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 */
1443 struct in_multi *
1444 in_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 */
1462 void
1463 in_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 */
1477 static int
1478 inp_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
1668 out_imf_rollback:
1669 if (error) {
1670 imf_rollback(imf);
1671 } else {
1672 imf_commit(imf);
1673 }
1674
1675 imf_reap(imf);
1676
1677 out_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 */
1693 static struct ip_moptions *
1694 inp_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 */
1749 static int
1750 inp_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 */
1918 int
1919 inp_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 */
2053 static struct ifnet *
2054 inp_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 */
2114 int
2115 inp_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
2421 out_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
2433 out_imo_free:
2434 if (error && is_new) {
2435 VERIFY(inm == NULL);
2436 imo->imo_membership[idx] = NULL;
2437 --imo->imo_num_memberships;
2438 }
2439
2440 out_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 */
2456 int
2457 inp_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
2664 out_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
2698 out_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 */
2716 static int
2717 inp_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 /* XXX remove? */
2776 #ifdef IGMP_DEBUG0
2777 IGMP_PRINTF(("%s: ifp = 0x%llx, addr = %s\n", __func__,
2778 (uint64_t)VM_KERNEL_ADDRPERM(ifp), inet_ntoa(addr)));
2779 #endif
2780 }
2781
2782 /* Reject interfaces which do not support multicast. */
2783 if (ifp != NULL && (ifp->if_flags & IFF_MULTICAST) == 0) {
2784 return EOPNOTSUPP;
2785 }
2786
2787 imo = inp_findmoptions(inp);
2788 if (imo == NULL) {
2789 return ENOMEM;
2790 }
2791
2792 IMO_LOCK(imo);
2793 imo->imo_multicast_ifp = ifp;
2794 if (ifindex) {
2795 imo->imo_multicast_addr = addr;
2796 } else {
2797 imo->imo_multicast_addr.s_addr = INADDR_ANY;
2798 }
2799 IMO_UNLOCK(imo);
2800 IMO_REMREF(imo); /* from inp_findmoptions() */
2801
2802 return 0;
2803 }
2804
2805 /*
2806 * Atomically set source filters on a socket for an IPv4 multicast group.
2807 */
2808 static int
2809 inp_set_source_filters(struct inpcb *inp, struct sockopt *sopt)
2810 {
2811 struct __msfilterreq64 msfr = {}, msfr64;
2812 struct __msfilterreq32 msfr32;
2813 struct sockaddr_in *gsa;
2814 struct ifnet *ifp;
2815 struct in_mfilter *imf;
2816 struct ip_moptions *imo;
2817 struct in_multi *inm;
2818 size_t idx;
2819 int error;
2820 user_addr_t tmp_ptr;
2821 struct igmp_tparams itp;
2822
2823 bzero(&itp, sizeof(itp));
2824
2825 if (IS_64BIT_PROCESS(current_proc())) {
2826 error = sooptcopyin(sopt, &msfr64,
2827 sizeof(struct __msfilterreq64),
2828 sizeof(struct __msfilterreq64));
2829 if (error) {
2830 return error;
2831 }
2832 /* we never use msfr.msfr_srcs; */
2833 memcpy(&msfr, &msfr64, sizeof(msfr64));
2834 } else {
2835 error = sooptcopyin(sopt, &msfr32,
2836 sizeof(struct __msfilterreq32),
2837 sizeof(struct __msfilterreq32));
2838 if (error) {
2839 return error;
2840 }
2841 /* we never use msfr.msfr_srcs; */
2842 memcpy(&msfr, &msfr32, sizeof(msfr32));
2843 }
2844
2845 if ((size_t) msfr.msfr_nsrcs >
2846 UINT32_MAX / sizeof(struct sockaddr_storage)) {
2847 msfr.msfr_nsrcs = UINT32_MAX / sizeof(struct sockaddr_storage);
2848 }
2849
2850 if (msfr.msfr_nsrcs > in_mcast_maxsocksrc) {
2851 return ENOBUFS;
2852 }
2853
2854 if ((msfr.msfr_fmode != MCAST_EXCLUDE &&
2855 msfr.msfr_fmode != MCAST_INCLUDE)) {
2856 return EINVAL;
2857 }
2858
2859 if (msfr.msfr_group.ss_family != AF_INET ||
2860 msfr.msfr_group.ss_len != sizeof(struct sockaddr_in)) {
2861 return EINVAL;
2862 }
2863
2864 gsa = (struct sockaddr_in *)&msfr.msfr_group;
2865 if (!IN_MULTICAST(ntohl(gsa->sin_addr.s_addr))) {
2866 return EINVAL;
2867 }
2868
2869 gsa->sin_port = 0; /* ignore port */
2870
2871 ifnet_head_lock_shared();
2872 if (msfr.msfr_ifindex == 0 || (u_int)if_index < msfr.msfr_ifindex) {
2873 ifnet_head_done();
2874 return EADDRNOTAVAIL;
2875 }
2876
2877 ifp = ifindex2ifnet[msfr.msfr_ifindex];
2878 ifnet_head_done();
2879 if (ifp == NULL) {
2880 return EADDRNOTAVAIL;
2881 }
2882
2883 /*
2884 * Check if this socket is a member of this group.
2885 */
2886 imo = inp_findmoptions(inp);
2887 if (imo == NULL) {
2888 return ENOMEM;
2889 }
2890
2891 IMO_LOCK(imo);
2892 idx = imo_match_group(imo, ifp, gsa);
2893 if (idx == (size_t)-1 || imo->imo_mfilters == NULL) {
2894 error = EADDRNOTAVAIL;
2895 goto out_imo_locked;
2896 }
2897 inm = imo->imo_membership[idx];
2898 imf = &imo->imo_mfilters[idx];
2899
2900 /*
2901 * Begin state merge transaction at socket layer.
2902 */
2903
2904 imf->imf_st[1] = msfr.msfr_fmode;
2905
2906 /*
2907 * Apply any new source filters, if present.
2908 * Make a copy of the user-space source vector so
2909 * that we may copy them with a single copyin. This
2910 * allows us to deal with page faults up-front.
2911 */
2912 if (msfr.msfr_nsrcs > 0) {
2913 struct in_msource *lims;
2914 struct sockaddr_in *psin;
2915 struct sockaddr_storage *kss, *pkss;
2916 int i;
2917
2918 if (IS_64BIT_PROCESS(current_proc())) {
2919 tmp_ptr = msfr64.msfr_srcs;
2920 } else {
2921 tmp_ptr = CAST_USER_ADDR_T(msfr32.msfr_srcs);
2922 }
2923
2924 IGMP_PRINTF(("%s: loading %lu source list entries\n",
2925 __func__, (unsigned long)msfr.msfr_nsrcs));
2926 kss = _MALLOC((size_t) msfr.msfr_nsrcs * sizeof(*kss),
2927 M_TEMP, M_WAITOK);
2928 if (kss == NULL) {
2929 error = ENOMEM;
2930 goto out_imo_locked;
2931 }
2932 error = copyin(tmp_ptr, kss,
2933 (size_t) msfr.msfr_nsrcs * sizeof(*kss));
2934 if (error) {
2935 FREE(kss, M_TEMP);
2936 goto out_imo_locked;
2937 }
2938
2939 /*
2940 * Mark all source filters as UNDEFINED at t1.
2941 * Restore new group filter mode, as imf_leave()
2942 * will set it to INCLUDE.
2943 */
2944 imf_leave(imf);
2945 imf->imf_st[1] = msfr.msfr_fmode;
2946
2947 /*
2948 * Update socket layer filters at t1, lazy-allocating
2949 * new entries. This saves a bunch of memory at the
2950 * cost of one RB_FIND() per source entry; duplicate
2951 * entries in the msfr_nsrcs vector are ignored.
2952 * If we encounter an error, rollback transaction.
2953 *
2954 * XXX This too could be replaced with a set-symmetric
2955 * difference like loop to avoid walking from root
2956 * every time, as the key space is common.
2957 */
2958 for (i = 0, pkss = kss; (u_int)i < msfr.msfr_nsrcs;
2959 i++, pkss++) {
2960 psin = (struct sockaddr_in *)pkss;
2961 if (psin->sin_family != AF_INET) {
2962 error = EAFNOSUPPORT;
2963 break;
2964 }
2965 if (psin->sin_len != sizeof(struct sockaddr_in)) {
2966 error = EINVAL;
2967 break;
2968 }
2969 error = imf_get_source(imf, psin, &lims);
2970 if (error) {
2971 break;
2972 }
2973 lims->imsl_st[1] = imf->imf_st[1];
2974 }
2975 FREE(kss, M_TEMP);
2976 }
2977
2978 if (error) {
2979 goto out_imf_rollback;
2980 }
2981
2982 /*
2983 * Begin state merge transaction at IGMP layer.
2984 */
2985 INM_LOCK(inm);
2986 IGMP_PRINTF(("%s: merge inm state\n", __func__));
2987 error = inm_merge(inm, imf);
2988 if (error) {
2989 IGMP_PRINTF(("%s: failed to merge inm state\n", __func__));
2990 INM_UNLOCK(inm);
2991 goto out_imf_rollback;
2992 }
2993
2994 IGMP_PRINTF(("%s: doing igmp downcall\n", __func__));
2995 error = igmp_change_state(inm, &itp);
2996 INM_UNLOCK(inm);
2997 #ifdef IGMP_DEBUG
2998 if (error) {
2999 IGMP_PRINTF(("%s: failed igmp downcall\n", __func__));
3000 }
3001 #endif
3002
3003 out_imf_rollback:
3004 if (error) {
3005 imf_rollback(imf);
3006 } else {
3007 imf_commit(imf);
3008 }
3009
3010 imf_reap(imf);
3011
3012 out_imo_locked:
3013 IMO_UNLOCK(imo);
3014 IMO_REMREF(imo); /* from inp_findmoptions() */
3015
3016 /* schedule timer now that we've dropped the lock(s) */
3017 igmp_set_timeout(&itp);
3018
3019 return error;
3020 }
3021
3022 /*
3023 * Set the IP multicast options in response to user setsockopt().
3024 *
3025 * Many of the socket options handled in this function duplicate the
3026 * functionality of socket options in the regular unicast API. However,
3027 * it is not possible to merge the duplicate code, because the idempotence
3028 * of the IPv4 multicast part of the BSD Sockets API must be preserved;
3029 * the effects of these options must be treated as separate and distinct.
3030 */
3031 int
3032 inp_setmoptions(struct inpcb *inp, struct sockopt *sopt)
3033 {
3034 struct ip_moptions *imo;
3035 int error;
3036 unsigned int ifindex;
3037 struct ifnet *ifp;
3038
3039 error = 0;
3040
3041 /*
3042 * If socket is neither of type SOCK_RAW or SOCK_DGRAM,
3043 * or is a divert socket, reject it.
3044 */
3045 if (SOCK_PROTO(inp->inp_socket) == IPPROTO_DIVERT ||
3046 (SOCK_TYPE(inp->inp_socket) != SOCK_RAW &&
3047 SOCK_TYPE(inp->inp_socket) != SOCK_DGRAM)) {
3048 return EOPNOTSUPP;
3049 }
3050
3051 switch (sopt->sopt_name) {
3052 case IP_MULTICAST_IF:
3053 error = inp_set_multicast_if(inp, sopt);
3054 break;
3055
3056 case IP_MULTICAST_IFINDEX:
3057 /*
3058 * Select the interface for outgoing multicast packets.
3059 */
3060 error = sooptcopyin(sopt, &ifindex, sizeof(ifindex),
3061 sizeof(ifindex));
3062 if (error) {
3063 break;
3064 }
3065
3066 imo = inp_findmoptions(inp);
3067 if (imo == NULL) {
3068 error = ENOMEM;
3069 break;
3070 }
3071 /*
3072 * Index 0 is used to remove a previous selection.
3073 * When no interface is selected, a default one is
3074 * chosen every time a multicast packet is sent.
3075 */
3076 if (ifindex == 0) {
3077 IMO_LOCK(imo);
3078 imo->imo_multicast_ifp = NULL;
3079 IMO_UNLOCK(imo);
3080 IMO_REMREF(imo); /* from inp_findmoptions() */
3081 break;
3082 }
3083
3084 ifnet_head_lock_shared();
3085 /* Don't need to check is ifindex is < 0 since it's unsigned */
3086 if ((unsigned int)if_index < ifindex) {
3087 ifnet_head_done();
3088 IMO_REMREF(imo); /* from inp_findmoptions() */
3089 error = ENXIO; /* per IPV6_MULTICAST_IF */
3090 break;
3091 }
3092 ifp = ifindex2ifnet[ifindex];
3093 ifnet_head_done();
3094
3095 /* If it's detached or isn't a multicast interface, bail out */
3096 if (ifp == NULL || !(ifp->if_flags & IFF_MULTICAST)) {
3097 IMO_REMREF(imo); /* from inp_findmoptions() */
3098 error = EADDRNOTAVAIL;
3099 break;
3100 }
3101 IMO_LOCK(imo);
3102 imo->imo_multicast_ifp = ifp;
3103 /*
3104 * Clear out any remnants of past IP_MULTICAST_IF. The addr
3105 * isn't really used anywhere in the kernel; we could have
3106 * iterated thru the addresses of the interface and pick one
3107 * here, but that is redundant since ip_getmoptions() already
3108 * takes care of that for INADDR_ANY.
3109 */
3110 imo->imo_multicast_addr.s_addr = INADDR_ANY;
3111 IMO_UNLOCK(imo);
3112 IMO_REMREF(imo); /* from inp_findmoptions() */
3113 break;
3114
3115 case IP_MULTICAST_TTL: {
3116 u_char ttl;
3117
3118 /*
3119 * Set the IP time-to-live for outgoing multicast packets.
3120 * The original multicast API required a char argument,
3121 * which is inconsistent with the rest of the socket API.
3122 * We allow either a char or an int.
3123 */
3124 if (sopt->sopt_valsize == sizeof(u_char)) {
3125 error = sooptcopyin(sopt, &ttl, sizeof(u_char),
3126 sizeof(u_char));
3127 if (error) {
3128 break;
3129 }
3130 } else {
3131 u_int ittl;
3132
3133 error = sooptcopyin(sopt, &ittl, sizeof(u_int),
3134 sizeof(u_int));
3135 if (error) {
3136 break;
3137 }
3138 if (ittl > 255) {
3139 error = EINVAL;
3140 break;
3141 }
3142 ttl = (u_char)ittl;
3143 }
3144 imo = inp_findmoptions(inp);
3145 if (imo == NULL) {
3146 error = ENOMEM;
3147 break;
3148 }
3149 IMO_LOCK(imo);
3150 imo->imo_multicast_ttl = ttl;
3151 IMO_UNLOCK(imo);
3152 IMO_REMREF(imo); /* from inp_findmoptions() */
3153 break;
3154 }
3155
3156 case IP_MULTICAST_LOOP: {
3157 u_char loop;
3158
3159 /*
3160 * Set the loopback flag for outgoing multicast packets.
3161 * Must be zero or one. The original multicast API required a
3162 * char argument, which is inconsistent with the rest
3163 * of the socket API. We allow either a char or an int.
3164 */
3165 if (sopt->sopt_valsize == sizeof(u_char)) {
3166 error = sooptcopyin(sopt, &loop, sizeof(u_char),
3167 sizeof(u_char));
3168 if (error) {
3169 break;
3170 }
3171 } else {
3172 u_int iloop;
3173
3174 error = sooptcopyin(sopt, &iloop, sizeof(u_int),
3175 sizeof(u_int));
3176 if (error) {
3177 break;
3178 }
3179 loop = (u_char)iloop;
3180 }
3181 imo = inp_findmoptions(inp);
3182 if (imo == NULL) {
3183 error = ENOMEM;
3184 break;
3185 }
3186 IMO_LOCK(imo);
3187 imo->imo_multicast_loop = !!loop;
3188 IMO_UNLOCK(imo);
3189 IMO_REMREF(imo); /* from inp_findmoptions() */
3190 break;
3191 }
3192
3193 case IP_ADD_MEMBERSHIP:
3194 case IP_ADD_SOURCE_MEMBERSHIP:
3195 case MCAST_JOIN_GROUP:
3196 case MCAST_JOIN_SOURCE_GROUP:
3197 error = inp_join_group(inp, sopt);
3198 break;
3199
3200 case IP_DROP_MEMBERSHIP:
3201 case IP_DROP_SOURCE_MEMBERSHIP:
3202 case MCAST_LEAVE_GROUP:
3203 case MCAST_LEAVE_SOURCE_GROUP:
3204 error = inp_leave_group(inp, sopt);
3205 break;
3206
3207 case IP_BLOCK_SOURCE:
3208 case IP_UNBLOCK_SOURCE:
3209 case MCAST_BLOCK_SOURCE:
3210 case MCAST_UNBLOCK_SOURCE:
3211 error = inp_block_unblock_source(inp, sopt);
3212 break;
3213
3214 case IP_MSFILTER:
3215 error = inp_set_source_filters(inp, sopt);
3216 break;
3217
3218 default:
3219 error = EOPNOTSUPP;
3220 break;
3221 }
3222
3223 return error;
3224 }
3225
3226 /*
3227 * Expose IGMP's multicast filter mode and source list(s) to userland,
3228 * keyed by (ifindex, group).
3229 * The filter mode is written out as a uint32_t, followed by
3230 * 0..n of struct in_addr.
3231 * For use by ifmcstat(8).
3232 */
3233 static int
3234 sysctl_ip_mcast_filters SYSCTL_HANDLER_ARGS
3235 {
3236 #pragma unused(oidp)
3237
3238 struct in_addr src = {}, group;
3239 struct ifnet *ifp;
3240 struct in_multi *inm;
3241 struct in_multistep step;
3242 struct ip_msource *ims;
3243 int *name;
3244 int retval = 0;
3245 u_int namelen;
3246 uint32_t fmode, ifindex;
3247
3248 name = (int *)arg1;
3249 namelen = (u_int)arg2;
3250
3251 if (req->newptr != USER_ADDR_NULL) {
3252 return EPERM;
3253 }
3254
3255 if (namelen != 2) {
3256 return EINVAL;
3257 }
3258
3259 ifindex = name[0];
3260 ifnet_head_lock_shared();
3261 if (ifindex <= 0 || ifindex > (u_int)if_index) {
3262 IGMP_PRINTF(("%s: ifindex %u out of range\n",
3263 __func__, ifindex));
3264 ifnet_head_done();
3265 return ENOENT;
3266 }
3267
3268 group.s_addr = name[1];
3269 if (!IN_MULTICAST(ntohl(group.s_addr))) {
3270 IGMP_INET_PRINTF(group,
3271 ("%s: group %s is not multicast\n",
3272 __func__, _igmp_inet_buf));
3273 ifnet_head_done();
3274 return EINVAL;
3275 }
3276
3277 ifp = ifindex2ifnet[ifindex];
3278 ifnet_head_done();
3279 if (ifp == NULL) {
3280 IGMP_PRINTF(("%s: no ifp for ifindex %u\n", __func__, ifindex));
3281 return ENOENT;
3282 }
3283
3284 in_multihead_lock_shared();
3285 IN_FIRST_MULTI(step, inm);
3286 while (inm != NULL) {
3287 INM_LOCK(inm);
3288 if (inm->inm_ifp != ifp) {
3289 goto next;
3290 }
3291
3292 if (!in_hosteq(inm->inm_addr, group)) {
3293 goto next;
3294 }
3295
3296 fmode = inm->inm_st[1].iss_fmode;
3297 retval = SYSCTL_OUT(req, &fmode, sizeof(uint32_t));
3298 if (retval != 0) {
3299 INM_UNLOCK(inm);
3300 break; /* abort */
3301 }
3302 RB_FOREACH(ims, ip_msource_tree, &inm->inm_srcs) {
3303 #ifdef IGMP_DEBUG
3304 struct in_addr ina;
3305 ina.s_addr = htonl(ims->ims_haddr);
3306 IGMP_INET_PRINTF(ina,
3307 ("%s: visit node %s\n", __func__, _igmp_inet_buf));
3308 #endif
3309 /*
3310 * Only copy-out sources which are in-mode.
3311 */
3312 if (fmode != ims_get_mode(inm, ims, 1)) {
3313 IGMP_PRINTF(("%s: skip non-in-mode\n",
3314 __func__));
3315 continue; /* process next source */
3316 }
3317 src.s_addr = htonl(ims->ims_haddr);
3318 retval = SYSCTL_OUT(req, &src, sizeof(struct in_addr));
3319 if (retval != 0) {
3320 break; /* process next inm */
3321 }
3322 }
3323 next:
3324 INM_UNLOCK(inm);
3325 IN_NEXT_MULTI(step, inm);
3326 }
3327 in_multihead_lock_done();
3328
3329 return retval;
3330 }
3331
3332 /*
3333 * XXX
3334 * The whole multicast option thing needs to be re-thought.
3335 * Several of these options are equally applicable to non-multicast
3336 * transmission, and one (IP_MULTICAST_TTL) totally duplicates a
3337 * standard option (IP_TTL).
3338 */
3339 /*
3340 * following RFC1724 section 3.3, 0.0.0.0/8 is interpreted as interface index.
3341 */
3342 static struct ifnet *
3343 ip_multicast_if(struct in_addr *a, unsigned int *ifindexp)
3344 {
3345 unsigned int ifindex;
3346 struct ifnet *ifp;
3347
3348 if (ifindexp != NULL) {
3349 *ifindexp = 0;
3350 }
3351 if (ntohl(a->s_addr) >> 24 == 0) {
3352 ifindex = ntohl(a->s_addr) & 0xffffff;
3353 ifnet_head_lock_shared();
3354 /* Don't need to check is ifindex is < 0 since it's unsigned */
3355 if ((unsigned int)if_index < ifindex) {
3356 ifnet_head_done();
3357 return NULL;
3358 }
3359 ifp = ifindex2ifnet[ifindex];
3360 ifnet_head_done();
3361 if (ifp != NULL && ifindexp != NULL) {
3362 *ifindexp = ifindex;
3363 }
3364 } else {
3365 INADDR_TO_IFP(*a, ifp);
3366 }
3367 return ifp;
3368 }
3369
3370 void
3371 in_multi_init(void)
3372 {
3373 PE_parse_boot_argn("ifa_debug", &inm_debug, sizeof(inm_debug));
3374
3375 /* Setup lock group and attribute for in_multihead */
3376 in_multihead_lock_grp_attr = lck_grp_attr_alloc_init();
3377 in_multihead_lock_grp = lck_grp_alloc_init("in_multihead",
3378 in_multihead_lock_grp_attr);
3379 in_multihead_lock_attr = lck_attr_alloc_init();
3380 lck_rw_init(&in_multihead_lock, in_multihead_lock_grp,
3381 in_multihead_lock_attr);
3382
3383 lck_mtx_init(&inm_trash_lock, in_multihead_lock_grp,
3384 in_multihead_lock_attr);
3385 TAILQ_INIT(&inm_trash_head);
3386
3387 inm_size = (inm_debug == 0) ? sizeof(struct in_multi) :
3388 sizeof(struct in_multi_dbg);
3389 inm_zone = zinit(inm_size, INM_ZONE_MAX * inm_size,
3390 0, INM_ZONE_NAME);
3391 if (inm_zone == NULL) {
3392 panic("%s: failed allocating %s", __func__, INM_ZONE_NAME);
3393 /* NOTREACHED */
3394 }
3395 zone_change(inm_zone, Z_EXPAND, TRUE);
3396
3397 ipms_size = sizeof(struct ip_msource);
3398 ipms_zone = zinit(ipms_size, IPMS_ZONE_MAX * ipms_size,
3399 0, IPMS_ZONE_NAME);
3400 if (ipms_zone == NULL) {
3401 panic("%s: failed allocating %s", __func__, IPMS_ZONE_NAME);
3402 /* NOTREACHED */
3403 }
3404 zone_change(ipms_zone, Z_EXPAND, TRUE);
3405
3406 inms_size = sizeof(struct in_msource);
3407 inms_zone = zinit(inms_size, INMS_ZONE_MAX * inms_size,
3408 0, INMS_ZONE_NAME);
3409 if (inms_zone == NULL) {
3410 panic("%s: failed allocating %s", __func__, INMS_ZONE_NAME);
3411 /* NOTREACHED */
3412 }
3413 zone_change(inms_zone, Z_EXPAND, TRUE);
3414 }
3415
3416 static struct in_multi *
3417 in_multi_alloc(int how)
3418 {
3419 struct in_multi *inm;
3420
3421 inm = (how == M_WAITOK) ? zalloc(inm_zone) : zalloc_noblock(inm_zone);
3422 if (inm != NULL) {
3423 bzero(inm, inm_size);
3424 lck_mtx_init(&inm->inm_lock, in_multihead_lock_grp,
3425 in_multihead_lock_attr);
3426 inm->inm_debug |= IFD_ALLOC;
3427 if (inm_debug != 0) {
3428 inm->inm_debug |= IFD_DEBUG;
3429 inm->inm_trace = inm_trace;
3430 }
3431 }
3432 return inm;
3433 }
3434
3435 static void
3436 in_multi_free(struct in_multi *inm)
3437 {
3438 INM_LOCK(inm);
3439 if (inm->inm_debug & IFD_ATTACHED) {
3440 panic("%s: attached inm=%p is being freed", __func__, inm);
3441 /* NOTREACHED */
3442 } else if (inm->inm_ifma != NULL) {
3443 panic("%s: ifma not NULL for inm=%p", __func__, inm);
3444 /* NOTREACHED */
3445 } else if (!(inm->inm_debug & IFD_ALLOC)) {
3446 panic("%s: inm %p cannot be freed", __func__, inm);
3447 /* NOTREACHED */
3448 } else if (inm->inm_refcount != 0) {
3449 panic("%s: non-zero refcount inm=%p", __func__, inm);
3450 /* NOTREACHED */
3451 } else if (inm->inm_reqcnt != 0) {
3452 panic("%s: non-zero reqcnt inm=%p", __func__, inm);
3453 /* NOTREACHED */
3454 }
3455
3456 /* Free any pending IGMPv3 state-change records */
3457 IF_DRAIN(&inm->inm_scq);
3458
3459 inm->inm_debug &= ~IFD_ALLOC;
3460 if ((inm->inm_debug & (IFD_DEBUG | IFD_TRASHED)) ==
3461 (IFD_DEBUG | IFD_TRASHED)) {
3462 lck_mtx_lock(&inm_trash_lock);
3463 TAILQ_REMOVE(&inm_trash_head, (struct in_multi_dbg *)inm,
3464 inm_trash_link);
3465 lck_mtx_unlock(&inm_trash_lock);
3466 inm->inm_debug &= ~IFD_TRASHED;
3467 }
3468 INM_UNLOCK(inm);
3469
3470 lck_mtx_destroy(&inm->inm_lock, in_multihead_lock_grp);
3471 zfree(inm_zone, inm);
3472 }
3473
3474 static void
3475 in_multi_attach(struct in_multi *inm)
3476 {
3477 in_multihead_lock_assert(LCK_RW_ASSERT_EXCLUSIVE);
3478 INM_LOCK_ASSERT_HELD(inm);
3479
3480 if (inm->inm_debug & IFD_ATTACHED) {
3481 panic("%s: Attempt to attach an already attached inm=%p",
3482 __func__, inm);
3483 /* NOTREACHED */
3484 } else if (inm->inm_debug & IFD_TRASHED) {
3485 panic("%s: Attempt to reattach a detached inm=%p",
3486 __func__, inm);
3487 /* NOTREACHED */
3488 }
3489
3490 inm->inm_reqcnt++;
3491 VERIFY(inm->inm_reqcnt == 1);
3492 INM_ADDREF_LOCKED(inm);
3493 inm->inm_debug |= IFD_ATTACHED;
3494 /*
3495 * Reattach case: If debugging is enabled, take it
3496 * out of the trash list and clear IFD_TRASHED.
3497 */
3498 if ((inm->inm_debug & (IFD_DEBUG | IFD_TRASHED)) ==
3499 (IFD_DEBUG | IFD_TRASHED)) {
3500 /* Become a regular mutex, just in case */
3501 INM_CONVERT_LOCK(inm);
3502 lck_mtx_lock(&inm_trash_lock);
3503 TAILQ_REMOVE(&inm_trash_head, (struct in_multi_dbg *)inm,
3504 inm_trash_link);
3505 lck_mtx_unlock(&inm_trash_lock);
3506 inm->inm_debug &= ~IFD_TRASHED;
3507 }
3508
3509 LIST_INSERT_HEAD(&in_multihead, inm, inm_link);
3510 }
3511
3512 int
3513 in_multi_detach(struct in_multi *inm)
3514 {
3515 in_multihead_lock_assert(LCK_RW_ASSERT_EXCLUSIVE);
3516 INM_LOCK_ASSERT_HELD(inm);
3517
3518 if (inm->inm_reqcnt == 0) {
3519 panic("%s: inm=%p negative reqcnt", __func__, inm);
3520 /* NOTREACHED */
3521 }
3522
3523 --inm->inm_reqcnt;
3524 if (inm->inm_reqcnt > 0) {
3525 return 0;
3526 }
3527
3528 if (!(inm->inm_debug & IFD_ATTACHED)) {
3529 panic("%s: Attempt to detach an unattached record inm=%p",
3530 __func__, inm);
3531 /* NOTREACHED */
3532 } else if (inm->inm_debug & IFD_TRASHED) {
3533 panic("%s: inm %p is already in trash list", __func__, inm);
3534 /* NOTREACHED */
3535 }
3536
3537 /*
3538 * NOTE: Caller calls IFMA_REMREF
3539 */
3540 inm->inm_debug &= ~IFD_ATTACHED;
3541 LIST_REMOVE(inm, inm_link);
3542
3543 if (inm->inm_debug & IFD_DEBUG) {
3544 /* Become a regular mutex, just in case */
3545 INM_CONVERT_LOCK(inm);
3546 lck_mtx_lock(&inm_trash_lock);
3547 TAILQ_INSERT_TAIL(&inm_trash_head,
3548 (struct in_multi_dbg *)inm, inm_trash_link);
3549 lck_mtx_unlock(&inm_trash_lock);
3550 inm->inm_debug |= IFD_TRASHED;
3551 }
3552
3553 return 1;
3554 }
3555
3556 void
3557 inm_addref(struct in_multi *inm, int locked)
3558 {
3559 if (!locked) {
3560 INM_LOCK_SPIN(inm);
3561 } else {
3562 INM_LOCK_ASSERT_HELD(inm);
3563 }
3564
3565 if (++inm->inm_refcount == 0) {
3566 panic("%s: inm=%p wraparound refcnt", __func__, inm);
3567 /* NOTREACHED */
3568 } else if (inm->inm_trace != NULL) {
3569 (*inm->inm_trace)(inm, TRUE);
3570 }
3571 if (!locked) {
3572 INM_UNLOCK(inm);
3573 }
3574 }
3575
3576 void
3577 inm_remref(struct in_multi *inm, int locked)
3578 {
3579 struct ifmultiaddr *ifma;
3580 struct igmp_ifinfo *igi;
3581
3582 if (!locked) {
3583 INM_LOCK_SPIN(inm);
3584 } else {
3585 INM_LOCK_ASSERT_HELD(inm);
3586 }
3587
3588 if (inm->inm_refcount == 0 || (inm->inm_refcount == 1 && locked)) {
3589 panic("%s: inm=%p negative/missing refcnt", __func__, inm);
3590 /* NOTREACHED */
3591 } else if (inm->inm_trace != NULL) {
3592 (*inm->inm_trace)(inm, FALSE);
3593 }
3594
3595 --inm->inm_refcount;
3596 if (inm->inm_refcount > 0) {
3597 if (!locked) {
3598 INM_UNLOCK(inm);
3599 }
3600 return;
3601 }
3602
3603 /*
3604 * Synchronization with in_getmulti(). In the event the inm has been
3605 * detached, the underlying ifma would still be in the if_multiaddrs
3606 * list, and thus can be looked up via if_addmulti(). At that point,
3607 * the only way to find this inm is via ifma_protospec. To avoid
3608 * race conditions between the last inm_remref() of that inm and its
3609 * use via ifma_protospec, in_multihead lock is used for serialization.
3610 * In order to avoid violating the lock order, we must drop inm_lock
3611 * before acquiring in_multihead lock. To prevent the inm from being
3612 * freed prematurely, we hold an extra reference.
3613 */
3614 ++inm->inm_refcount;
3615 INM_UNLOCK(inm);
3616 in_multihead_lock_shared();
3617 INM_LOCK_SPIN(inm);
3618 --inm->inm_refcount;
3619 if (inm->inm_refcount > 0) {
3620 /* We've lost the race, so abort since inm is still in use */
3621 INM_UNLOCK(inm);
3622 in_multihead_lock_done();
3623 /* If it was locked, return it as such */
3624 if (locked) {
3625 INM_LOCK(inm);
3626 }
3627 return;
3628 }
3629 inm_purge(inm);
3630 ifma = inm->inm_ifma;
3631 inm->inm_ifma = NULL;
3632 inm->inm_ifp = NULL;
3633 igi = inm->inm_igi;
3634 inm->inm_igi = NULL;
3635 INM_UNLOCK(inm);
3636 IFMA_LOCK_SPIN(ifma);
3637 ifma->ifma_protospec = NULL;
3638 IFMA_UNLOCK(ifma);
3639 in_multihead_lock_done();
3640
3641 in_multi_free(inm);
3642 if_delmulti_ifma(ifma);
3643 /* Release reference held to the underlying ifmultiaddr */
3644 IFMA_REMREF(ifma);
3645
3646 if (igi != NULL) {
3647 IGI_REMREF(igi);
3648 }
3649 }
3650
3651 static void
3652 inm_trace(struct in_multi *inm, int refhold)
3653 {
3654 struct in_multi_dbg *inm_dbg = (struct in_multi_dbg *)inm;
3655 ctrace_t *tr;
3656 u_int32_t idx;
3657 u_int16_t *cnt;
3658
3659 if (!(inm->inm_debug & IFD_DEBUG)) {
3660 panic("%s: inm %p has no debug structure", __func__, inm);
3661 /* NOTREACHED */
3662 }
3663 if (refhold) {
3664 cnt = &inm_dbg->inm_refhold_cnt;
3665 tr = inm_dbg->inm_refhold;
3666 } else {
3667 cnt = &inm_dbg->inm_refrele_cnt;
3668 tr = inm_dbg->inm_refrele;
3669 }
3670
3671 idx = atomic_add_16_ov(cnt, 1) % INM_TRACE_HIST_SIZE;
3672 ctrace_record(&tr[idx]);
3673 }
3674
3675 void
3676 in_multihead_lock_exclusive(void)
3677 {
3678 lck_rw_lock_exclusive(&in_multihead_lock);
3679 }
3680
3681 void
3682 in_multihead_lock_shared(void)
3683 {
3684 lck_rw_lock_shared(&in_multihead_lock);
3685 }
3686
3687 void
3688 in_multihead_lock_assert(int what)
3689 {
3690 #if !MACH_ASSERT
3691 #pragma unused(what)
3692 #endif
3693 LCK_RW_ASSERT(&in_multihead_lock, what);
3694 }
3695
3696 void
3697 in_multihead_lock_done(void)
3698 {
3699 lck_rw_done(&in_multihead_lock);
3700 }
3701
3702 static struct ip_msource *
3703 ipms_alloc(int how)
3704 {
3705 struct ip_msource *ims;
3706
3707 ims = (how == M_WAITOK) ? zalloc(ipms_zone) : zalloc_noblock(ipms_zone);
3708 if (ims != NULL) {
3709 bzero(ims, ipms_size);
3710 }
3711
3712 return ims;
3713 }
3714
3715 static void
3716 ipms_free(struct ip_msource *ims)
3717 {
3718 zfree(ipms_zone, ims);
3719 }
3720
3721 static struct in_msource *
3722 inms_alloc(int how)
3723 {
3724 struct in_msource *inms;
3725
3726 inms = (how == M_WAITOK) ? zalloc(inms_zone) :
3727 zalloc_noblock(inms_zone);
3728 if (inms != NULL) {
3729 bzero(inms, inms_size);
3730 }
3731
3732 return inms;
3733 }
3734
3735 static void
3736 inms_free(struct in_msource *inms)
3737 {
3738 zfree(inms_zone, inms);
3739 }
3740
3741 #ifdef IGMP_DEBUG
3742
3743 static const char *inm_modestrs[] = { "un\n", "in", "ex" };
3744
3745 static const char *
3746 inm_mode_str(const int mode)
3747 {
3748 if (mode >= MCAST_UNDEFINED && mode <= MCAST_EXCLUDE) {
3749 return inm_modestrs[mode];
3750 }
3751 return "??";
3752 }
3753
3754 static const char *inm_statestrs[] = {
3755 "not-member\n",
3756 "silent\n",
3757 "reporting\n",
3758 "idle\n",
3759 "lazy\n",
3760 "sleeping\n",
3761 "awakening\n",
3762 "query-pending\n",
3763 "sg-query-pending\n",
3764 "leaving"
3765 };
3766
3767 static const char *
3768 inm_state_str(const int state)
3769 {
3770 if (state >= IGMP_NOT_MEMBER && state <= IGMP_LEAVING_MEMBER) {
3771 return inm_statestrs[state];
3772 }
3773 return "??";
3774 }
3775
3776 /*
3777 * Dump an in_multi structure to the console.
3778 */
3779 void
3780 inm_print(const struct in_multi *inm)
3781 {
3782 int t;
3783 char buf[MAX_IPv4_STR_LEN];
3784
3785 INM_LOCK_ASSERT_HELD(__DECONST(struct in_multi *, inm));
3786
3787 if (igmp_debug == 0) {
3788 return;
3789 }
3790
3791 inet_ntop(AF_INET, &inm->inm_addr, buf, sizeof(buf));
3792 printf("%s: --- begin inm 0x%llx ---\n", __func__,
3793 (uint64_t)VM_KERNEL_ADDRPERM(inm));
3794 printf("addr %s ifp 0x%llx(%s) ifma 0x%llx\n",
3795 buf,
3796 (uint64_t)VM_KERNEL_ADDRPERM(inm->inm_ifp),
3797 if_name(inm->inm_ifp),
3798 (uint64_t)VM_KERNEL_ADDRPERM(inm->inm_ifma));
3799 printf("timer %u state %s refcount %u scq.len %u\n",
3800 inm->inm_timer,
3801 inm_state_str(inm->inm_state),
3802 inm->inm_refcount,
3803 inm->inm_scq.ifq_len);
3804 printf("igi 0x%llx nsrc %lu sctimer %u scrv %u\n",
3805 (uint64_t)VM_KERNEL_ADDRPERM(inm->inm_igi),
3806 inm->inm_nsrc,
3807 inm->inm_sctimer,
3808 inm->inm_scrv);
3809 for (t = 0; t < 2; t++) {
3810 printf("t%d: fmode %s asm %u ex %u in %u rec %u\n", t,
3811 inm_mode_str(inm->inm_st[t].iss_fmode),
3812 inm->inm_st[t].iss_asm,
3813 inm->inm_st[t].iss_ex,
3814 inm->inm_st[t].iss_in,
3815 inm->inm_st[t].iss_rec);
3816 }
3817 printf("%s: --- end inm 0x%llx ---\n", __func__,
3818 (uint64_t)VM_KERNEL_ADDRPERM(inm));
3819 }
3820
3821 #else
3822
3823 void
3824 inm_print(__unused const struct in_multi *inm)
3825 {
3826 }
3827
3828 #endif