xref: /xnu-11417.140.69/bsd/netinet/in_pcblist.c (revision 43a90889846e00bfb5cf1d255cdc0a701a1e05a4)
1 /*
2  * Copyright (c) 2010-2021 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) 1982, 1986, 1990, 1993
30  *	The Regents of the University of California.  All rights reserved.
31  *
32  * Redistribution and use in source and binary forms, with or without
33  * modification, are permitted provided that the following conditions
34  * are met:
35  * 1. Redistributions of source code must retain the above copyright
36  *    notice, this list of conditions and the following disclaimer.
37  * 2. Redistributions in binary form must reproduce the above copyright
38  *    notice, this list of conditions and the following disclaimer in the
39  *    documentation and/or other materials provided with the distribution.
40  * 3. All advertising materials mentioning features or use of this software
41  *    must display the following acknowledgement:
42  *	This product includes software developed by the University of
43  *	California, Berkeley and its contributors.
44  * 4. Neither the name of the University nor the names of its contributors
45  *    may be used to endorse or promote products derived from this software
46  *    without specific prior written permission.
47  *
48  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58  * SUCH DAMAGE.
59  */
60 
61 #include <sys/types.h>
62 #include <sys/malloc.h>
63 #include <sys/socket.h>
64 #include <sys/socketvar.h>
65 #include <sys/protosw.h>
66 #include <sys/domain.h>
67 #include <sys/filedesc.h>
68 #include <sys/file_internal.h>
69 #include <sys/kernel.h>
70 #include <sys/sysctl.h>
71 #include <sys/dtrace.h>
72 #include <sys/kauth.h>
73 
74 #include <net/route.h>
75 #include <net/if_var.h>
76 #include <net/if_ports_used.h>
77 #include <net/ntstat.h>
78 
79 #include <netinet/in.h>
80 #include <netinet/in_pcb.h>
81 #include <netinet/in_var.h>
82 #include <netinet/ip_var.h>
83 
84 #include <netinet/udp.h>
85 #include <netinet/udp_var.h>
86 
87 #include <netinet/tcp.h>
88 #include <netinet/tcp_fsm.h>
89 #include <netinet/tcp_seq.h>
90 #include <netinet/tcp_timer.h>
91 #include <netinet/tcp_var.h>
92 #include <netinet6/in6_var.h>
93 
94 #include <net/sockaddr_utils.h>
95 
96 #include <os/log.h>
97 
98 #ifndef ROUNDUP64
99 #define ROUNDUP64(x) P2ROUNDUP((x), sizeof (u_int64_t))
100 #endif
101 
102 #ifndef ADVANCE64
103 #define ADVANCE64(p, n) (void*)((char *)(p) + ROUNDUP64(n))
104 #endif
105 
106 static void inpcb_to_xinpcb_n(struct inpcb *, struct xinpcb_n *);
107 static void tcpcb_to_xtcpcb_n(struct tcpcb *, struct xtcpcb_n *);
108 void shutdown_sockets_on_interface(struct ifnet *ifp);
109 
110 
111 __private_extern__ void
sotoxsocket_n(struct socket * so,struct xsocket_n * xso)112 sotoxsocket_n(struct socket *so, struct xsocket_n *xso)
113 {
114 	xso->xso_len = sizeof(struct xsocket_n);
115 	xso->xso_kind = XSO_SOCKET;
116 
117 	if (so == NULL) {
118 		return;
119 	}
120 
121 	xso->xso_so = (uint64_t)VM_KERNEL_ADDRHASH(so);
122 	xso->so_type = so->so_type;
123 	xso->so_options = so->so_options;
124 	xso->so_linger = so->so_linger;
125 	xso->so_state = so->so_state;
126 	xso->so_pcb = (uint64_t)VM_KERNEL_ADDRHASH(so->so_pcb);
127 	if (so->so_proto) {
128 		xso->xso_protocol = SOCK_PROTO(so);
129 		xso->xso_family = SOCK_DOM(so);
130 	} else {
131 		xso->xso_protocol = xso->xso_family = 0;
132 	}
133 	xso->so_qlen = so->so_qlen;
134 	xso->so_incqlen = so->so_incqlen;
135 	xso->so_qlimit = so->so_qlimit;
136 	xso->so_timeo = so->so_timeo;
137 	xso->so_error = so->so_error;
138 	xso->so_pgid = so->so_pgid;
139 	xso->so_oobmark = so->so_oobmark;
140 	xso->so_uid = kauth_cred_getuid(so->so_cred);
141 	xso->so_last_pid = so->last_pid;
142 	xso->so_e_pid = so->e_pid;
143 	xso->so_gencnt = so->so_gencnt;
144 	xso->so_flags = so->so_flags;
145 	xso->so_flags1 = so->so_flags1;
146 	xso->so_usecount = so->so_usecount;
147 	xso->so_retaincnt = so->so_retaincnt;
148 	if (so->so_filt != NULL) {
149 		xso->xso_filter_flags |= XSOFF_SO_FILT;
150 	}
151 	if (so->so_flow_db != NULL) {
152 		xso->xso_filter_flags |= XSOFF_FLOW_DB;
153 	}
154 	if (so->so_cfil != NULL) {
155 		xso->xso_filter_flags |= XSOFF_CFIL;
156 	}
157 	if (so->so_fd_pcb != NULL) {
158 		xso->xso_filter_flags |= XSOFF_FLOW_DIV;
159 	}
160 }
161 
162 __private_extern__ void
sbtoxsockbuf_n(struct sockbuf * sb,struct xsockbuf_n * xsb)163 sbtoxsockbuf_n(struct sockbuf *sb, struct xsockbuf_n *xsb)
164 {
165 	xsb->xsb_len = sizeof(struct xsockbuf_n);
166 
167 	if (sb == NULL) {
168 		return;
169 	}
170 
171 	xsb->xsb_kind = (sb->sb_flags & SB_RECV) ? XSO_RCVBUF : XSO_SNDBUF;
172 	xsb->sb_cc = sb->sb_cc;
173 	xsb->sb_hiwat = sb->sb_hiwat;
174 	xsb->sb_mbcnt = sb->sb_mbcnt;
175 	xsb->sb_mbmax = sb->sb_mbmax;
176 	xsb->sb_lowat = sb->sb_lowat;
177 	xsb->sb_flags = (short)sb->sb_flags;
178 	xsb->sb_timeo = (short)((sb->sb_timeo.tv_sec * hz) +
179 	    sb->sb_timeo.tv_usec / tick);
180 	if (xsb->sb_timeo == 0 && sb->sb_timeo.tv_usec != 0) {
181 		xsb->sb_timeo = 1;
182 	}
183 }
184 
185 __private_extern__ void
sbtoxsockstat_n(struct socket * so,struct xsockstat_n * xst)186 sbtoxsockstat_n(struct socket *so, struct xsockstat_n *xst)
187 {
188 	int i;
189 
190 	xst->xst_len = sizeof(struct xsockstat_n);
191 	xst->xst_kind = XSO_STATS;
192 
193 	if (so == NULL) {
194 		return;
195 	}
196 
197 	for (i = 0; i < SO_TC_STATS_MAX; i++) {
198 		xst->xst_tc_stats[i].rxpackets = so->so_tc_stats[i].rxpackets;
199 		xst->xst_tc_stats[i].rxbytes = so->so_tc_stats[i].rxbytes;
200 		xst->xst_tc_stats[i].txpackets = so->so_tc_stats[i].txpackets;
201 		xst->xst_tc_stats[i].txbytes = so->so_tc_stats[i].txbytes;
202 	}
203 }
204 
205 static void
inpcb_to_xinpcb_n(struct inpcb * inp,struct xinpcb_n * xinp)206 inpcb_to_xinpcb_n(struct inpcb *inp, struct xinpcb_n *xinp)
207 {
208 	xinp->xi_len = sizeof(struct xinpcb_n);
209 	xinp->xi_kind = XSO_INPCB;
210 	xinp->xi_inpp = (uint64_t)VM_KERNEL_ADDRHASH(inp);
211 	xinp->inp_fport = inp->inp_fport;
212 	xinp->inp_lport = inp->inp_lport;
213 	xinp->inp_ppcb = (uint64_t)VM_KERNEL_ADDRHASH(inp->inp_ppcb);
214 	xinp->inp_gencnt = inp->inp_gencnt;
215 	xinp->inp_flags = inp->inp_flags;
216 	xinp->inp_flow = inp->inp_flow;
217 	xinp->inp_vflag = inp->inp_vflag;
218 	xinp->inp_ip_ttl = inp->inp_ip_ttl;
219 	xinp->inp_ip_p = inp->inp_ip_p;
220 	xinp->inp_dependfaddr.inp6_foreign = inp->inp_dependfaddr.inp6_foreign;
221 	xinp->inp_dependladdr.inp6_local = inp->inp_dependladdr.inp6_local;
222 	xinp->inp_depend4.inp4_ip_tos = inp->inp_depend4.inp4_ip_tos;
223 	xinp->inp_depend6.inp6_hlim = 0;
224 	xinp->inp_depend6.inp6_cksum = inp->inp_depend6.inp6_cksum;
225 	xinp->inp_depend6.inp6_ifindex = 0;
226 	xinp->inp_depend6.inp6_hops = inp->inp_depend6.inp6_hops;
227 	xinp->inp_flowhash = inp->inp_flowhash;
228 	xinp->inp_flags2 = inp->inp_flags2;
229 }
230 
231 __private_extern__ void
tcpcb_to_xtcpcb_n(struct tcpcb * tp,struct xtcpcb_n * xt)232 tcpcb_to_xtcpcb_n(struct tcpcb *tp, struct xtcpcb_n *xt)
233 {
234 	xt->xt_len = sizeof(struct xtcpcb_n);
235 	xt->xt_kind = XSO_TCPCB;
236 
237 	xt->t_segq = (uint32_t)VM_KERNEL_ADDRHASH(tp->t_segq.lh_first);
238 	xt->t_dupacks = tp->t_dupacks;
239 	xt->t_timer[TCPT_REXMT_EXT] = tp->t_timer[TCPT_REXMT];
240 	xt->t_timer[TCPT_PERSIST_EXT] = tp->t_timer[TCPT_PERSIST];
241 	xt->t_timer[TCPT_KEEP_EXT] = tp->t_timer[TCPT_KEEP];
242 	xt->t_timer[TCPT_2MSL_EXT] = tp->t_timer[TCPT_2MSL];
243 	xt->t_state = tp->t_state;
244 	xt->t_flags = tp->t_flags;
245 	xt->t_force = (tp->t_flagsext & TF_FORCE) ? 1 : 0;
246 	xt->snd_una = tp->snd_una;
247 	xt->snd_max = tp->snd_max;
248 	xt->snd_nxt = tp->snd_nxt;
249 	xt->snd_up = tp->snd_up;
250 	xt->snd_wl1 = tp->snd_wl1;
251 	xt->snd_wl2 = tp->snd_wl2;
252 	xt->iss = tp->iss;
253 	xt->irs = tp->irs;
254 	xt->rcv_nxt = tp->rcv_nxt;
255 	xt->rcv_adv = tp->rcv_adv;
256 	xt->rcv_wnd = tp->rcv_wnd;
257 	xt->rcv_up = tp->rcv_up;
258 	xt->snd_wnd = tp->snd_wnd;
259 	xt->snd_cwnd = tp->snd_cwnd;
260 	xt->snd_ssthresh = tp->snd_ssthresh;
261 	xt->t_maxopd = tp->t_maxopd;
262 	xt->t_rcvtime = tp->t_rcvtime;
263 	xt->t_starttime = tp->t_starttime;
264 	xt->t_rtttime = tp->t_rtttime;
265 	xt->t_rtseq = tp->t_rtseq;
266 	xt->t_rxtcur = tp->t_rxtcur;
267 	xt->t_maxseg = tp->t_maxseg;
268 	xt->t_srtt = tp->t_srtt;
269 	xt->t_rttvar = tp->t_rttvar;
270 	xt->t_rxtshift = tp->t_rxtshift;
271 	xt->t_rttmin = tp->t_rttmin;
272 	xt->t_rttupdated = tp->t_rttupdated;
273 	xt->max_sndwnd = tp->max_sndwnd;
274 	xt->t_softerror = tp->t_softerror;
275 	xt->t_oobflags = tp->t_oobflags;
276 	xt->t_iobc = tp->t_iobc;
277 	xt->snd_scale = tp->snd_scale;
278 	xt->rcv_scale = tp->rcv_scale;
279 	xt->request_r_scale = tp->request_r_scale;
280 	xt->requested_s_scale = tp->requested_s_scale;
281 	xt->ts_recent = tp->ts_recent;
282 	xt->ts_recent_age = tp->ts_recent_age;
283 	xt->last_ack_sent = tp->last_ack_sent;
284 	xt->cc_send = 0;
285 	xt->cc_recv = 0;
286 	xt->snd_recover = tp->snd_recover;
287 	xt->snd_cwnd_prev = tp->snd_cwnd_prev;
288 	xt->snd_ssthresh_prev = tp->snd_ssthresh_prev;
289 }
290 
291 __private_extern__ int
get_pcblist_n(short proto,struct sysctl_req * req,struct inpcbinfo * pcbinfo)292 get_pcblist_n(short proto, struct sysctl_req *req, struct inpcbinfo *pcbinfo)
293 {
294 	int error = 0;
295 	int i, n;
296 	size_t sz;
297 	struct inpcb *inp, **inp_list = NULL;
298 	inp_gen_t gencnt;
299 	struct xinpgen xig;
300 	void *buf = NULL;
301 	size_t item_size = ROUNDUP64(sizeof(struct xinpcb_n)) +
302 	    ROUNDUP64(sizeof(struct xsocket_n)) +
303 	    2 * ROUNDUP64(sizeof(struct xsockbuf_n)) +
304 	    ROUNDUP64(sizeof(struct xsockstat_n));
305 #if SKYWALK
306 	int nuserland;
307 	size_t userlandsnapshot_size = 0;
308 	void *__sized_by(userlandsnapshot_size) userlandsnapshot = NULL;
309 #endif /* SKYWALK */
310 
311 	if (proto == IPPROTO_TCP) {
312 		item_size += ROUNDUP64(sizeof(struct xtcpcb_n));
313 	}
314 
315 	if (req->oldptr == USER_ADDR_NULL) {
316 		n = pcbinfo->ipi_count;
317 #if SKYWALK
318 		n += ntstat_userland_count(proto);
319 #endif /* SKYWALK */
320 		req->oldidx = 2 * (sizeof(xig)) + (n + n / 8 + 1) * item_size;
321 		return 0;
322 	}
323 
324 	if (req->newptr != USER_ADDR_NULL) {
325 		return EPERM;
326 	}
327 
328 #if SKYWALK
329 	/*
330 	 * Get a snapshot of the state of the user level flows so we know
331 	 * the exact number of results to give back to the user.
332 	 * This could take a while and use other locks, so do this prior
333 	 * to taking any locks of our own.
334 	 */
335 	error = nstat_userland_get_snapshot(proto, &userlandsnapshot,
336 	    &userlandsnapshot_size, &nuserland);
337 
338 	if (error) {
339 		return error;
340 	}
341 #endif /* SKYWALK */
342 
343 	/*
344 	 * The process of preparing the PCB list is too time-consuming and
345 	 * resource-intensive to repeat twice on every request.
346 	 */
347 	lck_rw_lock_exclusive(&pcbinfo->ipi_lock);
348 	/*
349 	 * OK, now we're committed to doing something.
350 	 */
351 	gencnt = pcbinfo->ipi_gencnt;
352 	n = sz = pcbinfo->ipi_count;
353 
354 	bzero(&xig, sizeof(xig));
355 	xig.xig_len = sizeof(xig);
356 	xig.xig_count = n;
357 #if SKYWALK
358 	xig.xig_count += nuserland;
359 #endif /* SKYWALK */
360 	xig.xig_gen = gencnt;
361 	xig.xig_sogen = so_gencnt;
362 	error = SYSCTL_OUT(req, &xig, sizeof(xig));
363 	if (error) {
364 		goto done;
365 	}
366 	/*
367 	 * We are done if there is no pcb
368 	 */
369 	if (xig.xig_count == 0) {
370 		goto done;
371 	}
372 
373 	buf = kalloc_data(item_size, Z_WAITOK);
374 	if (buf == NULL) {
375 		error = ENOMEM;
376 		goto done;
377 	}
378 
379 	inp_list = kalloc_type(struct inpcb *, sz, Z_WAITOK);
380 	if (inp_list == NULL) {
381 		error = ENOMEM;
382 		goto done;
383 	}
384 
385 	/*
386 	 * Special case TCP to include the connections in time wait
387 	 */
388 	if (proto == IPPROTO_TCP) {
389 		n = get_tcp_inp_list(inp_list, sz, gencnt);
390 	} else {
391 		for (inp = pcbinfo->ipi_listhead->lh_first, i = 0; inp && i < sz;
392 		    inp = inp->inp_list.le_next) {
393 			if (inp->inp_gencnt <= gencnt &&
394 			    inp->inp_state != INPCB_STATE_DEAD) {
395 				inp_list[i++] = inp;
396 			}
397 		}
398 		n = i;
399 	}
400 
401 
402 	error = 0;
403 	for (i = 0; i < n; i++) {
404 		inp = inp_list[i];
405 		if (inp->inp_gencnt <= gencnt &&
406 		    inp->inp_state != INPCB_STATE_DEAD) {
407 			struct xinpcb_n *xi = (struct xinpcb_n *)buf;
408 			struct xsocket_n *xso = (struct xsocket_n *)
409 			    ADVANCE64(xi, sizeof(*xi));
410 			struct xsockbuf_n *xsbrcv = (struct xsockbuf_n *)
411 			    ADVANCE64(xso, sizeof(*xso));
412 			struct xsockbuf_n *xsbsnd = (struct xsockbuf_n *)
413 			    ADVANCE64(xsbrcv, sizeof(*xsbrcv));
414 			struct xsockstat_n *xsostats = (struct xsockstat_n *)
415 			    ADVANCE64(xsbsnd, sizeof(*xsbsnd));
416 
417 			bzero(buf, item_size);
418 
419 			inpcb_to_xinpcb_n(inp, xi);
420 			sotoxsocket_n(inp->inp_socket, xso);
421 			sbtoxsockbuf_n(inp->inp_socket ?
422 			    &inp->inp_socket->so_rcv : NULL, xsbrcv);
423 			sbtoxsockbuf_n(inp->inp_socket ?
424 			    &inp->inp_socket->so_snd : NULL, xsbsnd);
425 			sbtoxsockstat_n(inp->inp_socket, xsostats);
426 			if (proto == IPPROTO_TCP) {
427 				struct  xtcpcb_n *xt = (struct xtcpcb_n *)
428 				    ADVANCE64(xsostats, sizeof(*xsostats));
429 
430 				/*
431 				 * inp->inp_ppcb, can only be NULL on
432 				 * an initialization race window.
433 				 * No need to lock.
434 				 */
435 				if (inp->inp_ppcb == NULL) {
436 					continue;
437 				}
438 
439 				tcpcb_to_xtcpcb_n((struct tcpcb *)
440 				    inp->inp_ppcb, xt);
441 			}
442 			error = SYSCTL_OUT(req, buf, item_size);
443 			if (error) {
444 				break;
445 			}
446 		}
447 	}
448 #if SKYWALK
449 	if (!error && nuserland > 0) {
450 		error = nstat_userland_list_snapshot(proto, req, userlandsnapshot, nuserland);
451 	}
452 #endif /* SKYWALK */
453 
454 	if (!error) {
455 		/*
456 		 * Give the user an updated idea of our state.
457 		 * If the generation differs from what we told
458 		 * her before, she knows that something happened
459 		 * while we were processing this request, and it
460 		 * might be necessary to retry.
461 		 */
462 		bzero(&xig, sizeof(xig));
463 		xig.xig_len = sizeof(xig);
464 		xig.xig_gen = pcbinfo->ipi_gencnt;
465 		xig.xig_sogen = so_gencnt;
466 		xig.xig_count = pcbinfo->ipi_count;
467 #if SKYWALK
468 		xig.xig_count +=  nuserland;
469 #endif /* SKYWALK */
470 		error = SYSCTL_OUT(req, &xig, sizeof(xig));
471 	}
472 done:
473 	lck_rw_done(&pcbinfo->ipi_lock);
474 
475 #if SKYWALK
476 	nstat_userland_release_snapshot(userlandsnapshot, nuserland);
477 #endif /* SKYWALK */
478 
479 	kfree_type(struct inpcb *, sz, inp_list);
480 	if (buf != NULL) {
481 		kfree_data(buf, item_size);
482 	}
483 	return error;
484 }
485 
486 static void
inpcb_get_if_ports_used(ifnet_t ifp,int protocol,uint32_t flags,bitstr_t * __counted_by (bitstr_size (IP_PORTRANGE_SIZE))bitfield,struct inpcbinfo * pcbinfo)487 inpcb_get_if_ports_used(ifnet_t ifp, int protocol, uint32_t flags,
488     bitstr_t *__counted_by(bitstr_size(IP_PORTRANGE_SIZE)) bitfield, struct inpcbinfo *pcbinfo)
489 {
490 	struct inpcb *inp;
491 	struct socket *so;
492 	inp_gen_t gencnt;
493 	bool iswildcard, wildcardok, nowakeok;
494 	bool recvanyifonly, extbgidleok;
495 	bool activeonly;
496 	bool anytcpstateok;
497 
498 	if (ifp == NULL) {
499 		return;
500 	}
501 
502 	wildcardok = ((flags & IFNET_GET_LOCAL_PORTS_WILDCARDOK) != 0);
503 	nowakeok = ((flags & IFNET_GET_LOCAL_PORTS_NOWAKEUPOK) != 0);
504 	recvanyifonly = ((flags & IFNET_GET_LOCAL_PORTS_RECVANYIFONLY) != 0);
505 	extbgidleok = ((flags & IFNET_GET_LOCAL_PORTS_EXTBGIDLEONLY) != 0);
506 	activeonly = ((flags & IFNET_GET_LOCAL_PORTS_ACTIVEONLY) != 0);
507 	anytcpstateok = ((flags & IFNET_GET_LOCAL_PORTS_ANYTCPSTATEOK) != 0);
508 
509 	lck_rw_lock_shared(&pcbinfo->ipi_lock);
510 	gencnt = pcbinfo->ipi_gencnt;
511 
512 	for (inp = LIST_FIRST(pcbinfo->ipi_listhead); inp;
513 	    inp = LIST_NEXT(inp, inp_list)) {
514 		if (inp->inp_gencnt > gencnt ||
515 		    inp->inp_state == INPCB_STATE_DEAD ||
516 		    inp->inp_wantcnt == WNT_STOPUSING) {
517 			continue;
518 		}
519 
520 		if ((so = inp->inp_socket) == NULL || inp->inp_lport == 0) {
521 			continue;
522 		}
523 
524 		/*
525 		 * ANYTCPSTATEOK means incoming packets cannot be filtered
526 		 * reception so cast a wide net of possibilities
527 		 */
528 		if (!anytcpstateok &&
529 		    ((so->so_state & SS_DEFUNCT) ||
530 		    (so->so_state & SS_ISDISCONNECTED))) {
531 			continue;
532 		}
533 
534 		/*
535 		 * If protocol is specified, filter out inpcbs that
536 		 * are not relevant to the protocol family of interest.
537 		 */
538 		if (protocol != PF_UNSPEC) {
539 			if (protocol == PF_INET) {
540 				/*
541 				 * If protocol of interest is IPv4, skip the inpcb
542 				 * if the family is not IPv4.
543 				 * OR
544 				 * If the family is IPv4, skip if the IPv4 flow is
545 				 * CLAT46 translated.
546 				 */
547 				if ((inp->inp_vflag & INP_IPV4) == 0 ||
548 				    (inp->inp_flags2 & INP2_CLAT46_FLOW) != 0) {
549 					continue;
550 				}
551 			} else if (protocol == PF_INET6) {
552 				/*
553 				 * If protocol of interest is IPv6, skip the inpcb
554 				 * if the family is not IPv6.
555 				 * AND
556 				 * The flow is not a CLAT46'd flow.
557 				 */
558 				if ((inp->inp_vflag & INP_IPV6) == 0 &&
559 				    (inp->inp_flags2 & INP2_CLAT46_FLOW) == 0) {
560 					continue;
561 				}
562 			} else {
563 				/* Protocol family not supported */
564 				continue;
565 			}
566 		}
567 
568 		if (SOCK_PROTO(inp->inp_socket) != IPPROTO_UDP &&
569 		    SOCK_PROTO(inp->inp_socket) != IPPROTO_TCP) {
570 			continue;
571 		}
572 
573 		iswildcard = (((inp->inp_vflag & INP_IPV4) &&
574 		    inp->inp_laddr.s_addr == INADDR_ANY) ||
575 		    ((inp->inp_vflag & INP_IPV6) &&
576 		    IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)));
577 
578 		if (!wildcardok && iswildcard) {
579 			continue;
580 		}
581 
582 		if (!(inp->inp_flags & INP_RECV_ANYIF) &&
583 		    recvanyifonly) {
584 			continue;
585 		}
586 
587 		if (!(so->so_flags1 & SOF1_EXTEND_BK_IDLE_WANTED) &&
588 		    extbgidleok) {
589 			continue;
590 		}
591 
592 		if (!iswildcard &&
593 		    !(inp->inp_last_outifp == NULL || ifp == inp->inp_last_outifp)) {
594 			continue;
595 		}
596 
597 		if (!iswildcard && (ifp->if_eflags & IFEF_AWDL) != 0) {
598 			if (inp->inp_route.ro_rt == NULL ||
599 			    (inp->inp_route.ro_rt->rt_flags & (RTF_UP | RTF_CONDEMNED)) != RTF_UP) {
600 #if DEBUG || DEVELOPMENT
601 				char lbuf[MAX_IPv6_STR_LEN + 6] = {};
602 				char fbuf[MAX_IPv6_STR_LEN + 6] = {};
603 				char pname[MAXCOMLEN + 1];
604 
605 				proc_name(so->last_pid, pname, sizeof(pname));
606 
607 				if (protocol == PF_INET) {
608 					inet_ntop(PF_INET, &inp->inp_laddr.s_addr,
609 					    lbuf, sizeof(lbuf));
610 					inet_ntop(PF_INET, &inp->inp_faddr.s_addr,
611 					    fbuf, sizeof(fbuf));
612 				} else {
613 					inet_ntop(PF_INET6, &inp->in6p_laddr.s6_addr,
614 					    lbuf, sizeof(lbuf));
615 					inet_ntop(PF_INET6, &inp->in6p_faddr.s6_addr,
616 					    fbuf, sizeof(fbuf));
617 				}
618 
619 				os_log(OS_LOG_DEFAULT,
620 				    "inpcb_get_if_ports_used: route is down %s %s:%u %s:%u ifp %s proc %s:%d",
621 				    SOCK_PROTO(inp->inp_socket) == IPPROTO_TCP ? "tcp" : "udp",
622 				    lbuf, ntohs(inp->inp_lport), fbuf, ntohs(inp->inp_fport),
623 				    ifp->if_xname, pname, so->last_pid);
624 #endif /* DEBUG || DEVELOPMENT */
625 				continue;
626 			}
627 		}
628 
629 		if (SOCK_PROTO(inp->inp_socket) == IPPROTO_UDP &&
630 		    so->so_state & SS_CANTRCVMORE) {
631 			continue;
632 		}
633 
634 		if (SOCK_PROTO(inp->inp_socket) == IPPROTO_TCP) {
635 			struct  tcpcb *tp = sototcpcb(inp->inp_socket);
636 
637 			/*
638 			 * Workaround race where inp_ppcb is NULL during
639 			 * socket initialization
640 			 */
641 			if (tp == NULL) {
642 				continue;
643 			}
644 
645 			switch (tp->t_state) {
646 			case TCPS_CLOSED:
647 				if (anytcpstateok && inp->inp_fport != 0) {
648 					/*
649 					 * A foreign port means we had a 4 tuple at
650 					 * least a connection attempt so packets
651 					 * may be received for the 4 tuple after the
652 					 * connection is gone
653 					 */
654 					break;
655 				}
656 				continue;
657 			/* NOT REACHED */
658 			case TCPS_LISTEN:
659 			case TCPS_SYN_SENT:
660 			case TCPS_SYN_RECEIVED:
661 			case TCPS_ESTABLISHED:
662 			case TCPS_FIN_WAIT_1:
663 				/*
664 				 * Note: FIN_WAIT_1 is an active state
665 				 * because we need our FIN to be
666 				 * acknowledged
667 				 */
668 				break;
669 			case TCPS_CLOSE_WAIT:
670 			case TCPS_CLOSING:
671 			case TCPS_LAST_ACK:
672 			case TCPS_FIN_WAIT_2:
673 				/*
674 				 * In the closing states, the connection
675 				 * is active when there is outgoing
676 				 * data having to be acknowledged
677 				 */
678 				if (!anytcpstateok &&
679 				    (activeonly && so->so_snd.sb_cc == 0)) {
680 					continue;
681 				}
682 				break;
683 			case TCPS_TIME_WAIT:
684 				if (anytcpstateok) {
685 					/*
686 					 * Packets may still be received for the 4 tuple
687 					 * after the connection is gone
688 					 */
689 					break;
690 				}
691 				continue;
692 				/* NOT REACHED */
693 			}
694 		}
695 
696 #if DEBUG || DEVELOPMENT
697 		if ((so->so_options & SO_NOWAKEFROMSLEEP) && !nowakeok) {
698 			char lbuf[MAX_IPv6_STR_LEN + 6] = {};
699 			char fbuf[MAX_IPv6_STR_LEN + 6] = {};
700 			char pname[MAXCOMLEN + 1];
701 
702 			proc_name(so->last_pid, pname, sizeof(pname));
703 
704 			if (protocol == PF_INET) {
705 				inet_ntop(PF_INET, &inp->inp_laddr.s_addr,
706 				    lbuf, sizeof(lbuf));
707 				inet_ntop(PF_INET, &inp->inp_faddr.s_addr,
708 				    fbuf, sizeof(fbuf));
709 			} else {
710 				inet_ntop(PF_INET6, &inp->in6p_laddr.s6_addr,
711 				    lbuf, sizeof(lbuf));
712 				inet_ntop(PF_INET6, &inp->in6p_faddr.s6_addr,
713 				    fbuf, sizeof(fbuf));
714 			}
715 
716 			os_log(OS_LOG_DEFAULT,
717 			    "inpcb_get_if_ports_used: no wake from sleep %s %s:%u %s:%u ifp %s proc %s:%d",
718 			    SOCK_PROTO(inp->inp_socket) == IPPROTO_TCP ? "tcp" : "udp",
719 			    lbuf, ntohs(inp->inp_lport), fbuf, ntohs(inp->inp_fport),
720 			    ifp->if_xname, pname, so->last_pid);
721 		}
722 #endif /* DEBUG || DEVELOPMENT */
723 
724 
725 		/*
726 		 * When the socket has "no wake from sleep" option, do not set the port in the bitmap
727 		 * except if explicetely requested by the driver.
728 		 * We always add the socket to the list of port in order to report spurious wakes
729 		 */
730 		if ((so->so_options & SO_NOWAKEFROMSLEEP) == 0 || nowakeok) {
731 			bitstr_set(bitfield, ntohs(inp->inp_lport));
732 		}
733 
734 		(void) if_ports_used_add_inpcb(ifp->if_index, inp);
735 	}
736 	lck_rw_done(&pcbinfo->ipi_lock);
737 }
738 
739 __private_extern__ void
inpcb_get_ports_used(ifnet_t ifp,int protocol,uint32_t flags,bitstr_t * __counted_by (bitstr_size (IP_PORTRANGE_SIZE))bitfield,struct inpcbinfo * pcbinfo)740 inpcb_get_ports_used(ifnet_t ifp, int protocol, uint32_t flags,
741     bitstr_t *__counted_by(bitstr_size(IP_PORTRANGE_SIZE)) bitfield, struct inpcbinfo *pcbinfo)
742 {
743 	if (ifp != NULL) {
744 		inpcb_get_if_ports_used(ifp, protocol, flags, bitfield, pcbinfo);
745 	} else {
746 		errno_t error;
747 		uint32_t count = 0;
748 		ifnet_t *__counted_by(count) ifp_list = NULL;
749 		uint32_t i;
750 
751 		error = ifnet_list_get_all(IFNET_FAMILY_ANY, &ifp_list, &count);
752 		if (error != 0) {
753 			os_log_error(OS_LOG_DEFAULT,
754 			    "%s: ifnet_list_get_all() failed %d",
755 			    __func__, error);
756 			return;
757 		}
758 		for (i = 0; i < count; i++) {
759 			if (TAILQ_EMPTY(&ifp_list[i]->if_addrhead)) {
760 				continue;
761 			}
762 			inpcb_get_if_ports_used(ifp_list[i], protocol, flags,
763 			    bitfield, pcbinfo);
764 		}
765 		ifnet_list_free_counted_by(ifp_list, count);
766 	}
767 }
768 
769 __private_extern__ uint32_t
inpcb_count_opportunistic(unsigned int ifindex,struct inpcbinfo * pcbinfo,u_int32_t flags)770 inpcb_count_opportunistic(unsigned int ifindex, struct inpcbinfo *pcbinfo,
771     u_int32_t flags)
772 {
773 	uint32_t opportunistic = 0;
774 	struct inpcb *inp;
775 	inp_gen_t gencnt;
776 
777 	lck_rw_lock_shared(&pcbinfo->ipi_lock);
778 	gencnt = pcbinfo->ipi_gencnt;
779 	for (inp = LIST_FIRST(pcbinfo->ipi_listhead);
780 	    inp != NULL; inp = LIST_NEXT(inp, inp_list)) {
781 		if (inp->inp_gencnt <= gencnt &&
782 		    inp->inp_state != INPCB_STATE_DEAD &&
783 		    inp->inp_socket != NULL &&
784 		    so_get_opportunistic(inp->inp_socket) &&
785 		    inp->inp_last_outifp != NULL &&
786 		    ifindex == inp->inp_last_outifp->if_index) {
787 			opportunistic++;
788 			struct socket *so = inp->inp_socket;
789 			if ((flags & INPCB_OPPORTUNISTIC_SETCMD) &&
790 			    (so->so_state & SS_ISCONNECTED)) {
791 				socket_lock(so, 1);
792 				if (flags & INPCB_OPPORTUNISTIC_THROTTLEON) {
793 					so->so_flags |= SOF_SUSPENDED;
794 					soevent(so,
795 					    (SO_FILT_HINT_LOCKED |
796 					    SO_FILT_HINT_SUSPEND));
797 				} else {
798 					so->so_flags &= ~(SOF_SUSPENDED);
799 					soevent(so,
800 					    (SO_FILT_HINT_LOCKED |
801 					    SO_FILT_HINT_RESUME));
802 				}
803 				SOTHROTTLELOG("throttle[%d]: so 0x%llx "
804 				    "[%d,%d] %s\n", so->last_pid,
805 				    (uint64_t)VM_KERNEL_ADDRHASH(so),
806 				    SOCK_DOM(so), SOCK_TYPE(so),
807 				    (so->so_flags & SOF_SUSPENDED) ?
808 				    "SUSPENDED" : "RESUMED");
809 				socket_unlock(so, 1);
810 			}
811 		}
812 	}
813 
814 	lck_rw_done(&pcbinfo->ipi_lock);
815 
816 	return opportunistic;
817 }
818 
819 __private_extern__ uint32_t
inpcb_find_anypcb_byaddr(struct ifaddr * ifa,struct inpcbinfo * pcbinfo)820 inpcb_find_anypcb_byaddr(struct ifaddr *ifa, struct inpcbinfo *pcbinfo)
821 {
822 	struct inpcb *inp;
823 	inp_gen_t gencnt = pcbinfo->ipi_gencnt;
824 	struct socket *so = NULL;
825 	int af;
826 
827 	if ((ifa->ifa_addr->sa_family != AF_INET) &&
828 	    (ifa->ifa_addr->sa_family != AF_INET6)) {
829 		return 0;
830 	}
831 
832 	lck_rw_lock_shared(&pcbinfo->ipi_lock);
833 	for (inp = LIST_FIRST(pcbinfo->ipi_listhead);
834 	    inp != NULL; inp = LIST_NEXT(inp, inp_list)) {
835 		if (inp->inp_gencnt <= gencnt &&
836 		    inp->inp_state != INPCB_STATE_DEAD &&
837 		    inp->inp_socket != NULL) {
838 			so = inp->inp_socket;
839 			af = SOCK_DOM(so);
840 			if (af != ifa->ifa_addr->sa_family) {
841 				continue;
842 			}
843 			if (inp->inp_last_outifp != ifa->ifa_ifp) {
844 				continue;
845 			}
846 
847 			if (af == AF_INET) {
848 				if (inp->inp_laddr.s_addr ==
849 				    (satosin(ifa->ifa_addr))->sin_addr.s_addr) {
850 					lck_rw_done(&pcbinfo->ipi_lock);
851 					return 1;
852 				}
853 			}
854 			if (af == AF_INET6) {
855 				if (in6_are_addr_equal_scoped(IFA_IN6(ifa), &inp->in6p_laddr, SIN6(ifa->ifa_addr)->sin6_scope_id, inp->inp_lifscope)) {
856 					lck_rw_done(&pcbinfo->ipi_lock);
857 					return 1;
858 				}
859 			}
860 		}
861 	}
862 	lck_rw_done(&pcbinfo->ipi_lock);
863 	return 0;
864 }
865 
866 static int
shutdown_sockets_on_interface_proc_callout(proc_t p,void * arg)867 shutdown_sockets_on_interface_proc_callout(proc_t p, void *arg)
868 {
869 	struct fileproc *fp;
870 	struct ifnet *ifp = (struct ifnet *)arg;
871 
872 	if (ifp == NULL) {
873 		return PROC_RETURNED;
874 	}
875 
876 	proc_fdlock(p);
877 
878 	fdt_foreach(fp, p) {
879 		struct fileglob *fg = fp->fp_glob;
880 		struct socket *so;
881 		struct inpcb *inp;
882 		struct ifnet *inp_ifp;
883 		int error;
884 
885 		if (FILEGLOB_DTYPE(fg) != DTYPE_SOCKET) {
886 			continue;
887 		}
888 
889 		so = (struct socket *)fp_get_data(fp);
890 		if (SOCK_DOM(so) != PF_INET && SOCK_DOM(so) != PF_INET6) {
891 			continue;
892 		}
893 
894 		inp = (struct inpcb *)so->so_pcb;
895 
896 		if (in_pcb_checkstate(inp, WNT_ACQUIRE, 0) == WNT_STOPUSING) {
897 			continue;
898 		}
899 
900 		socket_lock(so, 1);
901 
902 		if (in_pcb_checkstate(inp, WNT_RELEASE, 1) == WNT_STOPUSING) {
903 			socket_unlock(so, 1);
904 			continue;
905 		}
906 
907 		if (inp->inp_boundifp != NULL) {
908 			inp_ifp = inp->inp_boundifp;
909 		} else if (inp->inp_last_outifp != NULL) {
910 			inp_ifp = inp->inp_last_outifp;
911 		} else {
912 			socket_unlock(so, 1);
913 			continue;
914 		}
915 
916 		if (inp_ifp != ifp && inp_ifp->if_delegated.ifp != ifp) {
917 			socket_unlock(so, 1);
918 			continue;
919 		}
920 		error = sosetdefunct(p, so, 0, TRUE);
921 		if (error != 0) {
922 			log(LOG_ERR, "%s: sosetdefunct() error %d",
923 			    __func__, error);
924 		} else {
925 			error = sodefunct(p, so, 0);
926 			if (error != 0) {
927 				log(LOG_ERR, "%s: sodefunct() error %d",
928 				    __func__, error);
929 			}
930 		}
931 
932 		socket_unlock(so, 1);
933 	}
934 	proc_fdunlock(p);
935 
936 	return PROC_RETURNED;
937 }
938 
939 void
shutdown_sockets_on_interface(struct ifnet * ifp)940 shutdown_sockets_on_interface(struct ifnet *ifp)
941 {
942 	proc_iterate(PROC_ALLPROCLIST,
943 	    shutdown_sockets_on_interface_proc_callout,
944 	    ifp, NULL, NULL);
945 }
946 
947 __private_extern__ int
inp_limit_companion_link(struct inpcbinfo * pcbinfo,u_int32_t limit)948 inp_limit_companion_link(struct inpcbinfo *pcbinfo, u_int32_t limit)
949 {
950 	struct inpcb *inp;
951 	struct socket *so = NULL;
952 
953 	lck_rw_lock_shared(&pcbinfo->ipi_lock);
954 	inp_gen_t gencnt = pcbinfo->ipi_gencnt;
955 	for (inp = LIST_FIRST(pcbinfo->ipi_listhead);
956 	    inp != NULL; inp = LIST_NEXT(inp, inp_list)) {
957 		if (inp->inp_gencnt <= gencnt &&
958 		    inp->inp_state != INPCB_STATE_DEAD &&
959 		    inp->inp_socket != NULL) {
960 			so = inp->inp_socket;
961 
962 			if ((so->so_state & SS_DEFUNCT) || so->so_state & SS_ISDISCONNECTED ||
963 			    SOCK_PROTO(so) != IPPROTO_TCP || inp->inp_last_outifp == NULL ||
964 			    !IFNET_IS_COMPANION_LINK(inp->inp_last_outifp)) {
965 				continue;
966 			}
967 			so->so_snd.sb_flags &= ~SB_LIMITED;
968 			u_int32_t new_size = MAX(MIN(limit, so->so_snd.sb_lowat), so->so_snd.sb_cc);
969 			sbreserve(&so->so_snd, new_size);
970 			so->so_snd.sb_flags |= SB_LIMITED;
971 		}
972 	}
973 	lck_rw_done(&pcbinfo->ipi_lock);
974 	return 0;
975 }
976 
977 __private_extern__ int
inp_recover_companion_link(struct inpcbinfo * pcbinfo)978 inp_recover_companion_link(struct inpcbinfo *pcbinfo)
979 {
980 	struct inpcb *inp;
981 	inp_gen_t gencnt = pcbinfo->ipi_gencnt;
982 	struct socket *so = NULL;
983 
984 	lck_rw_lock_shared(&pcbinfo->ipi_lock);
985 	for (inp = LIST_FIRST(pcbinfo->ipi_listhead);
986 	    inp != NULL; inp = LIST_NEXT(inp, inp_list)) {
987 		if (inp->inp_gencnt <= gencnt &&
988 		    inp->inp_state != INPCB_STATE_DEAD &&
989 		    inp->inp_socket != NULL) {
990 			so = inp->inp_socket;
991 
992 			if (SOCK_PROTO(so) != IPPROTO_TCP || inp->inp_last_outifp == NULL ||
993 			    !(so->so_snd.sb_flags & SB_LIMITED)) {
994 				continue;
995 			}
996 
997 			so->so_snd.sb_flags &= ~SB_LIMITED;
998 		}
999 	}
1000 	lck_rw_done(&pcbinfo->ipi_lock);
1001 	return 0;
1002 }
1003