2 * Copyright (c) 2012-2017, 2020 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
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.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
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.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
30 #include <sys/types.h>
31 #include <sys/syslog.h>
32 #include <sys/queue.h>
33 #include <sys/malloc.h>
34 #include <sys/socket.h>
35 #include <sys/kpi_mbuf.h>
37 #include <sys/domain.h>
38 #include <sys/protosw.h>
39 #include <sys/socketvar.h>
40 #include <sys/kernel.h>
41 #include <sys/systm.h>
42 #include <sys/kern_control.h>
44 #include <sys/codesign.h>
45 #include <libkern/tree.h>
46 #include <kern/locks.h>
47 #include <kern/debug.h>
48 #include <kern/task.h>
49 #include <mach/task_info.h>
50 #include <net/if_var.h>
51 #include <net/route.h>
52 #include <net/flowhash.h>
53 #include <net/ntstat.h>
54 #include <net/content_filter.h>
56 #include <netinet/in.h>
57 #include <netinet/in_var.h>
58 #include <netinet/tcp.h>
59 #include <netinet/tcp_var.h>
60 #include <netinet/tcp_fsm.h>
61 #include <netinet/flow_divert.h>
62 #include <netinet/flow_divert_proto.h>
63 #include <netinet6/in6_pcb.h>
64 #include <netinet6/ip6protosw.h>
65 #include <dev/random/randomdev.h>
66 #include <libkern/crypto/sha1.h>
67 #include <libkern/crypto/crypto_internal.h>
69 #include <corecrypto/cc.h>
71 #include <net/content_filter.h>
72 #endif /* CONTENT_FILTER */
74 #define FLOW_DIVERT_CONNECT_STARTED 0x00000001
75 #define FLOW_DIVERT_READ_CLOSED 0x00000002
76 #define FLOW_DIVERT_WRITE_CLOSED 0x00000004
77 #define FLOW_DIVERT_TUNNEL_RD_CLOSED 0x00000008
78 #define FLOW_DIVERT_TUNNEL_WR_CLOSED 0x00000010
79 #define FLOW_DIVERT_HAS_HMAC 0x00000040
80 #define FLOW_DIVERT_NOTIFY_ON_RECEIVED 0x00000080
81 #define FLOW_DIVERT_IMPLICIT_CONNECT 0x00000100
82 #define FLOW_DIVERT_DID_SET_LOCAL_ADDR 0x00000200
84 #define FDLOG(level, pcb, format, ...) \
85 os_log_with_type(OS_LOG_DEFAULT, flow_divert_syslog_type_to_oslog_type(level), "(%u): " format "\n", (pcb)->hash, __VA_ARGS__)
87 #define FDLOG0(level, pcb, msg) \
88 os_log_with_type(OS_LOG_DEFAULT, flow_divert_syslog_type_to_oslog_type(level), "(%u): " msg "\n", (pcb)->hash)
90 #define FDRETAIN(pcb) if ((pcb) != NULL) OSIncrementAtomic(&(pcb)->ref_count)
91 #define FDRELEASE(pcb) \
93 if ((pcb) != NULL && 1 == OSDecrementAtomic(&(pcb)->ref_count)) { \
94 flow_divert_pcb_destroy(pcb); \
98 #define FDLOCK(pcb) lck_mtx_lock(&(pcb)->mtx)
99 #define FDUNLOCK(pcb) lck_mtx_unlock(&(pcb)->mtx)
101 #define FD_CTL_SENDBUFF_SIZE (128 * 1024)
102 #define FD_CTL_RCVBUFF_SIZE (128 * 1024)
104 #define GROUP_BIT_CTL_ENQUEUE_BLOCKED 0
106 #define GROUP_COUNT_MAX 31
107 #define FLOW_DIVERT_MAX_NAME_SIZE 4096
108 #define FLOW_DIVERT_MAX_KEY_SIZE 1024
109 #define FLOW_DIVERT_MAX_TRIE_MEMORY (1024 * 1024)
111 struct flow_divert_trie_node
{
117 #define CHILD_MAP_SIZE 256
118 #define NULL_TRIE_IDX 0xffff
119 #define TRIE_NODE(t, i) ((t)->nodes[(i)])
120 #define TRIE_CHILD(t, i, b) (((t)->child_maps + (CHILD_MAP_SIZE * TRIE_NODE(t, i).child_map))[(b)])
121 #define TRIE_BYTE(t, i) ((t)->bytes[(i)])
123 static struct flow_divert_pcb nil_pcb
;
125 decl_lck_rw_data(static, g_flow_divert_group_lck
);
126 static struct flow_divert_group
**g_flow_divert_groups
= NULL
;
127 static uint32_t g_active_group_count
= 0;
129 static lck_grp_attr_t
*flow_divert_grp_attr
= NULL
;
130 static lck_attr_t
*flow_divert_mtx_attr
= NULL
;
131 static lck_grp_t
*flow_divert_mtx_grp
= NULL
;
132 static errno_t g_init_result
= 0;
134 static kern_ctl_ref g_flow_divert_kctl_ref
= NULL
;
136 static struct protosw g_flow_divert_in_protosw
;
137 static struct pr_usrreqs g_flow_divert_in_usrreqs
;
138 static struct protosw g_flow_divert_in_udp_protosw
;
139 static struct pr_usrreqs g_flow_divert_in_udp_usrreqs
;
140 static struct ip6protosw g_flow_divert_in6_protosw
;
141 static struct pr_usrreqs g_flow_divert_in6_usrreqs
;
142 static struct ip6protosw g_flow_divert_in6_udp_protosw
;
143 static struct pr_usrreqs g_flow_divert_in6_udp_usrreqs
;
145 static struct protosw
*g_tcp_protosw
= NULL
;
146 static struct ip6protosw
*g_tcp6_protosw
= NULL
;
147 static struct protosw
*g_udp_protosw
= NULL
;
148 static struct ip6protosw
*g_udp6_protosw
= NULL
;
150 ZONE_DECLARE(flow_divert_group_zone
, "flow_divert_group",
151 sizeof(struct flow_divert_group
), ZC_ZFREE_CLEARMEM
| ZC_NOENCRYPT
);
152 ZONE_DECLARE(flow_divert_pcb_zone
, "flow_divert_pcb",
153 sizeof(struct flow_divert_pcb
), ZC_ZFREE_CLEARMEM
| ZC_NOENCRYPT
);
156 flow_divert_dup_addr(sa_family_t family
, struct sockaddr
*addr
, struct sockaddr
**dup
);
159 flow_divert_is_sockaddr_valid(struct sockaddr
*addr
);
162 flow_divert_append_target_endpoint_tlv(mbuf_t connect_packet
, struct sockaddr
*toaddr
);
165 flow_divert_get_buffered_target_address(mbuf_t buffer
);
168 flow_divert_disconnect_socket(struct socket
*so
);
170 static inline uint8_t
171 flow_divert_syslog_type_to_oslog_type(int syslog_type
)
173 switch (syslog_type
) {
174 case LOG_ERR
: return OS_LOG_TYPE_ERROR
;
175 case LOG_INFO
: return OS_LOG_TYPE_INFO
;
176 case LOG_DEBUG
: return OS_LOG_TYPE_DEBUG
;
177 default: return OS_LOG_TYPE_DEFAULT
;
182 flow_divert_pcb_cmp(const struct flow_divert_pcb
*pcb_a
, const struct flow_divert_pcb
*pcb_b
)
184 return memcmp(&pcb_a
->hash
, &pcb_b
->hash
, sizeof(pcb_a
->hash
));
187 RB_PROTOTYPE(fd_pcb_tree
, flow_divert_pcb
, rb_link
, flow_divert_pcb_cmp
);
188 RB_GENERATE(fd_pcb_tree
, flow_divert_pcb
, rb_link
, flow_divert_pcb_cmp
);
191 flow_divert_packet_type2str(uint8_t packet_type
)
193 switch (packet_type
) {
194 case FLOW_DIVERT_PKT_CONNECT
:
196 case FLOW_DIVERT_PKT_CONNECT_RESULT
:
197 return "connect result";
198 case FLOW_DIVERT_PKT_DATA
:
200 case FLOW_DIVERT_PKT_CLOSE
:
202 case FLOW_DIVERT_PKT_READ_NOTIFY
:
203 return "read notification";
204 case FLOW_DIVERT_PKT_PROPERTIES_UPDATE
:
205 return "properties update";
206 case FLOW_DIVERT_PKT_APP_MAP_CREATE
:
207 return "app map create";
213 static struct flow_divert_pcb
*
214 flow_divert_pcb_lookup(uint32_t hash
, struct flow_divert_group
*group
)
216 struct flow_divert_pcb key_item
;
217 struct flow_divert_pcb
*fd_cb
= NULL
;
219 key_item
.hash
= hash
;
221 lck_rw_lock_shared(&group
->lck
);
222 fd_cb
= RB_FIND(fd_pcb_tree
, &group
->pcb_tree
, &key_item
);
224 lck_rw_done(&group
->lck
);
230 flow_divert_pcb_insert(struct flow_divert_pcb
*fd_cb
, uint32_t ctl_unit
)
233 struct flow_divert_pcb
*exist
= NULL
;
234 struct flow_divert_group
*group
;
235 static uint32_t g_nextkey
= 1;
236 static uint32_t g_hash_seed
= 0;
239 if (ctl_unit
== 0 || ctl_unit
>= GROUP_COUNT_MAX
) {
243 socket_unlock(fd_cb
->so
, 0);
244 lck_rw_lock_shared(&g_flow_divert_group_lck
);
246 if (g_flow_divert_groups
== NULL
|| g_active_group_count
== 0) {
247 FDLOG0(LOG_ERR
, &nil_pcb
, "No active groups, flow divert cannot be used for this socket");
252 group
= g_flow_divert_groups
[ctl_unit
];
254 FDLOG(LOG_ERR
, &nil_pcb
, "Group for control unit %u is NULL, flow divert cannot be used for this socket", ctl_unit
);
259 socket_lock(fd_cb
->so
, 0);
265 key
[0] = g_nextkey
++;
266 key
[1] = RandomULong();
268 if (g_hash_seed
== 0) {
269 g_hash_seed
= RandomULong();
272 fd_cb
->hash
= net_flowhash(key
, sizeof(key
), g_hash_seed
);
274 for (idx
= 1; idx
< GROUP_COUNT_MAX
; idx
++) {
275 struct flow_divert_group
*curr_group
= g_flow_divert_groups
[idx
];
276 if (curr_group
!= NULL
&& curr_group
!= group
) {
277 lck_rw_lock_shared(&curr_group
->lck
);
278 exist
= RB_FIND(fd_pcb_tree
, &curr_group
->pcb_tree
, fd_cb
);
279 lck_rw_done(&curr_group
->lck
);
287 lck_rw_lock_exclusive(&group
->lck
);
288 exist
= RB_INSERT(fd_pcb_tree
, &group
->pcb_tree
, fd_cb
);
289 lck_rw_done(&group
->lck
);
291 } while (exist
!= NULL
&& try_count
++ < 3);
294 fd_cb
->group
= group
;
295 FDRETAIN(fd_cb
); /* The group now has a reference */
301 socket_unlock(fd_cb
->so
, 0);
304 lck_rw_done(&g_flow_divert_group_lck
);
305 socket_lock(fd_cb
->so
, 0);
310 static struct flow_divert_pcb
*
311 flow_divert_pcb_create(socket_t so
)
313 struct flow_divert_pcb
*new_pcb
= NULL
;
315 new_pcb
= zalloc_flags(flow_divert_pcb_zone
, Z_WAITOK
| Z_ZERO
);
316 lck_mtx_init(&new_pcb
->mtx
, flow_divert_mtx_grp
, flow_divert_mtx_attr
);
318 new_pcb
->log_level
= nil_pcb
.log_level
;
320 FDRETAIN(new_pcb
); /* Represents the socket's reference */
326 flow_divert_pcb_destroy(struct flow_divert_pcb
*fd_cb
)
328 FDLOG(LOG_INFO
, fd_cb
, "Destroying, app tx %u, tunnel tx %u, tunnel rx %u",
329 fd_cb
->bytes_written_by_app
, fd_cb
->bytes_sent
, fd_cb
->bytes_received
);
331 if (fd_cb
->connect_token
!= NULL
) {
332 mbuf_freem(fd_cb
->connect_token
);
334 if (fd_cb
->connect_packet
!= NULL
) {
335 mbuf_freem(fd_cb
->connect_packet
);
337 if (fd_cb
->app_data
!= NULL
) {
338 FREE(fd_cb
->app_data
, M_TEMP
);
340 if (fd_cb
->original_remote_endpoint
!= NULL
) {
341 FREE(fd_cb
->original_remote_endpoint
, M_SONAME
);
343 zfree(flow_divert_pcb_zone
, fd_cb
);
347 flow_divert_pcb_remove(struct flow_divert_pcb
*fd_cb
)
349 if (fd_cb
->group
!= NULL
) {
350 struct flow_divert_group
*group
= fd_cb
->group
;
351 lck_rw_lock_exclusive(&group
->lck
);
352 FDLOG(LOG_INFO
, fd_cb
, "Removing from group %d, ref count = %d", group
->ctl_unit
, fd_cb
->ref_count
);
353 RB_REMOVE(fd_pcb_tree
, &group
->pcb_tree
, fd_cb
);
355 FDRELEASE(fd_cb
); /* Release the group's reference */
356 lck_rw_done(&group
->lck
);
361 flow_divert_packet_init(struct flow_divert_pcb
*fd_cb
, uint8_t packet_type
, mbuf_t
*packet
)
363 struct flow_divert_packet_header hdr
;
366 error
= mbuf_gethdr(MBUF_DONTWAIT
, MBUF_TYPE_HEADER
, packet
);
368 FDLOG(LOG_ERR
, fd_cb
, "failed to allocate the header mbuf: %d", error
);
372 hdr
.packet_type
= packet_type
;
373 hdr
.conn_id
= htonl(fd_cb
->hash
);
375 /* Lay down the header */
376 error
= mbuf_copyback(*packet
, 0, sizeof(hdr
), &hdr
, MBUF_DONTWAIT
);
378 FDLOG(LOG_ERR
, fd_cb
, "mbuf_copyback(hdr) failed: %d", error
);
388 flow_divert_packet_append_tlv(mbuf_t packet
, uint8_t type
, uint32_t length
, const void *value
)
390 uint32_t net_length
= htonl(length
);
393 error
= mbuf_copyback(packet
, mbuf_pkthdr_len(packet
), sizeof(type
), &type
, MBUF_DONTWAIT
);
395 FDLOG(LOG_ERR
, &nil_pcb
, "failed to append the type (%d)", type
);
399 error
= mbuf_copyback(packet
, mbuf_pkthdr_len(packet
), sizeof(net_length
), &net_length
, MBUF_DONTWAIT
);
401 FDLOG(LOG_ERR
, &nil_pcb
, "failed to append the length (%u)", length
);
405 error
= mbuf_copyback(packet
, mbuf_pkthdr_len(packet
), length
, value
, MBUF_DONTWAIT
);
407 FDLOG0(LOG_ERR
, &nil_pcb
, "failed to append the value");
415 flow_divert_packet_find_tlv(mbuf_t packet
, int offset
, uint8_t type
, int *err
, int next
)
417 size_t cursor
= offset
;
419 uint32_t curr_length
;
426 error
= mbuf_copydata(packet
, cursor
, sizeof(curr_type
), &curr_type
);
433 curr_type
= FLOW_DIVERT_TLV_NIL
;
436 if (curr_type
!= type
) {
437 cursor
+= sizeof(curr_type
);
438 error
= mbuf_copydata(packet
, cursor
, sizeof(curr_length
), &curr_length
);
444 cursor
+= (sizeof(curr_length
) + ntohl(curr_length
));
446 } while (curr_type
!= type
);
452 flow_divert_packet_get_tlv(mbuf_t packet
, int offset
, uint8_t type
, size_t buff_len
, void *buff
, uint32_t *val_size
)
458 tlv_offset
= flow_divert_packet_find_tlv(packet
, offset
, type
, &error
, 0);
459 if (tlv_offset
< 0) {
463 error
= mbuf_copydata(packet
, tlv_offset
+ sizeof(type
), sizeof(length
), &length
);
468 length
= ntohl(length
);
470 uint32_t data_offset
= tlv_offset
+ sizeof(type
) + sizeof(length
);
472 if (length
> (mbuf_pkthdr_len(packet
) - data_offset
)) {
473 FDLOG(LOG_ERR
, &nil_pcb
, "Length of %u TLV (%u) is larger than remaining packet data (%lu)", type
, length
, (mbuf_pkthdr_len(packet
) - data_offset
));
477 if (val_size
!= NULL
) {
481 if (buff
!= NULL
&& buff_len
> 0) {
482 memset(buff
, 0, buff_len
);
483 size_t to_copy
= (length
< buff_len
) ? length
: buff_len
;
484 error
= mbuf_copydata(packet
, data_offset
, to_copy
, buff
);
494 flow_divert_packet_compute_hmac(mbuf_t packet
, struct flow_divert_group
*group
, uint8_t *hmac
)
496 mbuf_t curr_mbuf
= packet
;
498 if (g_crypto_funcs
== NULL
|| group
->token_key
== NULL
) {
502 cchmac_di_decl(g_crypto_funcs
->ccsha1_di
, hmac_ctx
);
503 g_crypto_funcs
->cchmac_init_fn(g_crypto_funcs
->ccsha1_di
, hmac_ctx
, group
->token_key_size
, group
->token_key
);
505 while (curr_mbuf
!= NULL
) {
506 g_crypto_funcs
->cchmac_update_fn(g_crypto_funcs
->ccsha1_di
, hmac_ctx
, mbuf_len(curr_mbuf
), mbuf_data(curr_mbuf
));
507 curr_mbuf
= mbuf_next(curr_mbuf
);
510 g_crypto_funcs
->cchmac_final_fn(g_crypto_funcs
->ccsha1_di
, hmac_ctx
, hmac
);
516 flow_divert_packet_verify_hmac(mbuf_t packet
, uint32_t ctl_unit
)
519 struct flow_divert_group
*group
= NULL
;
521 uint8_t packet_hmac
[SHA_DIGEST_LENGTH
];
522 uint8_t computed_hmac
[SHA_DIGEST_LENGTH
];
525 lck_rw_lock_shared(&g_flow_divert_group_lck
);
527 if (g_flow_divert_groups
!= NULL
&& g_active_group_count
> 0) {
528 group
= g_flow_divert_groups
[ctl_unit
];
532 lck_rw_done(&g_flow_divert_group_lck
);
536 lck_rw_lock_shared(&group
->lck
);
538 if (group
->token_key
== NULL
) {
543 hmac_offset
= flow_divert_packet_find_tlv(packet
, 0, FLOW_DIVERT_TLV_HMAC
, &error
, 0);
544 if (hmac_offset
< 0) {
548 error
= flow_divert_packet_get_tlv(packet
, hmac_offset
, FLOW_DIVERT_TLV_HMAC
, sizeof(packet_hmac
), packet_hmac
, NULL
);
553 /* Chop off the HMAC TLV */
554 error
= mbuf_split(packet
, hmac_offset
, MBUF_WAITOK
, &tail
);
561 error
= flow_divert_packet_compute_hmac(packet
, group
, computed_hmac
);
566 if (cc_cmp_safe(sizeof(packet_hmac
), packet_hmac
, computed_hmac
)) {
567 FDLOG0(LOG_WARNING
, &nil_pcb
, "HMAC in token does not match computed HMAC");
573 lck_rw_done(&group
->lck
);
574 lck_rw_done(&g_flow_divert_group_lck
);
579 flow_divert_add_data_statistics(struct flow_divert_pcb
*fd_cb
, size_t data_len
, Boolean send
)
581 struct inpcb
*inp
= NULL
;
582 struct ifnet
*ifp
= NULL
;
583 Boolean cell
= FALSE
;
584 Boolean wifi
= FALSE
;
585 Boolean wired
= FALSE
;
587 inp
= sotoinpcb(fd_cb
->so
);
592 if (inp
->inp_vflag
& INP_IPV4
) {
593 ifp
= inp
->inp_last_outifp
;
594 } else if (inp
->inp_vflag
& INP_IPV6
) {
595 ifp
= inp
->in6p_last_outifp
;
598 cell
= IFNET_IS_CELLULAR(ifp
);
599 wifi
= (!cell
&& IFNET_IS_WIFI(ifp
));
600 wired
= (!wifi
&& IFNET_IS_WIRED(ifp
));
604 INP_ADD_STAT(inp
, cell
, wifi
, wired
, txpackets
, 1);
605 INP_ADD_STAT(inp
, cell
, wifi
, wired
, txbytes
, data_len
);
607 INP_ADD_STAT(inp
, cell
, wifi
, wired
, rxpackets
, 1);
608 INP_ADD_STAT(inp
, cell
, wifi
, wired
, rxbytes
, data_len
);
610 inp_set_activity_bitmap(inp
);
614 flow_divert_check_no_cellular(struct flow_divert_pcb
*fd_cb
)
616 struct inpcb
*inp
= sotoinpcb(fd_cb
->so
);
617 if (INP_NO_CELLULAR(inp
)) {
618 struct ifnet
*ifp
= NULL
;
619 if (inp
->inp_vflag
& INP_IPV4
) {
620 ifp
= inp
->inp_last_outifp
;
621 } else if (inp
->inp_vflag
& INP_IPV6
) {
622 ifp
= inp
->in6p_last_outifp
;
624 if (ifp
!= NULL
&& IFNET_IS_CELLULAR(ifp
)) {
625 FDLOG0(LOG_ERR
, fd_cb
, "Cellular is denied");
633 flow_divert_check_no_expensive(struct flow_divert_pcb
*fd_cb
)
635 struct inpcb
*inp
= sotoinpcb(fd_cb
->so
);
636 if (INP_NO_EXPENSIVE(inp
)) {
637 struct ifnet
*ifp
= NULL
;
638 if (inp
->inp_vflag
& INP_IPV4
) {
639 ifp
= inp
->inp_last_outifp
;
640 } else if (inp
->inp_vflag
& INP_IPV6
) {
641 ifp
= inp
->in6p_last_outifp
;
643 if (ifp
!= NULL
&& IFNET_IS_EXPENSIVE(ifp
)) {
644 FDLOG0(LOG_ERR
, fd_cb
, "Expensive is denied");
652 flow_divert_check_no_constrained(struct flow_divert_pcb
*fd_cb
)
654 struct inpcb
*inp
= sotoinpcb(fd_cb
->so
);
655 if (INP_NO_CONSTRAINED(inp
)) {
656 struct ifnet
*ifp
= NULL
;
657 if (inp
->inp_vflag
& INP_IPV4
) {
658 ifp
= inp
->inp_last_outifp
;
659 } else if (inp
->inp_vflag
& INP_IPV6
) {
660 ifp
= inp
->in6p_last_outifp
;
662 if (ifp
!= NULL
&& IFNET_IS_CONSTRAINED(ifp
)) {
663 FDLOG0(LOG_ERR
, fd_cb
, "Constrained is denied");
671 flow_divert_update_closed_state(struct flow_divert_pcb
*fd_cb
, int how
, Boolean tunnel
)
673 if (how
!= SHUT_RD
) {
674 fd_cb
->flags
|= FLOW_DIVERT_WRITE_CLOSED
;
675 if (tunnel
|| !(fd_cb
->flags
& FLOW_DIVERT_CONNECT_STARTED
)) {
676 fd_cb
->flags
|= FLOW_DIVERT_TUNNEL_WR_CLOSED
;
677 /* If the tunnel is not accepting writes any more, then flush the send buffer */
678 sbflush(&fd_cb
->so
->so_snd
);
681 if (how
!= SHUT_WR
) {
682 fd_cb
->flags
|= FLOW_DIVERT_READ_CLOSED
;
683 if (tunnel
|| !(fd_cb
->flags
& FLOW_DIVERT_CONNECT_STARTED
)) {
684 fd_cb
->flags
|= FLOW_DIVERT_TUNNEL_RD_CLOSED
;
690 trie_node_alloc(struct flow_divert_trie
*trie
)
692 if (trie
->nodes_free_next
< trie
->nodes_count
) {
693 uint16_t node_idx
= trie
->nodes_free_next
++;
694 TRIE_NODE(trie
, node_idx
).child_map
= NULL_TRIE_IDX
;
697 return NULL_TRIE_IDX
;
702 trie_child_map_alloc(struct flow_divert_trie
*trie
)
704 if (trie
->child_maps_free_next
< trie
->child_maps_count
) {
705 return trie
->child_maps_free_next
++;
707 return NULL_TRIE_IDX
;
712 trie_bytes_move(struct flow_divert_trie
*trie
, uint16_t bytes_idx
, size_t bytes_size
)
714 uint16_t start
= trie
->bytes_free_next
;
715 if (start
+ bytes_size
<= trie
->bytes_count
) {
716 if (start
!= bytes_idx
) {
717 memmove(&TRIE_BYTE(trie
, start
), &TRIE_BYTE(trie
, bytes_idx
), bytes_size
);
719 trie
->bytes_free_next
+= bytes_size
;
722 return NULL_TRIE_IDX
;
727 flow_divert_trie_insert(struct flow_divert_trie
*trie
, uint16_t string_start
, size_t string_len
)
729 uint16_t current
= trie
->root
;
730 uint16_t child
= trie
->root
;
731 uint16_t string_end
= string_start
+ (uint16_t)string_len
;
732 uint16_t string_idx
= string_start
;
733 uint16_t string_remainder
= (uint16_t)string_len
;
735 while (child
!= NULL_TRIE_IDX
) {
736 uint16_t parent
= current
;
738 uint16_t current_end
;
741 child
= NULL_TRIE_IDX
;
743 current_end
= TRIE_NODE(trie
, current
).start
+ TRIE_NODE(trie
, current
).length
;
745 for (node_idx
= TRIE_NODE(trie
, current
).start
;
746 node_idx
< current_end
&&
747 string_idx
< string_end
&&
748 TRIE_BYTE(trie
, node_idx
) == TRIE_BYTE(trie
, string_idx
);
749 node_idx
++, string_idx
++) {
753 string_remainder
= string_end
- string_idx
;
755 if (node_idx
< (TRIE_NODE(trie
, current
).start
+ TRIE_NODE(trie
, current
).length
)) {
757 * We did not reach the end of the current node's string.
758 * We need to split the current node into two:
759 * 1. A new node that contains the prefix of the node that matches
760 * the prefix of the string being inserted.
761 * 2. The current node modified to point to the remainder
762 * of the current node's string.
764 uint16_t prefix
= trie_node_alloc(trie
);
765 if (prefix
== NULL_TRIE_IDX
) {
766 FDLOG0(LOG_ERR
, &nil_pcb
, "Ran out of trie nodes while splitting an existing node");
767 return NULL_TRIE_IDX
;
771 * Prefix points to the portion of the current nodes's string that has matched
772 * the input string thus far.
774 TRIE_NODE(trie
, prefix
).start
= TRIE_NODE(trie
, current
).start
;
775 TRIE_NODE(trie
, prefix
).length
= (node_idx
- TRIE_NODE(trie
, current
).start
);
778 * Prefix has the current node as the child corresponding to the first byte
781 TRIE_NODE(trie
, prefix
).child_map
= trie_child_map_alloc(trie
);
782 if (TRIE_NODE(trie
, prefix
).child_map
== NULL_TRIE_IDX
) {
783 FDLOG0(LOG_ERR
, &nil_pcb
, "Ran out of child maps while splitting an existing node");
784 return NULL_TRIE_IDX
;
786 TRIE_CHILD(trie
, prefix
, TRIE_BYTE(trie
, node_idx
)) = current
;
788 /* Parent has the prefix as the child correspoding to the first byte in the prefix */
789 TRIE_CHILD(trie
, parent
, TRIE_BYTE(trie
, TRIE_NODE(trie
, prefix
).start
)) = prefix
;
791 /* Current node is adjusted to point to the remainder */
792 TRIE_NODE(trie
, current
).start
= node_idx
;
793 TRIE_NODE(trie
, current
).length
-= TRIE_NODE(trie
, prefix
).length
;
795 /* We want to insert the new leaf (if any) as a child of the prefix */
799 if (string_remainder
> 0) {
801 * We still have bytes in the string that have not been matched yet.
802 * If the current node has children, iterate to the child corresponding
803 * to the next byte in the string.
805 if (TRIE_NODE(trie
, current
).child_map
!= NULL_TRIE_IDX
) {
806 child
= TRIE_CHILD(trie
, current
, TRIE_BYTE(trie
, string_idx
));
809 } /* while (child != NULL_TRIE_IDX) */
811 if (string_remainder
> 0) {
812 /* Add a new leaf containing the remainder of the string */
813 uint16_t leaf
= trie_node_alloc(trie
);
814 if (leaf
== NULL_TRIE_IDX
) {
815 FDLOG0(LOG_ERR
, &nil_pcb
, "Ran out of trie nodes while inserting a new leaf");
816 return NULL_TRIE_IDX
;
819 TRIE_NODE(trie
, leaf
).start
= trie_bytes_move(trie
, string_idx
, string_remainder
);
820 if (TRIE_NODE(trie
, leaf
).start
== NULL_TRIE_IDX
) {
821 FDLOG0(LOG_ERR
, &nil_pcb
, "Ran out of bytes while inserting a new leaf");
822 return NULL_TRIE_IDX
;
824 TRIE_NODE(trie
, leaf
).length
= string_remainder
;
826 /* Set the new leaf as the child of the current node */
827 if (TRIE_NODE(trie
, current
).child_map
== NULL_TRIE_IDX
) {
828 TRIE_NODE(trie
, current
).child_map
= trie_child_map_alloc(trie
);
829 if (TRIE_NODE(trie
, current
).child_map
== NULL_TRIE_IDX
) {
830 FDLOG0(LOG_ERR
, &nil_pcb
, "Ran out of child maps while inserting a new leaf");
831 return NULL_TRIE_IDX
;
834 TRIE_CHILD(trie
, current
, TRIE_BYTE(trie
, TRIE_NODE(trie
, leaf
).start
)) = leaf
;
836 } /* else duplicate or this string is a prefix of one of the existing strings */
841 #define APPLE_WEBCLIP_ID_PREFIX "com.apple.webapp"
843 flow_divert_trie_search(struct flow_divert_trie
*trie
, const uint8_t *string_bytes
)
845 uint16_t current
= trie
->root
;
846 uint16_t string_idx
= 0;
848 while (current
!= NULL_TRIE_IDX
) {
849 uint16_t next
= NULL_TRIE_IDX
;
850 uint16_t node_end
= TRIE_NODE(trie
, current
).start
+ TRIE_NODE(trie
, current
).length
;
853 for (node_idx
= TRIE_NODE(trie
, current
).start
;
854 node_idx
< node_end
&& string_bytes
[string_idx
] != '\0' && string_bytes
[string_idx
] == TRIE_BYTE(trie
, node_idx
);
855 node_idx
++, string_idx
++) {
859 if (node_idx
== node_end
) {
860 if (string_bytes
[string_idx
] == '\0') {
861 return current
; /* Got an exact match */
862 } else if (string_idx
== strlen(APPLE_WEBCLIP_ID_PREFIX
) &&
863 0 == strncmp((const char *)string_bytes
, APPLE_WEBCLIP_ID_PREFIX
, string_idx
)) {
864 return current
; /* Got an apple webclip id prefix match */
865 } else if (TRIE_NODE(trie
, current
).child_map
!= NULL_TRIE_IDX
) {
866 next
= TRIE_CHILD(trie
, current
, string_bytes
[string_idx
]);
872 return NULL_TRIE_IDX
;
875 struct uuid_search_info
{
877 char *found_signing_id
;
878 boolean_t found_multiple_signing_ids
;
883 flow_divert_find_proc_by_uuid_callout(proc_t p
, void *arg
)
885 struct uuid_search_info
*info
= (struct uuid_search_info
*)arg
;
886 int result
= PROC_RETURNED_DONE
; /* By default, we didn't find the process */
888 if (info
->found_signing_id
!= NULL
) {
889 if (!info
->found_multiple_signing_ids
) {
890 /* All processes that were found had the same signing identifier, so just claim this first one and be done. */
891 info
->found_proc
= p
;
892 result
= PROC_CLAIMED_DONE
;
894 uuid_string_t uuid_str
;
895 uuid_unparse(info
->target_uuid
, uuid_str
);
896 FDLOG(LOG_WARNING
, &nil_pcb
, "Found multiple processes with UUID %s with different signing identifiers", uuid_str
);
898 FREE(info
->found_signing_id
, M_TEMP
);
899 info
->found_signing_id
= NULL
;
902 if (result
== PROC_RETURNED_DONE
) {
903 uuid_string_t uuid_str
;
904 uuid_unparse(info
->target_uuid
, uuid_str
);
905 FDLOG(LOG_WARNING
, &nil_pcb
, "Failed to find a process with UUID %s", uuid_str
);
912 flow_divert_find_proc_by_uuid_filter(proc_t p
, void *arg
)
914 struct uuid_search_info
*info
= (struct uuid_search_info
*)arg
;
917 if (info
->found_multiple_signing_ids
) {
921 include
= (uuid_compare(p
->p_uuid
, info
->target_uuid
) == 0);
923 const char *signing_id
= cs_identity_get(p
);
924 if (signing_id
!= NULL
) {
925 FDLOG(LOG_INFO
, &nil_pcb
, "Found process %d with signing identifier %s", p
->p_pid
, signing_id
);
926 size_t signing_id_size
= strlen(signing_id
) + 1;
927 if (info
->found_signing_id
== NULL
) {
928 MALLOC(info
->found_signing_id
, char *, signing_id_size
, M_TEMP
, M_WAITOK
);
929 memcpy(info
->found_signing_id
, signing_id
, signing_id_size
);
930 } else if (memcmp(signing_id
, info
->found_signing_id
, signing_id_size
)) {
931 info
->found_multiple_signing_ids
= TRUE
;
934 info
->found_multiple_signing_ids
= TRUE
;
936 include
= !info
->found_multiple_signing_ids
;
943 flow_divert_find_proc_by_uuid(uuid_t uuid
)
945 struct uuid_search_info info
;
947 if (LOG_INFO
<= nil_pcb
.log_level
) {
948 uuid_string_t uuid_str
;
949 uuid_unparse(uuid
, uuid_str
);
950 FDLOG(LOG_INFO
, &nil_pcb
, "Looking for process with UUID %s", uuid_str
);
953 memset(&info
, 0, sizeof(info
));
954 info
.found_proc
= PROC_NULL
;
955 uuid_copy(info
.target_uuid
, uuid
);
957 proc_iterate(PROC_ALLPROCLIST
, flow_divert_find_proc_by_uuid_callout
, &info
, flow_divert_find_proc_by_uuid_filter
, &info
);
959 return info
.found_proc
;
963 flow_divert_add_proc_info(struct flow_divert_pcb
*fd_cb
, proc_t proc
, const char *signing_id
, mbuf_t connect_packet
, bool is_effective
)
966 uint8_t *cdhash
= NULL
;
967 audit_token_t audit_token
= {};
968 const char *proc_cs_id
= signing_id
;
972 if (proc_cs_id
== NULL
) {
973 if (proc
->p_csflags
& (CS_VALID
| CS_DEBUGGED
)) {
974 proc_cs_id
= cs_identity_get(proc
);
976 FDLOG0(LOG_ERR
, fd_cb
, "Signature of proc is invalid");
981 lck_rw_lock_shared(&fd_cb
->group
->lck
);
982 if (!(fd_cb
->group
->flags
& FLOW_DIVERT_GROUP_FLAG_NO_APP_MAP
)) {
983 if (proc_cs_id
!= NULL
) {
984 uint16_t result
= flow_divert_trie_search(&fd_cb
->group
->signing_id_trie
, (const uint8_t *)proc_cs_id
);
985 if (result
== NULL_TRIE_IDX
) {
986 FDLOG(LOG_WARNING
, fd_cb
, "%s did not match", proc_cs_id
);
989 FDLOG(LOG_INFO
, fd_cb
, "%s matched", proc_cs_id
);
995 lck_rw_done(&fd_cb
->group
->lck
);
1003 * If signing_id is not NULL then it came from the flow divert token and will be added
1004 * as part of the token, so there is no need to add it here.
1006 if (signing_id
== NULL
&& proc_cs_id
!= NULL
) {
1007 error
= flow_divert_packet_append_tlv(connect_packet
,
1008 (is_effective
? FLOW_DIVERT_TLV_SIGNING_ID
: FLOW_DIVERT_TLV_APP_REAL_SIGNING_ID
),
1009 (uint32_t)strlen(proc_cs_id
),
1012 FDLOG(LOG_ERR
, fd_cb
, "failed to append the signing ID: %d", error
);
1017 cdhash
= cs_get_cdhash(proc
);
1018 if (cdhash
!= NULL
) {
1019 error
= flow_divert_packet_append_tlv(connect_packet
,
1020 (is_effective
? FLOW_DIVERT_TLV_CDHASH
: FLOW_DIVERT_TLV_APP_REAL_CDHASH
),
1024 FDLOG(LOG_ERR
, fd_cb
, "failed to append the cdhash: %d", error
);
1028 FDLOG0(LOG_ERR
, fd_cb
, "failed to get the cdhash");
1031 task_t task
= proc_task(proc
);
1032 if (task
!= TASK_NULL
) {
1033 mach_msg_type_number_t count
= TASK_AUDIT_TOKEN_COUNT
;
1034 kern_return_t rc
= task_info(task
, TASK_AUDIT_TOKEN
, (task_info_t
)&audit_token
, &count
);
1035 if (rc
== KERN_SUCCESS
) {
1036 int append_error
= flow_divert_packet_append_tlv(connect_packet
,
1037 (is_effective
? FLOW_DIVERT_TLV_APP_AUDIT_TOKEN
: FLOW_DIVERT_TLV_APP_REAL_AUDIT_TOKEN
),
1038 sizeof(audit_token_t
),
1041 FDLOG(LOG_ERR
, fd_cb
, "failed to append app audit token: %d", append_error
);
1053 flow_divert_add_all_proc_info(struct flow_divert_pcb
*fd_cb
, struct socket
*so
, proc_t proc
, const char *signing_id
, mbuf_t connect_packet
)
1056 proc_t effective_proc
= PROC_NULL
;
1057 proc_t responsible_proc
= PROC_NULL
;
1058 proc_t real_proc
= proc_find(so
->last_pid
);
1059 bool release_real_proc
= true;
1061 proc_t src_proc
= PROC_NULL
;
1062 proc_t real_src_proc
= PROC_NULL
;
1064 if (real_proc
== PROC_NULL
) {
1065 FDLOG(LOG_ERR
, fd_cb
, "failed to find the real proc record for %d", so
->last_pid
);
1066 release_real_proc
= false;
1068 if (real_proc
== PROC_NULL
) {
1069 real_proc
= current_proc();
1073 if (so
->so_flags
& SOF_DELEGATED
) {
1074 if (real_proc
->p_pid
!= so
->e_pid
) {
1075 effective_proc
= proc_find(so
->e_pid
);
1076 } else if (uuid_compare(real_proc
->p_uuid
, so
->e_uuid
)) {
1077 effective_proc
= flow_divert_find_proc_by_uuid(so
->e_uuid
);
1081 #if defined(XNU_TARGET_OS_OSX)
1082 lck_rw_lock_shared(&fd_cb
->group
->lck
);
1083 if (!(fd_cb
->group
->flags
& FLOW_DIVERT_GROUP_FLAG_NO_APP_MAP
)) {
1084 if (so
->so_rpid
> 0) {
1085 responsible_proc
= proc_find(so
->so_rpid
);
1088 lck_rw_done(&fd_cb
->group
->lck
);
1091 real_src_proc
= real_proc
;
1093 if (responsible_proc
!= PROC_NULL
) {
1094 src_proc
= responsible_proc
;
1095 if (effective_proc
!= NULL
) {
1096 real_src_proc
= effective_proc
;
1098 } else if (effective_proc
!= PROC_NULL
) {
1099 src_proc
= effective_proc
;
1101 src_proc
= real_proc
;
1104 error
= flow_divert_add_proc_info(fd_cb
, src_proc
, signing_id
, connect_packet
, true);
1109 if (real_src_proc
!= NULL
&& real_src_proc
!= src_proc
) {
1110 error
= flow_divert_add_proc_info(fd_cb
, real_src_proc
, NULL
, connect_packet
, false);
1117 if (responsible_proc
!= PROC_NULL
) {
1118 proc_rele(responsible_proc
);
1121 if (effective_proc
!= PROC_NULL
) {
1122 proc_rele(effective_proc
);
1125 if (real_proc
!= PROC_NULL
&& release_real_proc
) {
1126 proc_rele(real_proc
);
1133 flow_divert_send_packet(struct flow_divert_pcb
*fd_cb
, mbuf_t packet
, Boolean enqueue
)
1137 if (fd_cb
->group
== NULL
) {
1138 fd_cb
->so
->so_error
= ECONNABORTED
;
1139 flow_divert_disconnect_socket(fd_cb
->so
);
1140 return ECONNABORTED
;
1143 lck_rw_lock_shared(&fd_cb
->group
->lck
);
1145 if (MBUFQ_EMPTY(&fd_cb
->group
->send_queue
)) {
1146 error
= ctl_enqueuembuf(g_flow_divert_kctl_ref
, fd_cb
->group
->ctl_unit
, packet
, CTL_DATA_EOR
);
1151 if (error
== ENOBUFS
) {
1153 if (!lck_rw_lock_shared_to_exclusive(&fd_cb
->group
->lck
)) {
1154 lck_rw_lock_exclusive(&fd_cb
->group
->lck
);
1156 MBUFQ_ENQUEUE(&fd_cb
->group
->send_queue
, packet
);
1159 OSTestAndSet(GROUP_BIT_CTL_ENQUEUE_BLOCKED
, &fd_cb
->group
->atomic_bits
);
1162 lck_rw_done(&fd_cb
->group
->lck
);
1168 flow_divert_create_connect_packet(struct flow_divert_pcb
*fd_cb
, struct sockaddr
*to
, struct socket
*so
, proc_t p
, mbuf_t
*out_connect_packet
)
1172 char *signing_id
= NULL
;
1173 mbuf_t connect_packet
= NULL
;
1174 cfil_sock_id_t cfil_sock_id
= CFIL_SOCK_ID_NONE
;
1175 const void *cfil_id
= NULL
;
1176 size_t cfil_id_size
= 0;
1177 struct inpcb
*inp
= sotoinpcb(so
);
1178 struct ifnet
*ifp
= NULL
;
1180 error
= flow_divert_packet_init(fd_cb
, FLOW_DIVERT_PKT_CONNECT
, &connect_packet
);
1185 if (fd_cb
->connect_token
!= NULL
&& (fd_cb
->flags
& FLOW_DIVERT_HAS_HMAC
)) {
1186 uint32_t sid_size
= 0;
1187 int find_error
= flow_divert_packet_get_tlv(fd_cb
->connect_token
, 0, FLOW_DIVERT_TLV_SIGNING_ID
, 0, NULL
, &sid_size
);
1188 if (find_error
== 0 && sid_size
> 0) {
1189 MALLOC(signing_id
, char *, sid_size
+ 1, M_TEMP
, M_WAITOK
| M_ZERO
);
1190 if (signing_id
!= NULL
) {
1191 flow_divert_packet_get_tlv(fd_cb
->connect_token
, 0, FLOW_DIVERT_TLV_SIGNING_ID
, sid_size
, signing_id
, NULL
);
1192 FDLOG(LOG_INFO
, fd_cb
, "Got %s from token", signing_id
);
1197 socket_unlock(so
, 0);
1199 error
= flow_divert_add_all_proc_info(fd_cb
, so
, p
, signing_id
, connect_packet
);
1203 if (signing_id
!= NULL
) {
1204 FREE(signing_id
, M_TEMP
);
1208 FDLOG(LOG_ERR
, fd_cb
, "Failed to add source proc info: %d", error
);
1212 error
= flow_divert_packet_append_tlv(connect_packet
,
1213 FLOW_DIVERT_TLV_TRAFFIC_CLASS
,
1214 sizeof(fd_cb
->so
->so_traffic_class
),
1215 &fd_cb
->so
->so_traffic_class
);
1220 if (SOCK_TYPE(fd_cb
->so
) == SOCK_STREAM
) {
1221 flow_type
= FLOW_DIVERT_FLOW_TYPE_TCP
;
1222 } else if (SOCK_TYPE(fd_cb
->so
) == SOCK_DGRAM
) {
1223 flow_type
= FLOW_DIVERT_FLOW_TYPE_UDP
;
1228 error
= flow_divert_packet_append_tlv(connect_packet
,
1229 FLOW_DIVERT_TLV_FLOW_TYPE
,
1237 if (fd_cb
->connect_token
!= NULL
) {
1238 unsigned int token_len
= m_length(fd_cb
->connect_token
);
1239 mbuf_concatenate(connect_packet
, fd_cb
->connect_token
);
1240 mbuf_pkthdr_adjustlen(connect_packet
, token_len
);
1241 fd_cb
->connect_token
= NULL
;
1243 error
= flow_divert_append_target_endpoint_tlv(connect_packet
, to
);
1249 if (fd_cb
->local_endpoint
.sa
.sa_family
== AF_INET
|| fd_cb
->local_endpoint
.sa
.sa_family
== AF_INET6
) {
1250 error
= flow_divert_packet_append_tlv(connect_packet
, FLOW_DIVERT_TLV_LOCAL_ADDR
, fd_cb
->local_endpoint
.sa
.sa_len
, &(fd_cb
->local_endpoint
.sa
));
1256 if (inp
->inp_vflag
& INP_IPV4
) {
1257 ifp
= inp
->inp_last_outifp
;
1258 } else if (inp
->inp_vflag
& INP_IPV6
) {
1259 ifp
= inp
->in6p_last_outifp
;
1262 uint32_t flow_if_index
= ifp
->if_index
;
1263 error
= flow_divert_packet_append_tlv(connect_packet
, FLOW_DIVERT_TLV_OUT_IF_INDEX
,
1264 sizeof(flow_if_index
), &flow_if_index
);
1270 if (so
->so_flags1
& SOF1_DATA_IDEMPOTENT
) {
1271 uint32_t flags
= FLOW_DIVERT_TOKEN_FLAG_TFO
;
1272 error
= flow_divert_packet_append_tlv(connect_packet
, FLOW_DIVERT_TLV_FLAGS
, sizeof(flags
), &flags
);
1278 if (SOCK_TYPE(so
) == SOCK_DGRAM
) {
1279 cfil_sock_id
= cfil_sock_id_from_datagram_socket(so
, NULL
, to
);
1281 cfil_sock_id
= cfil_sock_id_from_socket(so
);
1284 if (cfil_sock_id
!= CFIL_SOCK_ID_NONE
) {
1285 cfil_id
= &cfil_sock_id
;
1286 cfil_id_size
= sizeof(cfil_sock_id
);
1287 } else if (so
->so_flags1
& SOF1_CONTENT_FILTER_SKIP
) {
1288 cfil_id
= &inp
->necp_client_uuid
;
1289 cfil_id_size
= sizeof(inp
->necp_client_uuid
);
1292 if (cfil_id
!= NULL
&& cfil_id_size
> 0 && cfil_id_size
<= sizeof(uuid_t
)) {
1293 error
= flow_divert_packet_append_tlv(connect_packet
, FLOW_DIVERT_TLV_CFIL_ID
, (uint32_t)cfil_id_size
, cfil_id
);
1301 *out_connect_packet
= connect_packet
;
1302 } else if (connect_packet
!= NULL
) {
1303 mbuf_freem(connect_packet
);
1310 flow_divert_send_connect_packet(struct flow_divert_pcb
*fd_cb
)
1313 mbuf_t connect_packet
= fd_cb
->connect_packet
;
1314 mbuf_t saved_connect_packet
= NULL
;
1316 if (connect_packet
!= NULL
) {
1317 error
= mbuf_copym(connect_packet
, 0, mbuf_pkthdr_len(connect_packet
), MBUF_DONTWAIT
, &saved_connect_packet
);
1319 FDLOG0(LOG_ERR
, fd_cb
, "Failed to copy the connect packet");
1323 error
= flow_divert_send_packet(fd_cb
, connect_packet
, TRUE
);
1328 fd_cb
->connect_packet
= saved_connect_packet
;
1329 saved_connect_packet
= NULL
;
1334 if (saved_connect_packet
!= NULL
) {
1335 mbuf_freem(saved_connect_packet
);
1342 flow_divert_send_connect_result(struct flow_divert_pcb
*fd_cb
)
1345 mbuf_t packet
= NULL
;
1346 int rbuff_space
= 0;
1348 error
= flow_divert_packet_init(fd_cb
, FLOW_DIVERT_PKT_CONNECT_RESULT
, &packet
);
1350 FDLOG(LOG_ERR
, fd_cb
, "failed to create a connect result packet: %d", error
);
1354 rbuff_space
= fd_cb
->so
->so_rcv
.sb_hiwat
;
1355 if (rbuff_space
< 0) {
1358 rbuff_space
= htonl(rbuff_space
);
1359 error
= flow_divert_packet_append_tlv(packet
,
1360 FLOW_DIVERT_TLV_SPACE_AVAILABLE
,
1361 sizeof(rbuff_space
),
1367 error
= flow_divert_send_packet(fd_cb
, packet
, TRUE
);
1373 if (error
&& packet
!= NULL
) {
1381 flow_divert_send_close(struct flow_divert_pcb
*fd_cb
, int how
)
1384 mbuf_t packet
= NULL
;
1387 error
= flow_divert_packet_init(fd_cb
, FLOW_DIVERT_PKT_CLOSE
, &packet
);
1389 FDLOG(LOG_ERR
, fd_cb
, "failed to create a close packet: %d", error
);
1393 error
= flow_divert_packet_append_tlv(packet
, FLOW_DIVERT_TLV_ERROR_CODE
, sizeof(zero
), &zero
);
1395 FDLOG(LOG_ERR
, fd_cb
, "failed to add the error code TLV: %d", error
);
1400 error
= flow_divert_packet_append_tlv(packet
, FLOW_DIVERT_TLV_HOW
, sizeof(how
), &how
);
1402 FDLOG(LOG_ERR
, fd_cb
, "failed to add the how flag: %d", error
);
1406 error
= flow_divert_send_packet(fd_cb
, packet
, TRUE
);
1412 if (error
&& packet
!= NULL
) {
1420 flow_divert_tunnel_how_closed(struct flow_divert_pcb
*fd_cb
)
1422 if ((fd_cb
->flags
& (FLOW_DIVERT_TUNNEL_RD_CLOSED
| FLOW_DIVERT_TUNNEL_WR_CLOSED
)) ==
1423 (FLOW_DIVERT_TUNNEL_RD_CLOSED
| FLOW_DIVERT_TUNNEL_WR_CLOSED
)) {
1425 } else if (fd_cb
->flags
& FLOW_DIVERT_TUNNEL_RD_CLOSED
) {
1427 } else if (fd_cb
->flags
& FLOW_DIVERT_TUNNEL_WR_CLOSED
) {
1435 * Determine what close messages if any need to be sent to the tunnel. Returns TRUE if the tunnel is closed for both reads and
1436 * writes. Returns FALSE otherwise.
1439 flow_divert_send_close_if_needed(struct flow_divert_pcb
*fd_cb
)
1443 /* Do not send any close messages if there is still data in the send buffer */
1444 if (fd_cb
->so
->so_snd
.sb_cc
== 0) {
1445 if ((fd_cb
->flags
& (FLOW_DIVERT_READ_CLOSED
| FLOW_DIVERT_TUNNEL_RD_CLOSED
)) == FLOW_DIVERT_READ_CLOSED
) {
1446 /* Socket closed reads, but tunnel did not. Tell tunnel to close reads */
1449 if ((fd_cb
->flags
& (FLOW_DIVERT_WRITE_CLOSED
| FLOW_DIVERT_TUNNEL_WR_CLOSED
)) == FLOW_DIVERT_WRITE_CLOSED
) {
1450 /* Socket closed writes, but tunnel did not. Tell tunnel to close writes */
1451 if (how
== SHUT_RD
) {
1460 FDLOG(LOG_INFO
, fd_cb
, "sending close, how = %d", how
);
1461 if (flow_divert_send_close(fd_cb
, how
) != ENOBUFS
) {
1462 /* Successfully sent the close packet. Record the ways in which the tunnel has been closed */
1463 if (how
!= SHUT_RD
) {
1464 fd_cb
->flags
|= FLOW_DIVERT_TUNNEL_WR_CLOSED
;
1466 if (how
!= SHUT_WR
) {
1467 fd_cb
->flags
|= FLOW_DIVERT_TUNNEL_RD_CLOSED
;
1472 if (flow_divert_tunnel_how_closed(fd_cb
) == SHUT_RDWR
) {
1473 flow_divert_disconnect_socket(fd_cb
->so
);
1478 flow_divert_send_data_packet(struct flow_divert_pcb
*fd_cb
, mbuf_t data
, size_t data_len
, struct sockaddr
*toaddr
, Boolean force
)
1480 mbuf_t packet
= NULL
;
1484 error
= flow_divert_packet_init(fd_cb
, FLOW_DIVERT_PKT_DATA
, &packet
);
1485 if (error
|| packet
== NULL
) {
1486 FDLOG(LOG_ERR
, fd_cb
, "flow_divert_packet_init failed: %d", error
);
1490 if (toaddr
!= NULL
) {
1491 error
= flow_divert_append_target_endpoint_tlv(packet
, toaddr
);
1493 FDLOG(LOG_ERR
, fd_cb
, "flow_divert_append_target_endpoint_tlv() failed: %d", error
);
1498 if (data_len
> 0 && data_len
<= INT_MAX
&& data
!= NULL
) {
1499 last
= m_last(packet
);
1500 mbuf_setnext(last
, data
);
1501 mbuf_pkthdr_adjustlen(packet
, (int)data_len
);
1505 error
= flow_divert_send_packet(fd_cb
, packet
, force
);
1506 if (error
== 0 && data_len
> 0) {
1507 fd_cb
->bytes_sent
+= data_len
;
1508 flow_divert_add_data_statistics(fd_cb
, data_len
, TRUE
);
1514 mbuf_setnext(last
, NULL
);
1516 if (packet
!= NULL
) {
1525 flow_divert_send_buffered_data(struct flow_divert_pcb
*fd_cb
, Boolean force
)
1532 to_send
= fd_cb
->so
->so_snd
.sb_cc
;
1533 buffer
= fd_cb
->so
->so_snd
.sb_mb
;
1535 if (buffer
== NULL
&& to_send
> 0) {
1536 FDLOG(LOG_ERR
, fd_cb
, "Send buffer is NULL, but size is supposed to be %lu", to_send
);
1540 /* Ignore the send window if force is enabled */
1541 if (!force
&& (to_send
> fd_cb
->send_window
)) {
1542 to_send
= fd_cb
->send_window
;
1545 if (SOCK_TYPE(fd_cb
->so
) == SOCK_STREAM
) {
1546 while (sent
< to_send
) {
1550 data_len
= to_send
- sent
;
1551 if (data_len
> FLOW_DIVERT_CHUNK_SIZE
) {
1552 data_len
= FLOW_DIVERT_CHUNK_SIZE
;
1555 error
= mbuf_copym(buffer
, sent
, data_len
, MBUF_DONTWAIT
, &data
);
1557 FDLOG(LOG_ERR
, fd_cb
, "mbuf_copym failed: %d", error
);
1561 error
= flow_divert_send_data_packet(fd_cb
, data
, data_len
, NULL
, force
);
1571 sbdrop(&fd_cb
->so
->so_snd
, (int)sent
);
1572 sowwakeup(fd_cb
->so
);
1573 } else if (SOCK_TYPE(fd_cb
->so
) == SOCK_DGRAM
) {
1579 struct sockaddr
*toaddr
= flow_divert_get_buffered_target_address(buffer
);
1582 if (toaddr
!= NULL
) {
1583 /* look for data in the chain */
1586 if (m
!= NULL
&& m
->m_type
== MT_DATA
) {
1592 FDLOG0(LOG_ERR
, fd_cb
, "failed to find type MT_DATA in the mbuf chain.");
1596 data_len
= mbuf_pkthdr_len(m
);
1598 FDLOG(LOG_DEBUG
, fd_cb
, "mbuf_copym() data_len = %lu", data_len
);
1599 error
= mbuf_copym(m
, 0, data_len
, MBUF_DONTWAIT
, &data
);
1601 FDLOG(LOG_ERR
, fd_cb
, "mbuf_copym failed: %d", error
);
1607 error
= flow_divert_send_data_packet(fd_cb
, data
, data_len
, toaddr
, force
);
1616 buffer
= buffer
->m_nextpkt
;
1617 (void) sbdroprecord(&(fd_cb
->so
->so_snd
));
1622 FDLOG(LOG_DEBUG
, fd_cb
, "sent %lu bytes of buffered data", sent
);
1623 if (fd_cb
->send_window
>= sent
) {
1624 fd_cb
->send_window
-= sent
;
1626 fd_cb
->send_window
= 0;
1632 flow_divert_send_app_data(struct flow_divert_pcb
*fd_cb
, mbuf_t data
, struct sockaddr
*toaddr
)
1634 size_t to_send
= mbuf_pkthdr_len(data
);
1637 if (to_send
> fd_cb
->send_window
) {
1638 to_send
= fd_cb
->send_window
;
1641 if (fd_cb
->so
->so_snd
.sb_cc
> 0) {
1642 to_send
= 0; /* If the send buffer is non-empty, then we can't send anything */
1645 if (SOCK_TYPE(fd_cb
->so
) == SOCK_STREAM
) {
1647 mbuf_t remaining_data
= data
;
1648 mbuf_t pkt_data
= NULL
;
1649 while (sent
< to_send
&& remaining_data
!= NULL
) {
1650 size_t pkt_data_len
;
1652 pkt_data
= remaining_data
;
1654 if ((to_send
- sent
) > FLOW_DIVERT_CHUNK_SIZE
) {
1655 pkt_data_len
= FLOW_DIVERT_CHUNK_SIZE
;
1657 pkt_data_len
= to_send
- sent
;
1660 if (pkt_data_len
< mbuf_pkthdr_len(pkt_data
)) {
1661 error
= mbuf_split(pkt_data
, pkt_data_len
, MBUF_DONTWAIT
, &remaining_data
);
1663 FDLOG(LOG_ERR
, fd_cb
, "mbuf_split failed: %d", error
);
1668 remaining_data
= NULL
;
1671 error
= flow_divert_send_data_packet(fd_cb
, pkt_data
, pkt_data_len
, NULL
, FALSE
);
1678 sent
+= pkt_data_len
;
1681 fd_cb
->send_window
-= sent
;
1685 if (pkt_data
!= NULL
) {
1686 if (sbspace(&fd_cb
->so
->so_snd
) > 0) {
1687 if (!sbappendstream(&fd_cb
->so
->so_snd
, pkt_data
)) {
1688 FDLOG(LOG_ERR
, fd_cb
, "sbappendstream failed with pkt_data, send buffer size = %u, send_window = %u\n",
1689 fd_cb
->so
->so_snd
.sb_cc
, fd_cb
->send_window
);
1692 mbuf_freem(pkt_data
);
1697 if (remaining_data
!= NULL
) {
1698 if (sbspace(&fd_cb
->so
->so_snd
) > 0) {
1699 if (!sbappendstream(&fd_cb
->so
->so_snd
, remaining_data
)) {
1700 FDLOG(LOG_ERR
, fd_cb
, "sbappendstream failed with remaining_data, send buffer size = %u, send_window = %u\n",
1701 fd_cb
->so
->so_snd
.sb_cc
, fd_cb
->send_window
);
1704 mbuf_freem(remaining_data
);
1708 } else if (SOCK_TYPE(fd_cb
->so
) == SOCK_DGRAM
) {
1709 if (to_send
|| mbuf_pkthdr_len(data
) == 0) {
1710 error
= flow_divert_send_data_packet(fd_cb
, data
, to_send
, toaddr
, FALSE
);
1712 FDLOG(LOG_ERR
, fd_cb
, "flow_divert_send_data_packet failed. send data size = %lu", to_send
);
1717 fd_cb
->send_window
-= to_send
;
1721 if (sbspace(&fd_cb
->so
->so_snd
) >= (int)mbuf_pkthdr_len(data
)) {
1722 if (toaddr
!= NULL
) {
1723 if (!sbappendaddr(&fd_cb
->so
->so_snd
, toaddr
, data
, NULL
, &error
)) {
1724 FDLOG(LOG_ERR
, fd_cb
,
1725 "sbappendaddr failed. send buffer size = %u, send_window = %u, error = %d\n",
1726 fd_cb
->so
->so_snd
.sb_cc
, fd_cb
->send_window
, error
);
1730 if (!sbappendrecord(&fd_cb
->so
->so_snd
, data
)) {
1731 FDLOG(LOG_ERR
, fd_cb
,
1732 "sbappendrecord failed. send buffer size = %u, send_window = %u, error = %d\n",
1733 fd_cb
->so
->so_snd
.sb_cc
, fd_cb
->send_window
, error
);
1749 flow_divert_send_read_notification(struct flow_divert_pcb
*fd_cb
)
1752 mbuf_t packet
= NULL
;
1754 error
= flow_divert_packet_init(fd_cb
, FLOW_DIVERT_PKT_READ_NOTIFY
, &packet
);
1756 FDLOG(LOG_ERR
, fd_cb
, "failed to create a read notification packet: %d", error
);
1760 error
= flow_divert_send_packet(fd_cb
, packet
, TRUE
);
1766 if (error
&& packet
!= NULL
) {
1774 flow_divert_send_traffic_class_update(struct flow_divert_pcb
*fd_cb
, int traffic_class
)
1777 mbuf_t packet
= NULL
;
1779 error
= flow_divert_packet_init(fd_cb
, FLOW_DIVERT_PKT_PROPERTIES_UPDATE
, &packet
);
1781 FDLOG(LOG_ERR
, fd_cb
, "failed to create a properties update packet: %d", error
);
1785 error
= flow_divert_packet_append_tlv(packet
, FLOW_DIVERT_TLV_TRAFFIC_CLASS
, sizeof(traffic_class
), &traffic_class
);
1787 FDLOG(LOG_ERR
, fd_cb
, "failed to add the traffic class: %d", error
);
1791 error
= flow_divert_send_packet(fd_cb
, packet
, TRUE
);
1797 if (error
&& packet
!= NULL
) {
1805 flow_divert_set_local_endpoint(struct flow_divert_pcb
*fd_cb
, struct sockaddr
*local_endpoint
, bool port_only
)
1807 struct inpcb
*inp
= sotoinpcb(fd_cb
->so
);
1809 if (local_endpoint
->sa_family
== AF_INET6
) {
1810 if (IN6_IS_ADDR_UNSPECIFIED(&inp
->in6p_laddr
) && !port_only
) {
1811 fd_cb
->flags
|= FLOW_DIVERT_DID_SET_LOCAL_ADDR
;
1812 inp
->in6p_laddr
= (satosin6(local_endpoint
))->sin6_addr
;
1814 if (inp
->inp_lport
== 0) {
1815 inp
->inp_lport
= (satosin6(local_endpoint
))->sin6_port
;
1817 } else if (local_endpoint
->sa_family
== AF_INET
) {
1818 if (inp
->inp_laddr
.s_addr
== INADDR_ANY
&& !port_only
) {
1819 fd_cb
->flags
|= FLOW_DIVERT_DID_SET_LOCAL_ADDR
;
1820 inp
->inp_laddr
= (satosin(local_endpoint
))->sin_addr
;
1822 if (inp
->inp_lport
== 0) {
1823 inp
->inp_lport
= (satosin(local_endpoint
))->sin_port
;
1829 flow_divert_set_remote_endpoint(struct flow_divert_pcb
*fd_cb
, struct sockaddr
*remote_endpoint
)
1831 struct inpcb
*inp
= sotoinpcb(fd_cb
->so
);
1833 if (remote_endpoint
->sa_family
== AF_INET6
) {
1834 if (IN6_IS_ADDR_UNSPECIFIED(&inp
->in6p_faddr
)) {
1835 inp
->in6p_faddr
= (satosin6(remote_endpoint
))->sin6_addr
;
1837 if (inp
->inp_fport
== 0) {
1838 inp
->inp_fport
= (satosin6(remote_endpoint
))->sin6_port
;
1840 } else if (remote_endpoint
->sa_family
== AF_INET
) {
1841 if (inp
->inp_laddr
.s_addr
== INADDR_ANY
) {
1842 inp
->inp_faddr
= (satosin(remote_endpoint
))->sin_addr
;
1844 if (inp
->inp_fport
== 0) {
1845 inp
->inp_fport
= (satosin(remote_endpoint
))->sin_port
;
1851 flow_divert_derive_kernel_control_unit(uint32_t ctl_unit
, uint32_t *aggregate_unit
)
1853 if (aggregate_unit
!= NULL
&& *aggregate_unit
!= 0) {
1855 for (counter
= 0; counter
< (GROUP_COUNT_MAX
- 1); counter
++) {
1856 if ((*aggregate_unit
) & (1 << counter
)) {
1860 if (counter
< (GROUP_COUNT_MAX
- 1)) {
1861 *aggregate_unit
&= ~(1 << counter
);
1872 flow_divert_try_next(struct flow_divert_pcb
*fd_cb
)
1874 uint32_t current_ctl_unit
= 0;
1875 uint32_t next_ctl_unit
= 0;
1876 struct flow_divert_group
*current_group
= NULL
;
1877 struct flow_divert_group
*next_group
= NULL
;
1880 next_ctl_unit
= flow_divert_derive_kernel_control_unit(fd_cb
->policy_control_unit
, &(fd_cb
->aggregate_unit
));
1881 current_ctl_unit
= fd_cb
->control_group_unit
;
1883 if (current_ctl_unit
== next_ctl_unit
) {
1884 FDLOG0(LOG_NOTICE
, fd_cb
, "Next control unit is the same as the current control unit, disabling flow divert");
1889 if (next_ctl_unit
== 0 || next_ctl_unit
>= GROUP_COUNT_MAX
) {
1890 FDLOG0(LOG_NOTICE
, fd_cb
, "No more valid control units, disabling flow divert");
1895 if (g_flow_divert_groups
== NULL
|| g_active_group_count
== 0) {
1896 FDLOG0(LOG_NOTICE
, fd_cb
, "No active groups, disabling flow divert");
1901 next_group
= g_flow_divert_groups
[next_ctl_unit
];
1902 if (next_group
== NULL
) {
1903 FDLOG(LOG_NOTICE
, fd_cb
, "Group for control unit %u does not exist", next_ctl_unit
);
1908 current_group
= fd_cb
->group
;
1910 lck_rw_lock_exclusive(&(current_group
->lck
));
1911 lck_rw_lock_exclusive(&(next_group
->lck
));
1913 FDLOG(LOG_NOTICE
, fd_cb
, "Moving from %u to %u", current_ctl_unit
, next_ctl_unit
);
1915 RB_REMOVE(fd_pcb_tree
, &(current_group
->pcb_tree
), fd_cb
);
1916 if (RB_INSERT(fd_pcb_tree
, &(next_group
->pcb_tree
), fd_cb
) != NULL
) {
1917 panic("group with unit %u already contains a connection with hash %u", next_ctl_unit
, fd_cb
->hash
);
1920 fd_cb
->group
= next_group
;
1921 fd_cb
->control_group_unit
= next_ctl_unit
;
1923 lck_rw_done(&(next_group
->lck
));
1924 lck_rw_done(&(current_group
->lck
));
1926 error
= flow_divert_send_connect_packet(fd_cb
);
1928 FDLOG(LOG_NOTICE
, fd_cb
, "Failed to send the connect packet to %u, disabling flow divert", next_ctl_unit
);
1938 flow_divert_disable(struct flow_divert_pcb
*fd_cb
)
1940 struct socket
*so
= NULL
;
1943 proc_t last_proc
= NULL
;
1944 struct sockaddr
*remote_endpoint
= fd_cb
->original_remote_endpoint
;
1945 bool do_connect
= !(fd_cb
->flags
& FLOW_DIVERT_IMPLICIT_CONNECT
);
1946 struct inpcb
*inp
= NULL
;
1953 FDLOG0(LOG_NOTICE
, fd_cb
, "Skipped all flow divert services, disabling flow divert");
1955 /* Restore the IP state */
1956 inp
= sotoinpcb(so
);
1957 inp
->inp_vflag
= fd_cb
->original_vflag
;
1958 inp
->inp_faddr
.s_addr
= INADDR_ANY
;
1960 memset(&(inp
->in6p_faddr
), 0, sizeof(inp
->in6p_faddr
));
1961 inp
->in6p_fport
= 0;
1962 /* If flow divert set the local address, clear it out */
1963 if (fd_cb
->flags
& FLOW_DIVERT_DID_SET_LOCAL_ADDR
) {
1964 inp
->inp_laddr
.s_addr
= INADDR_ANY
;
1965 memset(&(inp
->in6p_laddr
), 0, sizeof(inp
->in6p_laddr
));
1967 inp
->inp_last_outifp
= fd_cb
->original_last_outifp
;
1968 inp
->in6p_last_outifp
= fd_cb
->original_last_outifp6
;
1970 /* Dis-associate the socket */
1971 so
->so_flags
&= ~SOF_FLOW_DIVERT
;
1972 so
->so_flags1
|= SOF1_FLOW_DIVERT_SKIP
;
1973 so
->so_fd_pcb
= NULL
;
1976 /* Remove from the group */
1977 flow_divert_pcb_remove(fd_cb
);
1979 FDRELEASE(fd_cb
); /* Release the socket's reference */
1981 /* Revert back to the original protocol */
1982 so
->so_proto
= pffindproto(SOCK_DOM(so
), SOCK_PROTO(so
), SOCK_TYPE(so
));
1984 last_proc
= proc_find(so
->last_pid
);
1987 /* Connect using the original protocol */
1988 error
= (*so
->so_proto
->pr_usrreqs
->pru_connect
)(so
, remote_endpoint
, (last_proc
!= NULL
? last_proc
: current_proc()));
1990 FDLOG(LOG_ERR
, fd_cb
, "Failed to connect using the socket's original protocol: %d", error
);
1995 buffer
= so
->so_snd
.sb_mb
;
1996 if (buffer
== NULL
) {
1997 /* No buffered data, done */
2001 /* Send any buffered data using the original protocol */
2002 if (SOCK_TYPE(so
) == SOCK_STREAM
) {
2003 mbuf_t data_to_send
= NULL
;
2004 size_t data_len
= so
->so_snd
.sb_cc
;
2006 error
= mbuf_copym(buffer
, 0, data_len
, MBUF_DONTWAIT
, &data_to_send
);
2008 FDLOG0(LOG_ERR
, fd_cb
, "Failed to copy the mbuf chain in the socket's send buffer");
2012 sbflush(&so
->so_snd
);
2014 if (data_to_send
->m_flags
& M_PKTHDR
) {
2015 mbuf_pkthdr_setlen(data_to_send
, data_len
);
2018 error
= (*so
->so_proto
->pr_usrreqs
->pru_send
)(so
,
2023 (last_proc
!= NULL
? last_proc
: current_proc()));
2026 FDLOG(LOG_ERR
, fd_cb
, "Failed to send queued data using the socket's original protocol: %d", error
);
2028 } else if (SOCK_TYPE(so
) == SOCK_DGRAM
) {
2029 struct sockbuf
*sb
= &so
->so_snd
;
2030 MBUFQ_HEAD(send_queue_head
) send_queue
;
2031 MBUFQ_INIT(&send_queue
);
2033 /* Flush the send buffer, moving all records to a temporary queue */
2034 while (sb
->sb_mb
!= NULL
) {
2035 mbuf_t record
= sb
->sb_mb
;
2037 sb
->sb_mb
= sb
->sb_mb
->m_nextpkt
;
2042 record
->m_nextpkt
= NULL
;
2043 MBUFQ_ENQUEUE(&send_queue
, record
);
2047 while (!MBUFQ_EMPTY(&send_queue
)) {
2048 mbuf_t next_record
= MBUFQ_FIRST(&send_queue
);
2050 mbuf_t control
= NULL
;
2051 mbuf_t last_control
= NULL
;
2053 mbuf_t m
= next_record
;
2054 struct sockaddr
*to_endpoint
= NULL
;
2056 MBUFQ_DEQUEUE(&send_queue
, next_record
);
2059 if (m
->m_type
== MT_SONAME
) {
2061 } else if (m
->m_type
== MT_CONTROL
) {
2062 if (control
== NULL
) {
2066 } else if (m
->m_type
== MT_DATA
) {
2074 to_endpoint
= flow_divert_get_buffered_target_address(addr
);
2075 if (to_endpoint
== NULL
) {
2076 FDLOG0(LOG_NOTICE
, fd_cb
, "Failed to get the remote address from the buffer");
2081 FDLOG0(LOG_ERR
, fd_cb
, "Buffered record does not contain any data");
2082 mbuf_freem(next_record
);
2086 if (!(data
->m_flags
& M_PKTHDR
)) {
2087 FDLOG0(LOG_ERR
, fd_cb
, "Buffered data does not have a packet header");
2088 mbuf_freem(next_record
);
2093 addr
->m_next
= NULL
;
2096 if (last_control
!= NULL
) {
2097 last_control
->m_next
= NULL
;
2100 error
= (*so
->so_proto
->pr_usrreqs
->pru_send
)(so
,
2105 (last_proc
!= NULL
? last_proc
: current_proc()));
2112 FDLOG(LOG_ERR
, fd_cb
, "Failed to send queued data using the socket's original protocol: %d", error
);
2117 if (last_proc
!= NULL
) {
2118 proc_rele(last_proc
);
2122 so
->so_error
= (uint16_t)error
;
2123 flow_divert_disconnect_socket(so
);
2128 flow_divert_handle_connect_result(struct flow_divert_pcb
*fd_cb
, mbuf_t packet
, int offset
)
2130 uint32_t connect_error
= 0;
2131 uint32_t ctl_unit
= 0;
2133 struct flow_divert_group
*grp
= NULL
;
2134 union sockaddr_in_4_6 local_endpoint
= {};
2135 union sockaddr_in_4_6 remote_endpoint
= {};
2136 int out_if_index
= 0;
2137 uint32_t send_window
;
2138 uint32_t app_data_length
= 0;
2140 memset(&local_endpoint
, 0, sizeof(local_endpoint
));
2141 memset(&remote_endpoint
, 0, sizeof(remote_endpoint
));
2143 error
= flow_divert_packet_get_tlv(packet
, offset
, FLOW_DIVERT_TLV_ERROR_CODE
, sizeof(connect_error
), &connect_error
, NULL
);
2145 FDLOG(LOG_ERR
, fd_cb
, "failed to get the connect result: %d", error
);
2149 connect_error
= ntohl(connect_error
);
2150 FDLOG(LOG_INFO
, fd_cb
, "received connect result %u", connect_error
);
2152 error
= flow_divert_packet_get_tlv(packet
, offset
, FLOW_DIVERT_TLV_SPACE_AVAILABLE
, sizeof(send_window
), &send_window
, NULL
);
2154 FDLOG(LOG_ERR
, fd_cb
, "failed to get the send window: %d", error
);
2158 error
= flow_divert_packet_get_tlv(packet
, offset
, FLOW_DIVERT_TLV_CTL_UNIT
, sizeof(ctl_unit
), &ctl_unit
, NULL
);
2160 FDLOG0(LOG_INFO
, fd_cb
, "No control unit provided in the connect result");
2163 error
= flow_divert_packet_get_tlv(packet
, offset
, FLOW_DIVERT_TLV_LOCAL_ADDR
, sizeof(local_endpoint
), &(local_endpoint
.sa
), NULL
);
2165 FDLOG0(LOG_INFO
, fd_cb
, "No local address provided");
2168 error
= flow_divert_packet_get_tlv(packet
, offset
, FLOW_DIVERT_TLV_REMOTE_ADDR
, sizeof(remote_endpoint
), &(remote_endpoint
.sa
), NULL
);
2170 FDLOG0(LOG_INFO
, fd_cb
, "No remote address provided");
2173 error
= flow_divert_packet_get_tlv(packet
, offset
, FLOW_DIVERT_TLV_OUT_IF_INDEX
, sizeof(out_if_index
), &out_if_index
, NULL
);
2175 FDLOG0(LOG_INFO
, fd_cb
, "No output if index provided");
2178 error
= flow_divert_packet_get_tlv(packet
, offset
, FLOW_DIVERT_TLV_APP_DATA
, 0, NULL
, &app_data_length
);
2180 FDLOG0(LOG_INFO
, fd_cb
, "No application data provided in connect result");
2184 ctl_unit
= ntohl(ctl_unit
);
2186 lck_rw_lock_shared(&g_flow_divert_group_lck
);
2188 if (connect_error
== 0 && ctl_unit
> 0) {
2189 if (ctl_unit
>= GROUP_COUNT_MAX
) {
2190 FDLOG(LOG_ERR
, fd_cb
, "Connect result contains an invalid control unit: %u", ctl_unit
);
2192 } else if (g_flow_divert_groups
== NULL
|| g_active_group_count
== 0) {
2193 FDLOG0(LOG_ERR
, fd_cb
, "No active groups, dropping connection");
2196 grp
= g_flow_divert_groups
[ctl_unit
];
2204 if (fd_cb
->so
!= NULL
) {
2205 struct inpcb
*inp
= NULL
;
2206 struct ifnet
*ifp
= NULL
;
2207 struct flow_divert_group
*old_group
;
2208 struct socket
*so
= fd_cb
->so
;
2212 if (SOCK_TYPE(so
) == SOCK_STREAM
&& !(so
->so_state
& SS_ISCONNECTING
)) {
2213 FDLOG0(LOG_ERR
, fd_cb
, "TCP socket is not in the connecting state, ignoring connect result");
2217 inp
= sotoinpcb(so
);
2219 if (connect_error
|| error
) {
2220 goto set_socket_state
;
2223 if (flow_divert_is_sockaddr_valid(&(local_endpoint
.sa
))) {
2224 if (local_endpoint
.sa
.sa_family
== AF_INET
) {
2225 local_endpoint
.sa
.sa_len
= sizeof(struct sockaddr_in
);
2226 } else if (local_endpoint
.sa
.sa_family
== AF_INET6
) {
2227 local_endpoint
.sa
.sa_len
= sizeof(struct sockaddr_in6
);
2229 fd_cb
->local_endpoint
= local_endpoint
;
2230 flow_divert_set_local_endpoint(fd_cb
, &(local_endpoint
.sa
), (SOCK_TYPE(so
) == SOCK_DGRAM
));
2233 if (flow_divert_is_sockaddr_valid(&(remote_endpoint
.sa
)) && SOCK_TYPE(so
) == SOCK_STREAM
) {
2234 if (remote_endpoint
.sa
.sa_family
== AF_INET
) {
2235 remote_endpoint
.sa
.sa_len
= sizeof(struct sockaddr_in
);
2236 } else if (remote_endpoint
.sa
.sa_family
== AF_INET6
) {
2237 remote_endpoint
.sa
.sa_len
= sizeof(struct sockaddr_in6
);
2239 flow_divert_set_remote_endpoint(fd_cb
, &(remote_endpoint
.sa
));
2242 if (app_data_length
> 0) {
2243 uint8_t *app_data
= NULL
;
2244 MALLOC(app_data
, uint8_t *, app_data_length
, M_TEMP
, M_WAITOK
);
2245 if (app_data
!= NULL
) {
2246 error
= flow_divert_packet_get_tlv(packet
, offset
, FLOW_DIVERT_TLV_APP_DATA
, app_data_length
, app_data
, NULL
);
2248 FDLOG(LOG_INFO
, fd_cb
, "Got %u bytes of app data from the connect result", app_data_length
);
2249 if (fd_cb
->app_data
!= NULL
) {
2250 FREE(fd_cb
->app_data
, M_TEMP
);
2252 fd_cb
->app_data
= app_data
;
2253 fd_cb
->app_data_length
= app_data_length
;
2255 FDLOG(LOG_ERR
, fd_cb
, "Failed to copy %u bytes of application data from the connect result packet", app_data_length
);
2256 FREE(app_data
, M_TEMP
);
2259 FDLOG(LOG_ERR
, fd_cb
, "Failed to allocate a buffer of size %u to hold the application data from the connect result", app_data_length
);
2263 ifnet_head_lock_shared();
2264 if (out_if_index
> 0 && out_if_index
<= if_index
) {
2265 ifp
= ifindex2ifnet
[out_if_index
];
2269 if (inp
->inp_vflag
& INP_IPV4
) {
2270 inp
->inp_last_outifp
= ifp
;
2271 } else if (inp
->inp_vflag
& INP_IPV6
) {
2272 inp
->in6p_last_outifp
= ifp
;
2280 goto set_socket_state
;
2283 if (fd_cb
->group
== NULL
) {
2285 goto set_socket_state
;
2289 old_group
= fd_cb
->group
;
2291 lck_rw_lock_exclusive(&old_group
->lck
);
2292 lck_rw_lock_exclusive(&grp
->lck
);
2294 RB_REMOVE(fd_pcb_tree
, &old_group
->pcb_tree
, fd_cb
);
2295 if (RB_INSERT(fd_pcb_tree
, &grp
->pcb_tree
, fd_cb
) != NULL
) {
2296 panic("group with unit %u already contains a connection with hash %u", grp
->ctl_unit
, fd_cb
->hash
);
2301 lck_rw_done(&grp
->lck
);
2302 lck_rw_done(&old_group
->lck
);
2305 fd_cb
->send_window
= ntohl(send_window
);
2308 if (!connect_error
&& !error
) {
2309 FDLOG0(LOG_INFO
, fd_cb
, "sending connect result");
2310 error
= flow_divert_send_connect_result(fd_cb
);
2313 if (connect_error
|| error
) {
2314 if (connect_error
&& fd_cb
->control_group_unit
!= fd_cb
->policy_control_unit
) {
2315 error
= flow_divert_try_next(fd_cb
);
2317 flow_divert_disable(fd_cb
);
2322 if (!connect_error
) {
2323 flow_divert_update_closed_state(fd_cb
, SHUT_RDWR
, FALSE
);
2324 so
->so_error
= (uint16_t)error
;
2325 flow_divert_send_close_if_needed(fd_cb
);
2327 flow_divert_update_closed_state(fd_cb
, SHUT_RDWR
, TRUE
);
2328 so
->so_error
= (uint16_t)connect_error
;
2330 flow_divert_disconnect_socket(so
);
2333 /* Update NECP client with connected five-tuple */
2334 if (!uuid_is_null(inp
->necp_client_uuid
)) {
2335 socket_unlock(so
, 0);
2336 necp_client_assign_from_socket(so
->last_pid
, inp
->necp_client_uuid
, inp
);
2341 flow_divert_send_buffered_data(fd_cb
, FALSE
);
2345 /* We don't need the connect packet any more */
2346 if (fd_cb
->connect_packet
!= NULL
) {
2347 mbuf_freem(fd_cb
->connect_packet
);
2348 fd_cb
->connect_packet
= NULL
;
2351 /* We don't need the original remote endpoint any more */
2352 if (fd_cb
->original_remote_endpoint
!= NULL
) {
2353 FREE(fd_cb
->original_remote_endpoint
, M_SONAME
);
2354 fd_cb
->original_remote_endpoint
= NULL
;
2357 socket_unlock(so
, 0);
2361 lck_rw_done(&g_flow_divert_group_lck
);
2365 flow_divert_handle_close(struct flow_divert_pcb
*fd_cb
, mbuf_t packet
, int offset
)
2367 uint32_t close_error
;
2371 error
= flow_divert_packet_get_tlv(packet
, offset
, FLOW_DIVERT_TLV_ERROR_CODE
, sizeof(close_error
), &close_error
, NULL
);
2373 FDLOG(LOG_ERR
, fd_cb
, "failed to get the close error: %d", error
);
2377 error
= flow_divert_packet_get_tlv(packet
, offset
, FLOW_DIVERT_TLV_HOW
, sizeof(how
), &how
, NULL
);
2379 FDLOG(LOG_ERR
, fd_cb
, "failed to get the close how flag: %d", error
);
2385 FDLOG(LOG_INFO
, fd_cb
, "close received, how = %d", how
);
2388 if (fd_cb
->so
!= NULL
) {
2389 socket_lock(fd_cb
->so
, 0);
2391 fd_cb
->so
->so_error
= (uint16_t)ntohl(close_error
);
2393 flow_divert_update_closed_state(fd_cb
, how
, TRUE
);
2395 how
= flow_divert_tunnel_how_closed(fd_cb
);
2396 if (how
== SHUT_RDWR
) {
2397 flow_divert_disconnect_socket(fd_cb
->so
);
2398 } else if (how
== SHUT_RD
) {
2399 socantrcvmore(fd_cb
->so
);
2400 } else if (how
== SHUT_WR
) {
2401 socantsendmore(fd_cb
->so
);
2404 socket_unlock(fd_cb
->so
, 0);
2410 flow_divert_create_control_mbuf(struct flow_divert_pcb
*fd_cb
)
2412 struct inpcb
*inp
= sotoinpcb(fd_cb
->so
);
2413 bool is_cfil_enabled
= false;
2415 /* Content Filter needs to see the local address */
2416 is_cfil_enabled
= (inp
->inp_socket
&& inp
->inp_socket
->so_cfil_db
!= NULL
);
2418 if ((inp
->inp_vflag
& INP_IPV4
) &&
2419 fd_cb
->local_endpoint
.sa
.sa_family
== AF_INET
&&
2420 ((inp
->inp_flags
& INP_RECVDSTADDR
) || is_cfil_enabled
)) {
2421 return sbcreatecontrol((caddr_t
)&(fd_cb
->local_endpoint
.sin
.sin_addr
), sizeof(struct in_addr
), IP_RECVDSTADDR
, IPPROTO_IP
);
2422 } else if ((inp
->inp_vflag
& INP_IPV6
) &&
2423 fd_cb
->local_endpoint
.sa
.sa_family
== AF_INET6
&&
2424 ((inp
->inp_flags
& IN6P_PKTINFO
) || is_cfil_enabled
)) {
2425 struct in6_pktinfo pi6
;
2426 memset(&pi6
, 0, sizeof(pi6
));
2427 pi6
.ipi6_addr
= fd_cb
->local_endpoint
.sin6
.sin6_addr
;
2429 return sbcreatecontrol((caddr_t
)&pi6
, sizeof(pi6
), IPV6_PKTINFO
, IPPROTO_IPV6
);
2435 flow_divert_handle_data(struct flow_divert_pcb
*fd_cb
, mbuf_t packet
, size_t offset
)
2440 if (fd_cb
->so
!= NULL
) {
2443 struct sockaddr_storage remote_address
;
2444 boolean_t got_remote_sa
= FALSE
;
2445 boolean_t appended
= FALSE
;
2446 boolean_t append_success
= FALSE
;
2448 socket_lock(fd_cb
->so
, 0);
2450 if (sbspace(&fd_cb
->so
->so_rcv
) == 0) {
2452 fd_cb
->flags
|= FLOW_DIVERT_NOTIFY_ON_RECEIVED
;
2453 FDLOG0(LOG_INFO
, fd_cb
, "Receive buffer is full, will send read notification when app reads some data");
2457 if (SOCK_TYPE(fd_cb
->so
) == SOCK_DGRAM
) {
2458 uint32_t val_size
= 0;
2460 /* check if we got remote address with data */
2461 memset(&remote_address
, 0, sizeof(remote_address
));
2462 error
= flow_divert_packet_get_tlv(packet
, (int)offset
, FLOW_DIVERT_TLV_REMOTE_ADDR
, sizeof(remote_address
), &remote_address
, &val_size
);
2463 if (error
|| val_size
> sizeof(remote_address
)) {
2464 FDLOG0(LOG_INFO
, fd_cb
, "No remote address provided");
2467 if (remote_address
.ss_len
> sizeof(remote_address
)) {
2468 remote_address
.ss_len
= sizeof(remote_address
);
2470 /* validate the address */
2471 if (flow_divert_is_sockaddr_valid((struct sockaddr
*)&remote_address
)) {
2472 got_remote_sa
= TRUE
;
2474 FDLOG0(LOG_INFO
, fd_cb
, "Remote address is invalid");
2476 offset
+= (sizeof(uint8_t) + sizeof(uint32_t) + val_size
);
2480 data_size
= (mbuf_pkthdr_len(packet
) - offset
);
2482 if (fd_cb
->so
->so_state
& SS_CANTRCVMORE
) {
2483 FDLOG(LOG_NOTICE
, fd_cb
, "app cannot receive any more data, dropping %lu bytes of data", data_size
);
2487 if (SOCK_TYPE(fd_cb
->so
) != SOCK_STREAM
&& SOCK_TYPE(fd_cb
->so
) != SOCK_DGRAM
) {
2488 FDLOG(LOG_ERR
, fd_cb
, "socket has an unsupported type: %d", SOCK_TYPE(fd_cb
->so
));
2492 FDLOG(LOG_DEBUG
, fd_cb
, "received %lu bytes of data", data_size
);
2494 error
= mbuf_split(packet
, offset
, MBUF_DONTWAIT
, &data
);
2495 if (error
|| data
== NULL
) {
2496 FDLOG(LOG_ERR
, fd_cb
, "mbuf_split failed: %d", error
);
2500 if (SOCK_TYPE(fd_cb
->so
) == SOCK_STREAM
) {
2501 appended
= (sbappendstream(&fd_cb
->so
->so_rcv
, data
) != 0);
2502 append_success
= TRUE
;
2504 struct sockaddr
*append_sa
= NULL
;
2507 if (got_remote_sa
== TRUE
) {
2508 error
= flow_divert_dup_addr(remote_address
.ss_family
, (struct sockaddr
*)&remote_address
, &append_sa
);
2510 if (fd_cb
->so
->so_proto
->pr_domain
->dom_family
== AF_INET6
) {
2511 error
= in6_mapped_peeraddr(fd_cb
->so
, &append_sa
);
2513 error
= in_getpeeraddr(fd_cb
->so
, &append_sa
);
2517 FDLOG0(LOG_ERR
, fd_cb
, "failed to dup the socket address.");
2520 mctl
= flow_divert_create_control_mbuf(fd_cb
);
2521 int append_error
= 0;
2522 if (sbappendaddr(&fd_cb
->so
->so_rcv
, append_sa
, data
, mctl
, &append_error
) || append_error
== EJUSTRETURN
) {
2523 append_success
= TRUE
;
2524 appended
= (append_error
== 0);
2526 FDLOG(LOG_ERR
, fd_cb
, "failed to append %lu bytes of data: %d", data_size
, append_error
);
2529 if (append_sa
!= NULL
) {
2530 FREE(append_sa
, M_SONAME
);
2534 if (append_success
) {
2535 fd_cb
->bytes_received
+= data_size
;
2536 flow_divert_add_data_statistics(fd_cb
, data_size
, FALSE
);
2540 sorwakeup(fd_cb
->so
);
2543 socket_unlock(fd_cb
->so
, 0);
2551 flow_divert_handle_read_notification(struct flow_divert_pcb
*fd_cb
, mbuf_t packet
, int offset
)
2553 uint32_t read_count
;
2556 error
= flow_divert_packet_get_tlv(packet
, offset
, FLOW_DIVERT_TLV_READ_COUNT
, sizeof(read_count
), &read_count
, NULL
);
2558 FDLOG(LOG_ERR
, fd_cb
, "failed to get the read count: %d", error
);
2562 FDLOG(LOG_DEBUG
, fd_cb
, "received a read notification for %u bytes", ntohl(read_count
));
2565 if (fd_cb
->so
!= NULL
) {
2566 socket_lock(fd_cb
->so
, 0);
2567 fd_cb
->send_window
+= ntohl(read_count
);
2568 flow_divert_send_buffered_data(fd_cb
, FALSE
);
2569 socket_unlock(fd_cb
->so
, 0);
2575 flow_divert_handle_group_init(struct flow_divert_group
*group
, mbuf_t packet
, int offset
)
2578 uint32_t key_size
= 0;
2582 error
= flow_divert_packet_get_tlv(packet
, offset
, FLOW_DIVERT_TLV_TOKEN_KEY
, 0, NULL
, &key_size
);
2584 FDLOG(LOG_ERR
, &nil_pcb
, "failed to get the key size: %d", error
);
2588 if (key_size
== 0 || key_size
> FLOW_DIVERT_MAX_KEY_SIZE
) {
2589 FDLOG(LOG_ERR
, &nil_pcb
, "Invalid key size: %u", key_size
);
2593 error
= flow_divert_packet_get_tlv(packet
, offset
, FLOW_DIVERT_TLV_LOG_LEVEL
, sizeof(log_level
), &log_level
, NULL
);
2595 nil_pcb
.log_level
= (uint8_t)log_level
;
2598 lck_rw_lock_exclusive(&group
->lck
);
2600 if (group
->token_key
!= NULL
) {
2601 FREE(group
->token_key
, M_TEMP
);
2602 group
->token_key
= NULL
;
2605 MALLOC(group
->token_key
, uint8_t *, key_size
, M_TEMP
, M_WAITOK
);
2606 error
= flow_divert_packet_get_tlv(packet
, offset
, FLOW_DIVERT_TLV_TOKEN_KEY
, key_size
, group
->token_key
, NULL
);
2608 FDLOG(LOG_ERR
, &nil_pcb
, "failed to get the token key: %d", error
);
2609 FREE(group
->token_key
, M_TEMP
);
2610 group
->token_key
= NULL
;
2611 lck_rw_done(&group
->lck
);
2615 group
->token_key_size
= key_size
;
2617 error
= flow_divert_packet_get_tlv(packet
, offset
, FLOW_DIVERT_TLV_FLAGS
, sizeof(flags
), &flags
, NULL
);
2619 group
->flags
= flags
;
2622 lck_rw_done(&group
->lck
);
2626 flow_divert_handle_properties_update(struct flow_divert_pcb
*fd_cb
, mbuf_t packet
, int offset
)
2629 int out_if_index
= 0;
2630 uint32_t app_data_length
= 0;
2632 FDLOG0(LOG_INFO
, fd_cb
, "received a properties update");
2634 error
= flow_divert_packet_get_tlv(packet
, offset
, FLOW_DIVERT_TLV_OUT_IF_INDEX
, sizeof(out_if_index
), &out_if_index
, NULL
);
2636 FDLOG0(LOG_INFO
, fd_cb
, "No output if index provided in properties update");
2639 error
= flow_divert_packet_get_tlv(packet
, offset
, FLOW_DIVERT_TLV_APP_DATA
, 0, NULL
, &app_data_length
);
2641 FDLOG0(LOG_INFO
, fd_cb
, "No application data provided in properties update");
2645 if (fd_cb
->so
!= NULL
) {
2646 socket_lock(fd_cb
->so
, 0);
2648 if (out_if_index
> 0) {
2649 struct inpcb
*inp
= NULL
;
2650 struct ifnet
*ifp
= NULL
;
2652 inp
= sotoinpcb(fd_cb
->so
);
2654 ifnet_head_lock_shared();
2655 if (out_if_index
<= if_index
) {
2656 ifp
= ifindex2ifnet
[out_if_index
];
2660 if (inp
->inp_vflag
& INP_IPV4
) {
2661 inp
->inp_last_outifp
= ifp
;
2662 } else if (inp
->inp_vflag
& INP_IPV6
) {
2663 inp
->in6p_last_outifp
= ifp
;
2669 if (app_data_length
> 0) {
2670 uint8_t *app_data
= NULL
;
2671 MALLOC(app_data
, uint8_t *, app_data_length
, M_TEMP
, M_WAITOK
);
2672 if (app_data
!= NULL
) {
2673 error
= flow_divert_packet_get_tlv(packet
, offset
, FLOW_DIVERT_TLV_APP_DATA
, app_data_length
, app_data
, NULL
);
2675 if (fd_cb
->app_data
!= NULL
) {
2676 FREE(fd_cb
->app_data
, M_TEMP
);
2678 fd_cb
->app_data
= app_data
;
2679 fd_cb
->app_data_length
= app_data_length
;
2681 FDLOG(LOG_ERR
, fd_cb
, "Failed to copy %u bytes of application data from the properties update packet", app_data_length
);
2682 FREE(app_data
, M_TEMP
);
2685 FDLOG(LOG_ERR
, fd_cb
, "Failed to allocate a buffer of size %u to hold the application data from the properties update", app_data_length
);
2689 socket_unlock(fd_cb
->so
, 0);
2695 flow_divert_handle_app_map_create(struct flow_divert_group
*group
, mbuf_t packet
, int offset
)
2697 size_t bytes_mem_size
;
2698 size_t child_maps_mem_size
;
2699 size_t nodes_mem_size
;
2700 size_t trie_memory_size
= 0;
2703 struct flow_divert_trie new_trie
;
2704 int insert_error
= 0;
2705 int prefix_count
= -1;
2706 int signing_id_count
= 0;
2707 size_t bytes_count
= 0;
2708 size_t nodes_count
= 0;
2709 size_t maps_count
= 0;
2711 lck_rw_lock_exclusive(&group
->lck
);
2713 /* Re-set the current trie */
2714 if (group
->signing_id_trie
.memory
!= NULL
) {
2715 FREE(group
->signing_id_trie
.memory
, M_TEMP
);
2717 memset(&group
->signing_id_trie
, 0, sizeof(group
->signing_id_trie
));
2718 group
->signing_id_trie
.root
= NULL_TRIE_IDX
;
2720 memset(&new_trie
, 0, sizeof(new_trie
));
2722 /* Get the number of shared prefixes in the new set of signing ID strings */
2723 error
= flow_divert_packet_get_tlv(packet
, offset
, FLOW_DIVERT_TLV_PREFIX_COUNT
, sizeof(prefix_count
), &prefix_count
, NULL
);
2725 if (prefix_count
< 0 || error
) {
2726 FDLOG(LOG_ERR
, &nil_pcb
, "Invalid prefix count (%d) or an error occurred while reading the prefix count: %d", prefix_count
, error
);
2727 lck_rw_done(&group
->lck
);
2731 /* Compute the number of signing IDs and the total amount of bytes needed to store them */
2732 for (cursor
= flow_divert_packet_find_tlv(packet
, offset
, FLOW_DIVERT_TLV_SIGNING_ID
, &error
, 0);
2734 cursor
= flow_divert_packet_find_tlv(packet
, cursor
, FLOW_DIVERT_TLV_SIGNING_ID
, &error
, 1)) {
2735 uint32_t sid_size
= 0;
2736 error
= flow_divert_packet_get_tlv(packet
, cursor
, FLOW_DIVERT_TLV_SIGNING_ID
, 0, NULL
, &sid_size
);
2737 if (error
|| sid_size
== 0) {
2738 FDLOG(LOG_ERR
, &nil_pcb
, "Failed to get the length of the signing identifier at offset %d: %d", cursor
, error
);
2739 signing_id_count
= 0;
2742 if (os_add_overflow(bytes_count
, sid_size
, &bytes_count
)) {
2743 FDLOG0(LOG_ERR
, &nil_pcb
, "Overflow while incrementing number of bytes");
2744 signing_id_count
= 0;
2750 if (signing_id_count
== 0) {
2751 lck_rw_done(&group
->lck
);
2752 FDLOG0(LOG_NOTICE
, &nil_pcb
, "No signing identifiers");
2756 if (os_add3_overflow(prefix_count
, signing_id_count
, 1, &nodes_count
)) { /* + 1 for the root node */
2757 lck_rw_done(&group
->lck
);
2758 FDLOG0(LOG_ERR
, &nil_pcb
, "Overflow while computing the number of nodes");
2762 if (os_add_overflow(prefix_count
, 1, &maps_count
)) { /* + 1 for the root node */
2763 lck_rw_done(&group
->lck
);
2764 FDLOG0(LOG_ERR
, &nil_pcb
, "Overflow while computing the number of maps");
2768 if (bytes_count
> UINT16_MAX
|| nodes_count
> UINT16_MAX
|| maps_count
> UINT16_MAX
) {
2769 lck_rw_done(&group
->lck
);
2770 FDLOG(LOG_NOTICE
, &nil_pcb
, "Invalid bytes count (%lu), nodes count (%lu) or maps count (%lu)", bytes_count
, nodes_count
, maps_count
);
2774 FDLOG(LOG_INFO
, &nil_pcb
, "Nodes count = %lu, child maps count = %lu, bytes_count = %lu",
2775 nodes_count
, maps_count
, bytes_count
);
2777 if (os_mul_overflow(sizeof(*new_trie
.nodes
), (size_t)nodes_count
, &nodes_mem_size
) ||
2778 os_mul3_overflow(sizeof(*new_trie
.child_maps
), CHILD_MAP_SIZE
, (size_t)maps_count
, &child_maps_mem_size
) ||
2779 os_mul_overflow(sizeof(*new_trie
.bytes
), (size_t)bytes_count
, &bytes_mem_size
) ||
2780 os_add3_overflow(nodes_mem_size
, child_maps_mem_size
, bytes_mem_size
, &trie_memory_size
)) {
2781 FDLOG0(LOG_ERR
, &nil_pcb
, "Overflow while computing trie memory sizes");
2782 lck_rw_done(&group
->lck
);
2786 if (trie_memory_size
> FLOW_DIVERT_MAX_TRIE_MEMORY
) {
2787 FDLOG(LOG_ERR
, &nil_pcb
, "Trie memory size (%lu) is too big (maximum is %u)", trie_memory_size
, FLOW_DIVERT_MAX_TRIE_MEMORY
);
2788 lck_rw_done(&group
->lck
);
2792 MALLOC(new_trie
.memory
, void *, trie_memory_size
, M_TEMP
, M_WAITOK
);
2793 if (new_trie
.memory
== NULL
) {
2794 FDLOG(LOG_ERR
, &nil_pcb
, "Failed to allocate %lu bytes of memory for the signing ID trie",
2795 nodes_mem_size
+ child_maps_mem_size
+ bytes_mem_size
);
2796 lck_rw_done(&group
->lck
);
2800 new_trie
.bytes_count
= (uint16_t)bytes_count
;
2801 new_trie
.nodes_count
= (uint16_t)nodes_count
;
2802 new_trie
.child_maps_count
= (uint16_t)maps_count
;
2804 /* Initialize the free lists */
2805 new_trie
.nodes
= (struct flow_divert_trie_node
*)new_trie
.memory
;
2806 new_trie
.nodes_free_next
= 0;
2807 memset(new_trie
.nodes
, 0, nodes_mem_size
);
2809 new_trie
.child_maps
= (uint16_t *)(void *)((uint8_t *)new_trie
.memory
+ nodes_mem_size
);
2810 new_trie
.child_maps_free_next
= 0;
2811 memset(new_trie
.child_maps
, 0xff, child_maps_mem_size
);
2813 new_trie
.bytes
= (uint8_t *)(void *)((uint8_t *)new_trie
.memory
+ nodes_mem_size
+ child_maps_mem_size
);
2814 new_trie
.bytes_free_next
= 0;
2815 memset(new_trie
.bytes
, 0, bytes_mem_size
);
2817 /* The root is an empty node */
2818 new_trie
.root
= trie_node_alloc(&new_trie
);
2820 /* Add each signing ID to the trie */
2821 for (cursor
= flow_divert_packet_find_tlv(packet
, offset
, FLOW_DIVERT_TLV_SIGNING_ID
, &error
, 0);
2823 cursor
= flow_divert_packet_find_tlv(packet
, cursor
, FLOW_DIVERT_TLV_SIGNING_ID
, &error
, 1)) {
2824 uint32_t sid_size
= 0;
2825 error
= flow_divert_packet_get_tlv(packet
, cursor
, FLOW_DIVERT_TLV_SIGNING_ID
, 0, NULL
, &sid_size
);
2826 if (error
|| sid_size
== 0) {
2827 FDLOG(LOG_ERR
, &nil_pcb
, "Failed to get the length of the signing identifier at offset %d while building: %d", cursor
, error
);
2828 insert_error
= EINVAL
;
2831 if (sid_size
<= UINT16_MAX
&& new_trie
.bytes_free_next
+ (uint16_t)sid_size
<= new_trie
.bytes_count
) {
2832 uint16_t new_node_idx
;
2833 error
= flow_divert_packet_get_tlv(packet
, cursor
, FLOW_DIVERT_TLV_SIGNING_ID
, sid_size
, &TRIE_BYTE(&new_trie
, new_trie
.bytes_free_next
), NULL
);
2835 FDLOG(LOG_ERR
, &nil_pcb
, "Failed to read the signing identifier at offset %d: %d", cursor
, error
);
2836 insert_error
= EINVAL
;
2839 new_node_idx
= flow_divert_trie_insert(&new_trie
, new_trie
.bytes_free_next
, sid_size
);
2840 if (new_node_idx
== NULL_TRIE_IDX
) {
2841 insert_error
= EINVAL
;
2845 FDLOG0(LOG_ERR
, &nil_pcb
, "No place to put signing ID for insertion");
2846 insert_error
= ENOBUFS
;
2851 if (!insert_error
) {
2852 group
->signing_id_trie
= new_trie
;
2854 FREE(new_trie
.memory
, M_TEMP
);
2857 lck_rw_done(&group
->lck
);
2861 flow_divert_input(mbuf_t packet
, struct flow_divert_group
*group
)
2863 struct flow_divert_packet_header hdr
;
2865 struct flow_divert_pcb
*fd_cb
;
2867 if (mbuf_pkthdr_len(packet
) < sizeof(hdr
)) {
2868 FDLOG(LOG_ERR
, &nil_pcb
, "got a bad packet, length (%lu) < sizeof hdr (%lu)", mbuf_pkthdr_len(packet
), sizeof(hdr
));
2873 if (mbuf_pkthdr_len(packet
) > FD_CTL_RCVBUFF_SIZE
) {
2874 FDLOG(LOG_ERR
, &nil_pcb
, "got a bad packet, length (%lu) > %d", mbuf_pkthdr_len(packet
), FD_CTL_RCVBUFF_SIZE
);
2879 error
= mbuf_copydata(packet
, 0, sizeof(hdr
), &hdr
);
2881 FDLOG(LOG_ERR
, &nil_pcb
, "mbuf_copydata failed for the header: %d", error
);
2886 hdr
.conn_id
= ntohl(hdr
.conn_id
);
2888 if (hdr
.conn_id
== 0) {
2889 switch (hdr
.packet_type
) {
2890 case FLOW_DIVERT_PKT_GROUP_INIT
:
2891 flow_divert_handle_group_init(group
, packet
, sizeof(hdr
));
2893 case FLOW_DIVERT_PKT_APP_MAP_CREATE
:
2894 flow_divert_handle_app_map_create(group
, packet
, sizeof(hdr
));
2897 FDLOG(LOG_WARNING
, &nil_pcb
, "got an unknown message type: %d", hdr
.packet_type
);
2903 fd_cb
= flow_divert_pcb_lookup(hdr
.conn_id
, group
); /* This retains the PCB */
2904 if (fd_cb
== NULL
) {
2905 if (hdr
.packet_type
!= FLOW_DIVERT_PKT_CLOSE
&& hdr
.packet_type
!= FLOW_DIVERT_PKT_READ_NOTIFY
) {
2906 FDLOG(LOG_NOTICE
, &nil_pcb
, "got a %s message from group %d for an unknown pcb: %u", flow_divert_packet_type2str(hdr
.packet_type
), group
->ctl_unit
, hdr
.conn_id
);
2911 switch (hdr
.packet_type
) {
2912 case FLOW_DIVERT_PKT_CONNECT_RESULT
:
2913 flow_divert_handle_connect_result(fd_cb
, packet
, sizeof(hdr
));
2915 case FLOW_DIVERT_PKT_CLOSE
:
2916 flow_divert_handle_close(fd_cb
, packet
, sizeof(hdr
));
2918 case FLOW_DIVERT_PKT_DATA
:
2919 error
= flow_divert_handle_data(fd_cb
, packet
, sizeof(hdr
));
2921 case FLOW_DIVERT_PKT_READ_NOTIFY
:
2922 flow_divert_handle_read_notification(fd_cb
, packet
, sizeof(hdr
));
2924 case FLOW_DIVERT_PKT_PROPERTIES_UPDATE
:
2925 flow_divert_handle_properties_update(fd_cb
, packet
, sizeof(hdr
));
2928 FDLOG(LOG_WARNING
, fd_cb
, "got an unknown message type: %d", hdr
.packet_type
);
2940 flow_divert_close_all(struct flow_divert_group
*group
)
2942 struct flow_divert_pcb
*fd_cb
;
2943 SLIST_HEAD(, flow_divert_pcb
) tmp_list
;
2945 SLIST_INIT(&tmp_list
);
2947 lck_rw_lock_exclusive(&group
->lck
);
2949 MBUFQ_DRAIN(&group
->send_queue
);
2951 RB_FOREACH(fd_cb
, fd_pcb_tree
, &group
->pcb_tree
) {
2953 SLIST_INSERT_HEAD(&tmp_list
, fd_cb
, tmp_list_entry
);
2956 lck_rw_done(&group
->lck
);
2958 while (!SLIST_EMPTY(&tmp_list
)) {
2959 fd_cb
= SLIST_FIRST(&tmp_list
);
2961 SLIST_REMOVE_HEAD(&tmp_list
, tmp_list_entry
);
2962 if (fd_cb
->so
!= NULL
) {
2963 socket_lock(fd_cb
->so
, 0);
2964 flow_divert_pcb_remove(fd_cb
);
2965 flow_divert_update_closed_state(fd_cb
, SHUT_RDWR
, TRUE
);
2966 fd_cb
->so
->so_error
= ECONNABORTED
;
2967 flow_divert_disconnect_socket(fd_cb
->so
);
2968 socket_unlock(fd_cb
->so
, 0);
2976 flow_divert_detach(struct socket
*so
)
2978 struct flow_divert_pcb
*fd_cb
= so
->so_fd_pcb
;
2980 VERIFY((so
->so_flags
& SOF_FLOW_DIVERT
) && so
->so_fd_pcb
!= NULL
);
2982 so
->so_flags
&= ~SOF_FLOW_DIVERT
;
2983 so
->so_fd_pcb
= NULL
;
2985 FDLOG(LOG_INFO
, fd_cb
, "Detaching, ref count = %d", fd_cb
->ref_count
);
2987 if (fd_cb
->group
!= NULL
) {
2988 /* Last-ditch effort to send any buffered data */
2989 flow_divert_send_buffered_data(fd_cb
, TRUE
);
2991 flow_divert_update_closed_state(fd_cb
, SHUT_RDWR
, FALSE
);
2992 flow_divert_send_close_if_needed(fd_cb
);
2993 /* Remove from the group */
2994 flow_divert_pcb_remove(fd_cb
);
2997 socket_unlock(so
, 0);
3003 FDRELEASE(fd_cb
); /* Release the socket's reference */
3007 flow_divert_close(struct socket
*so
)
3009 struct flow_divert_pcb
*fd_cb
= so
->so_fd_pcb
;
3011 VERIFY((so
->so_flags
& SOF_FLOW_DIVERT
) && so
->so_fd_pcb
!= NULL
);
3013 FDLOG0(LOG_INFO
, fd_cb
, "Closing");
3015 if (SOCK_TYPE(so
) == SOCK_STREAM
) {
3016 soisdisconnecting(so
);
3017 sbflush(&so
->so_rcv
);
3020 flow_divert_send_buffered_data(fd_cb
, TRUE
);
3021 flow_divert_update_closed_state(fd_cb
, SHUT_RDWR
, FALSE
);
3022 flow_divert_send_close_if_needed(fd_cb
);
3024 /* Remove from the group */
3025 flow_divert_pcb_remove(fd_cb
);
3031 flow_divert_disconnectx(struct socket
*so
, sae_associd_t aid
,
3032 sae_connid_t cid __unused
)
3034 if (aid
!= SAE_ASSOCID_ANY
&& aid
!= SAE_ASSOCID_ALL
) {
3038 return flow_divert_close(so
);
3042 flow_divert_shutdown(struct socket
*so
)
3044 struct flow_divert_pcb
*fd_cb
= so
->so_fd_pcb
;
3046 VERIFY((so
->so_flags
& SOF_FLOW_DIVERT
) && so
->so_fd_pcb
!= NULL
);
3048 FDLOG0(LOG_INFO
, fd_cb
, "Can't send more");
3052 flow_divert_update_closed_state(fd_cb
, SHUT_WR
, FALSE
);
3053 flow_divert_send_close_if_needed(fd_cb
);
3059 flow_divert_rcvd(struct socket
*so
, int flags __unused
)
3061 struct flow_divert_pcb
*fd_cb
= so
->so_fd_pcb
;
3062 int space
= sbspace(&so
->so_rcv
);
3064 VERIFY((so
->so_flags
& SOF_FLOW_DIVERT
) && so
->so_fd_pcb
!= NULL
);
3066 FDLOG(LOG_DEBUG
, fd_cb
, "app read bytes, space = %d", space
);
3067 if ((fd_cb
->flags
& FLOW_DIVERT_NOTIFY_ON_RECEIVED
) &&
3069 flow_divert_send_read_notification(fd_cb
) == 0) {
3070 FDLOG0(LOG_INFO
, fd_cb
, "Sent a read notification");
3071 fd_cb
->flags
&= ~FLOW_DIVERT_NOTIFY_ON_RECEIVED
;
3078 flow_divert_append_target_endpoint_tlv(mbuf_t connect_packet
, struct sockaddr
*toaddr
)
3083 if (!flow_divert_is_sockaddr_valid(toaddr
)) {
3084 FDLOG(LOG_ERR
, &nil_pcb
, "Invalid target address, family = %u, length = %u", toaddr
->sa_family
, toaddr
->sa_len
);
3089 error
= flow_divert_packet_append_tlv(connect_packet
, FLOW_DIVERT_TLV_TARGET_ADDRESS
, toaddr
->sa_len
, toaddr
);
3094 if (toaddr
->sa_family
== AF_INET
) {
3095 port
= ntohs((satosin(toaddr
))->sin_port
);
3097 port
= ntohs((satosin6(toaddr
))->sin6_port
);
3100 error
= flow_divert_packet_append_tlv(connect_packet
, FLOW_DIVERT_TLV_TARGET_PORT
, sizeof(port
), &port
);
3110 flow_divert_get_buffered_target_address(mbuf_t buffer
)
3112 if (buffer
!= NULL
&& buffer
->m_type
== MT_SONAME
) {
3113 struct sockaddr
*toaddr
= mtod(buffer
, struct sockaddr
*);
3114 if (toaddr
!= NULL
&& flow_divert_is_sockaddr_valid(toaddr
)) {
3122 flow_divert_is_sockaddr_valid(struct sockaddr
*addr
)
3124 switch (addr
->sa_family
) {
3126 if (addr
->sa_len
< sizeof(struct sockaddr_in
)) {
3131 if (addr
->sa_len
< sizeof(struct sockaddr_in6
)) {
3142 flow_divert_dup_addr(sa_family_t family
, struct sockaddr
*addr
,
3143 struct sockaddr
**dup
)
3146 struct sockaddr
*result
;
3147 struct sockaddr_storage ss
;
3152 memset(&ss
, 0, sizeof(ss
));
3153 ss
.ss_family
= family
;
3154 if (ss
.ss_family
== AF_INET
) {
3155 ss
.ss_len
= sizeof(struct sockaddr_in
);
3156 } else if (ss
.ss_family
== AF_INET6
) {
3157 ss
.ss_len
= sizeof(struct sockaddr_in6
);
3161 result
= (struct sockaddr
*)&ss
;
3165 *dup
= dup_sockaddr(result
, 1);
3175 flow_divert_disconnect_socket(struct socket
*so
)
3177 soisdisconnected(so
);
3178 if (SOCK_TYPE(so
) == SOCK_DGRAM
) {
3179 struct inpcb
*inp
= NULL
;
3181 inp
= sotoinpcb(so
);
3183 if (SOCK_CHECK_DOM(so
, PF_INET6
)) {
3193 flow_divert_ctloutput(struct socket
*so
, struct sockopt
*sopt
)
3195 struct flow_divert_pcb
*fd_cb
= so
->so_fd_pcb
;
3197 VERIFY((so
->so_flags
& SOF_FLOW_DIVERT
) && so
->so_fd_pcb
!= NULL
);
3199 if (sopt
->sopt_name
== SO_TRAFFIC_CLASS
) {
3200 if (sopt
->sopt_dir
== SOPT_SET
&& fd_cb
->flags
& FLOW_DIVERT_CONNECT_STARTED
) {
3201 flow_divert_send_traffic_class_update(fd_cb
, so
->so_traffic_class
);
3205 if (SOCK_DOM(so
) == PF_INET
) {
3206 return g_tcp_protosw
->pr_ctloutput(so
, sopt
);
3207 } else if (SOCK_DOM(so
) == PF_INET6
) {
3208 return g_tcp6_protosw
->pr_ctloutput(so
, sopt
);
3214 flow_divert_connect_out_internal(struct socket
*so
, struct sockaddr
*to
, proc_t p
, bool implicit
)
3216 struct flow_divert_pcb
*fd_cb
= so
->so_fd_pcb
;
3218 struct inpcb
*inp
= sotoinpcb(so
);
3219 struct sockaddr_in
*sinp
;
3220 mbuf_t connect_packet
= NULL
;
3223 VERIFY((so
->so_flags
& SOF_FLOW_DIVERT
) && so
->so_fd_pcb
!= NULL
);
3225 if (fd_cb
->group
== NULL
) {
3226 error
= ENETUNREACH
;
3233 } else if (inp
->inp_state
== INPCB_STATE_DEAD
) {
3235 error
= so
->so_error
;
3243 if (fd_cb
->flags
& FLOW_DIVERT_CONNECT_STARTED
) {
3248 FDLOG0(LOG_INFO
, fd_cb
, "Connecting");
3250 if (fd_cb
->connect_packet
== NULL
) {
3251 struct sockaddr_in sin
= {};
3252 struct ifnet
*ifp
= NULL
;
3255 FDLOG0(LOG_ERR
, fd_cb
, "No destination address available when creating connect packet");
3260 fd_cb
->original_remote_endpoint
= dup_sockaddr(to
, 0);
3261 if (fd_cb
->original_remote_endpoint
== NULL
) {
3262 FDLOG0(LOG_ERR
, fd_cb
, "Failed to dup the remote endpoint");
3266 fd_cb
->original_vflag
= inp
->inp_vflag
;
3267 fd_cb
->original_last_outifp
= inp
->inp_last_outifp
;
3268 fd_cb
->original_last_outifp6
= inp
->in6p_last_outifp
;
3270 sinp
= (struct sockaddr_in
*)(void *)to
;
3271 if (sinp
->sin_family
== AF_INET
&& IN_MULTICAST(ntohl(sinp
->sin_addr
.s_addr
))) {
3272 error
= EAFNOSUPPORT
;
3276 if (to
->sa_family
== AF_INET6
&& !(inp
->inp_flags
& IN6P_IPV6_V6ONLY
)) {
3277 struct sockaddr_in6 sin6
= {};
3278 sin6
.sin6_family
= AF_INET6
;
3279 sin6
.sin6_len
= sizeof(struct sockaddr_in6
);
3280 sin6
.sin6_port
= satosin6(to
)->sin6_port
;
3281 sin6
.sin6_addr
= satosin6(to
)->sin6_addr
;
3282 if (IN6_IS_ADDR_V4MAPPED(&(sin6
.sin6_addr
))) {
3283 in6_sin6_2_sin(&sin
, &sin6
);
3284 to
= (struct sockaddr
*)&sin
;
3288 if (to
->sa_family
== AF_INET6
) {
3289 inp
->inp_vflag
&= ~INP_IPV4
;
3290 inp
->inp_vflag
|= INP_IPV6
;
3291 fd_cb
->local_endpoint
.sin6
.sin6_len
= sizeof(struct sockaddr_in6
);
3292 fd_cb
->local_endpoint
.sin6
.sin6_family
= AF_INET6
;
3293 fd_cb
->local_endpoint
.sin6
.sin6_port
= inp
->inp_lport
;
3294 error
= in6_pcbladdr(inp
, to
, &(fd_cb
->local_endpoint
.sin6
.sin6_addr
), &ifp
);
3296 FDLOG(LOG_WARNING
, fd_cb
, "failed to get a local IPv6 address: %d", error
);
3300 inp
->in6p_last_outifp
= ifp
;
3303 } else if (to
->sa_family
== AF_INET
) {
3304 inp
->inp_vflag
|= INP_IPV4
;
3305 inp
->inp_vflag
&= ~INP_IPV6
;
3306 fd_cb
->local_endpoint
.sin
.sin_len
= sizeof(struct sockaddr_in
);
3307 fd_cb
->local_endpoint
.sin
.sin_family
= AF_INET
;
3308 fd_cb
->local_endpoint
.sin
.sin_port
= inp
->inp_lport
;
3309 error
= in_pcbladdr(inp
, to
, &(fd_cb
->local_endpoint
.sin
.sin_addr
), IFSCOPE_NONE
, &ifp
, 0);
3311 FDLOG(LOG_WARNING
, fd_cb
, "failed to get a local IPv4 address: %d", error
);
3315 inp
->inp_last_outifp
= ifp
;
3319 FDLOG(LOG_WARNING
, fd_cb
, "target address has an unsupported family: %d", to
->sa_family
);
3322 error
= flow_divert_check_no_cellular(fd_cb
) ||
3323 flow_divert_check_no_expensive(fd_cb
) ||
3324 flow_divert_check_no_constrained(fd_cb
);
3329 error
= flow_divert_create_connect_packet(fd_cb
, to
, so
, p
, &connect_packet
);
3334 if (!implicit
|| SOCK_TYPE(so
) == SOCK_STREAM
) {
3335 flow_divert_set_remote_endpoint(fd_cb
, to
);
3336 flow_divert_set_local_endpoint(fd_cb
, &(fd_cb
->local_endpoint
.sa
), false);
3340 fd_cb
->flags
|= FLOW_DIVERT_IMPLICIT_CONNECT
;
3343 if (so
->so_flags1
& SOF1_PRECONNECT_DATA
) {
3344 FDLOG0(LOG_INFO
, fd_cb
, "Delaying sending the connect packet until send or receive");
3348 fd_cb
->connect_packet
= connect_packet
;
3349 connect_packet
= NULL
;
3351 FDLOG0(LOG_INFO
, fd_cb
, "Sending saved connect packet");
3355 error
= flow_divert_send_connect_packet(fd_cb
);
3360 fd_cb
->flags
|= FLOW_DIVERT_CONNECT_STARTED
;
3363 if (SOCK_TYPE(so
) == SOCK_DGRAM
) {
3374 flow_divert_connect_out(struct socket
*so
, struct sockaddr
*to
, proc_t p
)
3376 return flow_divert_connect_out_internal(so
, to
, p
, false);
3380 flow_divert_connectx_out_common(struct socket
*so
, struct sockaddr
*dst
,
3381 struct proc
*p
, sae_connid_t
*pcid
, struct uio
*auio
, user_ssize_t
*bytes_written
)
3383 struct inpcb
*inp
= sotoinpcb(so
);
3390 VERIFY(dst
!= NULL
);
3392 error
= flow_divert_connect_out(so
, dst
, p
);
3398 /* if there is data, send it */
3400 user_ssize_t datalen
= 0;
3402 socket_unlock(so
, 0);
3404 VERIFY(bytes_written
!= NULL
);
3406 datalen
= uio_resid(auio
);
3407 error
= so
->so_proto
->pr_usrreqs
->pru_sosend(so
, NULL
, (uio_t
)auio
, NULL
, NULL
, 0);
3410 if (error
== 0 || error
== EWOULDBLOCK
) {
3411 *bytes_written
= datalen
- uio_resid(auio
);
3415 * sosend returns EWOULDBLOCK if it's a non-blocking
3416 * socket or a timeout occured (this allows to return
3417 * the amount of queued data through sendit()).
3419 * However, connectx() returns EINPROGRESS in case of a
3420 * blocking socket. So we change the return value here.
3422 if (error
== EWOULDBLOCK
) {
3423 error
= EINPROGRESS
;
3427 if (error
== 0 && pcid
!= NULL
) {
3428 *pcid
= 1; /* there is only 1 connection for a TCP */
3435 flow_divert_connectx_out(struct socket
*so
, struct sockaddr
*src __unused
,
3436 struct sockaddr
*dst
, struct proc
*p
, uint32_t ifscope __unused
,
3437 sae_associd_t aid __unused
, sae_connid_t
*pcid
, uint32_t flags __unused
, void *arg __unused
,
3438 uint32_t arglen __unused
, struct uio
*uio
, user_ssize_t
*bytes_written
)
3440 return flow_divert_connectx_out_common(so
, dst
, p
, pcid
, uio
, bytes_written
);
3444 flow_divert_connectx6_out(struct socket
*so
, struct sockaddr
*src __unused
,
3445 struct sockaddr
*dst
, struct proc
*p
, uint32_t ifscope __unused
,
3446 sae_associd_t aid __unused
, sae_connid_t
*pcid
, uint32_t flags __unused
, void *arg __unused
,
3447 uint32_t arglen __unused
, struct uio
*uio
, user_ssize_t
*bytes_written
)
3449 return flow_divert_connectx_out_common(so
, dst
, p
, pcid
, uio
, bytes_written
);
3453 flow_divert_data_out(struct socket
*so
, int flags
, mbuf_t data
, struct sockaddr
*to
, mbuf_t control
, struct proc
*p
)
3455 struct flow_divert_pcb
*fd_cb
= so
->so_fd_pcb
;
3459 struct m_tag
*cfil_tag
= NULL
;
3462 VERIFY((so
->so_flags
& SOF_FLOW_DIVERT
) && so
->so_fd_pcb
!= NULL
);
3464 inp
= sotoinpcb(so
);
3465 if (inp
== NULL
|| inp
->inp_state
== INPCB_STATE_DEAD
) {
3470 if (control
&& mbuf_len(control
) > 0) {
3475 if (flags
& MSG_OOB
) {
3477 goto done
; /* We don't support OOB data */
3482 * If the socket is subject to a UDP Content Filter and no remote address is passed in,
3483 * retrieve the CFIL saved remote address from the mbuf and use it.
3485 if (to
== NULL
&& so
->so_cfil_db
) {
3486 struct sockaddr
*cfil_faddr
= NULL
;
3487 cfil_tag
= cfil_dgram_get_socket_state(data
, NULL
, NULL
, &cfil_faddr
, NULL
);
3489 to
= (struct sockaddr
*)(void *)cfil_faddr
;
3491 FDLOG(LOG_INFO
, fd_cb
, "Using remote address from CFIL saved state: %p", to
);
3495 /* Implicit connect */
3496 if (!(fd_cb
->flags
& FLOW_DIVERT_CONNECT_STARTED
)) {
3497 FDLOG0(LOG_INFO
, fd_cb
, "implicit connect");
3499 error
= flow_divert_connect_out_internal(so
, to
, p
, true);
3504 if (so
->so_flags1
& SOF1_DATA_IDEMPOTENT
) {
3505 /* Open up the send window so that the data will get sent right away */
3506 fd_cb
->send_window
= (uint32_t)mbuf_pkthdr_len(data
);
3509 error
= flow_divert_check_no_cellular(fd_cb
) ||
3510 flow_divert_check_no_expensive(fd_cb
) ||
3511 flow_divert_check_no_constrained(fd_cb
);
3517 FDLOG(LOG_DEBUG
, fd_cb
, "app wrote %lu bytes", mbuf_pkthdr_len(data
));
3519 fd_cb
->bytes_written_by_app
+= mbuf_pkthdr_len(data
);
3520 error
= flow_divert_send_app_data(fd_cb
, data
, to
);
3528 if (flags
& PRUS_EOF
) {
3529 flow_divert_shutdown(so
);
3541 m_tag_free(cfil_tag
);
3549 flow_divert_preconnect(struct socket
*so
)
3552 struct flow_divert_pcb
*fd_cb
= so
->so_fd_pcb
;
3554 VERIFY((so
->so_flags
& SOF_FLOW_DIVERT
) && so
->so_fd_pcb
!= NULL
);
3556 if (!(fd_cb
->flags
& FLOW_DIVERT_CONNECT_STARTED
)) {
3557 FDLOG0(LOG_INFO
, fd_cb
, "Pre-connect read: sending saved connect packet");
3558 error
= flow_divert_send_connect_packet(so
->so_fd_pcb
);
3563 fd_cb
->flags
|= FLOW_DIVERT_CONNECT_STARTED
;
3566 soclearfastopen(so
);
3572 flow_divert_set_protosw(struct socket
*so
)
3574 if (SOCK_DOM(so
) == PF_INET
) {
3575 so
->so_proto
= &g_flow_divert_in_protosw
;
3577 so
->so_proto
= (struct protosw
*)&g_flow_divert_in6_protosw
;
3582 flow_divert_set_udp_protosw(struct socket
*so
)
3584 if (SOCK_DOM(so
) == PF_INET
) {
3585 so
->so_proto
= &g_flow_divert_in_udp_protosw
;
3587 so
->so_proto
= (struct protosw
*)&g_flow_divert_in6_udp_protosw
;
3592 flow_divert_implicit_data_out(struct socket
*so
, int flags
, mbuf_t data
, struct sockaddr
*to
, mbuf_t control
, struct proc
*p
)
3594 struct flow_divert_pcb
*fd_cb
= so
->so_fd_pcb
;
3598 inp
= sotoinpcb(so
);
3603 if (fd_cb
== NULL
) {
3604 error
= flow_divert_pcb_init(so
);
3605 fd_cb
= so
->so_fd_pcb
;
3606 if (error
!= 0 || fd_cb
== NULL
) {
3610 return flow_divert_data_out(so
, flags
, data
, to
, control
, p
);
3624 flow_divert_pcb_init_internal(struct socket
*so
, uint32_t ctl_unit
, uint32_t aggregate_unit
)
3627 struct flow_divert_pcb
*fd_cb
;
3628 uint32_t agg_unit
= aggregate_unit
;
3629 uint32_t group_unit
= flow_divert_derive_kernel_control_unit(ctl_unit
, &agg_unit
);
3631 if (group_unit
== 0) {
3635 if (so
->so_flags
& SOF_FLOW_DIVERT
) {
3639 fd_cb
= flow_divert_pcb_create(so
);
3640 if (fd_cb
!= NULL
) {
3641 so
->so_fd_pcb
= fd_cb
;
3642 so
->so_flags
|= SOF_FLOW_DIVERT
;
3643 fd_cb
->control_group_unit
= group_unit
;
3644 fd_cb
->policy_control_unit
= ctl_unit
;
3645 fd_cb
->aggregate_unit
= agg_unit
;
3647 error
= flow_divert_pcb_insert(fd_cb
, group_unit
);
3649 FDLOG(LOG_ERR
, fd_cb
, "pcb insert failed: %d", error
);
3650 so
->so_fd_pcb
= NULL
;
3651 so
->so_flags
&= ~SOF_FLOW_DIVERT
;
3654 if (SOCK_TYPE(so
) == SOCK_STREAM
) {
3655 flow_divert_set_protosw(so
);
3656 } else if (SOCK_TYPE(so
) == SOCK_DGRAM
) {
3657 flow_divert_set_udp_protosw(so
);
3660 FDLOG0(LOG_INFO
, fd_cb
, "Created");
3670 flow_divert_pcb_init(struct socket
*so
)
3672 struct inpcb
*inp
= sotoinpcb(so
);
3673 uint32_t aggregate_units
= 0;
3674 uint32_t ctl_unit
= necp_socket_get_flow_divert_control_unit(inp
, &aggregate_units
);
3675 return flow_divert_pcb_init_internal(so
, ctl_unit
, aggregate_units
);
3679 flow_divert_token_set(struct socket
*so
, struct sockopt
*sopt
)
3681 uint32_t ctl_unit
= 0;
3682 uint32_t key_unit
= 0;
3683 uint32_t aggregate_unit
= 0;
3686 mbuf_t token
= NULL
;
3688 if (so
->so_flags
& SOF_FLOW_DIVERT
) {
3693 if (g_init_result
) {
3694 FDLOG(LOG_ERR
, &nil_pcb
, "flow_divert_init failed (%d), cannot use flow divert", g_init_result
);
3695 error
= ENOPROTOOPT
;
3699 if ((SOCK_TYPE(so
) != SOCK_STREAM
&& SOCK_TYPE(so
) != SOCK_DGRAM
) ||
3700 (SOCK_PROTO(so
) != IPPROTO_TCP
&& SOCK_PROTO(so
) != IPPROTO_UDP
) ||
3701 (SOCK_DOM(so
) != PF_INET
&& SOCK_DOM(so
) != PF_INET6
)) {
3705 if (SOCK_TYPE(so
) == SOCK_STREAM
&& SOCK_PROTO(so
) == IPPROTO_TCP
) {
3706 struct tcpcb
*tp
= sototcpcb(so
);
3707 if (tp
== NULL
|| tp
->t_state
!= TCPS_CLOSED
) {
3714 error
= soopt_getm(sopt
, &token
);
3720 error
= soopt_mcopyin(sopt
, token
);
3726 error
= flow_divert_packet_get_tlv(token
, 0, FLOW_DIVERT_TLV_KEY_UNIT
, sizeof(key_unit
), (void *)&key_unit
, NULL
);
3728 key_unit
= ntohl(key_unit
);
3729 if (key_unit
>= GROUP_COUNT_MAX
) {
3732 } else if (error
!= ENOENT
) {
3733 FDLOG(LOG_ERR
, &nil_pcb
, "Failed to get the key unit from the token: %d", error
);
3739 error
= flow_divert_packet_get_tlv(token
, 0, FLOW_DIVERT_TLV_CTL_UNIT
, sizeof(ctl_unit
), (void *)&ctl_unit
, NULL
);
3741 FDLOG(LOG_ERR
, &nil_pcb
, "Failed to get the control socket unit from the token: %d", error
);
3745 error
= flow_divert_packet_get_tlv(token
, 0, FLOW_DIVERT_TLV_AGGREGATE_UNIT
, sizeof(aggregate_unit
), (void *)&aggregate_unit
, NULL
);
3746 if (error
&& error
!= ENOENT
) {
3747 FDLOG(LOG_ERR
, &nil_pcb
, "Failed to get the aggregate unit from the token: %d", error
);
3751 /* A valid kernel control unit is required */
3752 ctl_unit
= ntohl(ctl_unit
);
3753 aggregate_unit
= ntohl(aggregate_unit
);
3755 if (ctl_unit
> 0 && ctl_unit
< GROUP_COUNT_MAX
) {
3756 socket_unlock(so
, 0);
3757 hmac_error
= flow_divert_packet_verify_hmac(token
, (key_unit
!= 0 ? key_unit
: ctl_unit
));
3760 if (hmac_error
&& hmac_error
!= ENOENT
) {
3761 FDLOG(LOG_ERR
, &nil_pcb
, "HMAC verfication failed: %d", hmac_error
);
3767 error
= flow_divert_pcb_init_internal(so
, ctl_unit
, aggregate_unit
);
3769 struct flow_divert_pcb
*fd_cb
= so
->so_fd_pcb
;
3770 int log_level
= LOG_NOTICE
;
3772 error
= flow_divert_packet_get_tlv(token
, 0, FLOW_DIVERT_TLV_LOG_LEVEL
, sizeof(log_level
), &log_level
, NULL
);
3774 fd_cb
->log_level
= (uint8_t)log_level
;
3778 fd_cb
->connect_token
= token
;
3782 if (hmac_error
== 0) {
3783 struct flow_divert_pcb
*fd_cb
= so
->so_fd_pcb
;
3784 if (fd_cb
!= NULL
) {
3785 fd_cb
->flags
|= FLOW_DIVERT_HAS_HMAC
;
3790 if (token
!= NULL
) {
3798 flow_divert_token_get(struct socket
*so
, struct sockopt
*sopt
)
3802 uint8_t hmac
[SHA_DIGEST_LENGTH
];
3803 struct flow_divert_pcb
*fd_cb
= so
->so_fd_pcb
;
3804 mbuf_t token
= NULL
;
3805 struct flow_divert_group
*control_group
= NULL
;
3807 if (!(so
->so_flags
& SOF_FLOW_DIVERT
)) {
3812 VERIFY((so
->so_flags
& SOF_FLOW_DIVERT
) && so
->so_fd_pcb
!= NULL
);
3814 if (fd_cb
->group
== NULL
) {
3819 error
= mbuf_gethdr(MBUF_DONTWAIT
, MBUF_TYPE_HEADER
, &token
);
3821 FDLOG(LOG_ERR
, fd_cb
, "failed to allocate the header mbuf: %d", error
);
3825 ctl_unit
= htonl(fd_cb
->group
->ctl_unit
);
3827 error
= flow_divert_packet_append_tlv(token
, FLOW_DIVERT_TLV_CTL_UNIT
, sizeof(ctl_unit
), &ctl_unit
);
3832 error
= flow_divert_packet_append_tlv(token
, FLOW_DIVERT_TLV_FLOW_ID
, sizeof(fd_cb
->hash
), &fd_cb
->hash
);
3837 if (fd_cb
->app_data
!= NULL
) {
3838 error
= flow_divert_packet_append_tlv(token
, FLOW_DIVERT_TLV_APP_DATA
, (uint32_t)fd_cb
->app_data_length
, fd_cb
->app_data
);
3844 socket_unlock(so
, 0);
3845 lck_rw_lock_shared(&g_flow_divert_group_lck
);
3847 if (g_flow_divert_groups
!= NULL
&& g_active_group_count
> 0 &&
3848 fd_cb
->control_group_unit
> 0 && fd_cb
->control_group_unit
< GROUP_COUNT_MAX
) {
3849 control_group
= g_flow_divert_groups
[fd_cb
->control_group_unit
];
3852 if (control_group
!= NULL
) {
3853 lck_rw_lock_shared(&control_group
->lck
);
3854 ctl_unit
= htonl(control_group
->ctl_unit
);
3855 error
= flow_divert_packet_append_tlv(token
, FLOW_DIVERT_TLV_KEY_UNIT
, sizeof(ctl_unit
), &ctl_unit
);
3857 error
= flow_divert_packet_compute_hmac(token
, control_group
, hmac
);
3859 lck_rw_done(&control_group
->lck
);
3861 error
= ENOPROTOOPT
;
3864 lck_rw_done(&g_flow_divert_group_lck
);
3871 error
= flow_divert_packet_append_tlv(token
, FLOW_DIVERT_TLV_HMAC
, sizeof(hmac
), hmac
);
3876 if (sopt
->sopt_val
== USER_ADDR_NULL
) {
3877 /* If the caller passed NULL to getsockopt, just set the size of the token and return */
3878 sopt
->sopt_valsize
= mbuf_pkthdr_len(token
);
3882 error
= soopt_mcopyout(sopt
, token
);
3884 token
= NULL
; /* For some reason, soopt_mcopyout() frees the mbuf if it fails */
3889 if (token
!= NULL
) {
3897 flow_divert_kctl_connect(kern_ctl_ref kctlref __unused
, struct sockaddr_ctl
*sac
, void **unitinfo
)
3899 struct flow_divert_group
*new_group
= NULL
;
3902 if (sac
->sc_unit
>= GROUP_COUNT_MAX
) {
3909 new_group
= zalloc_flags(flow_divert_group_zone
, Z_WAITOK
| Z_ZERO
);
3910 lck_rw_init(&new_group
->lck
, flow_divert_mtx_grp
, flow_divert_mtx_attr
);
3911 RB_INIT(&new_group
->pcb_tree
);
3912 new_group
->ctl_unit
= sac
->sc_unit
;
3913 MBUFQ_INIT(&new_group
->send_queue
);
3914 new_group
->signing_id_trie
.root
= NULL_TRIE_IDX
;
3916 lck_rw_lock_exclusive(&g_flow_divert_group_lck
);
3918 if (g_flow_divert_groups
== NULL
) {
3919 MALLOC(g_flow_divert_groups
,
3920 struct flow_divert_group
**,
3921 GROUP_COUNT_MAX
* sizeof(struct flow_divert_group
*),
3926 if (g_flow_divert_groups
== NULL
) {
3928 } else if (g_flow_divert_groups
[sac
->sc_unit
] != NULL
) {
3931 g_flow_divert_groups
[sac
->sc_unit
] = new_group
;
3932 g_active_group_count
++;
3935 lck_rw_done(&g_flow_divert_group_lck
);
3939 *unitinfo
= new_group
;
3940 } else if (new_group
!= NULL
) {
3941 zfree(flow_divert_group_zone
, new_group
);
3947 flow_divert_kctl_disconnect(kern_ctl_ref kctlref __unused
, uint32_t unit
, void *unitinfo
)
3949 struct flow_divert_group
*group
= NULL
;
3952 if (unit
>= GROUP_COUNT_MAX
) {
3956 if (unitinfo
== NULL
) {
3960 FDLOG(LOG_INFO
, &nil_pcb
, "disconnecting group %d", unit
);
3962 lck_rw_lock_exclusive(&g_flow_divert_group_lck
);
3964 if (g_flow_divert_groups
== NULL
|| g_active_group_count
== 0) {
3965 panic("flow divert group %u is disconnecting, but no groups are active (groups = %p, active count = %u", unit
,
3966 g_flow_divert_groups
, g_active_group_count
);
3969 group
= g_flow_divert_groups
[unit
];
3971 if (group
!= (struct flow_divert_group
*)unitinfo
) {
3972 panic("group with unit %d (%p) != unit info (%p)", unit
, group
, unitinfo
);
3975 g_flow_divert_groups
[unit
] = NULL
;
3976 g_active_group_count
--;
3978 if (g_active_group_count
== 0) {
3979 FREE(g_flow_divert_groups
, M_TEMP
);
3980 g_flow_divert_groups
= NULL
;
3983 lck_rw_done(&g_flow_divert_group_lck
);
3985 if (group
!= NULL
) {
3986 flow_divert_close_all(group
);
3988 lck_rw_lock_exclusive(&group
->lck
);
3990 if (group
->token_key
!= NULL
) {
3991 memset(group
->token_key
, 0, group
->token_key_size
);
3992 FREE(group
->token_key
, M_TEMP
);
3993 group
->token_key
= NULL
;
3994 group
->token_key_size
= 0;
3997 /* Re-set the current trie */
3998 if (group
->signing_id_trie
.memory
!= NULL
) {
3999 FREE(group
->signing_id_trie
.memory
, M_TEMP
);
4001 memset(&group
->signing_id_trie
, 0, sizeof(group
->signing_id_trie
));
4002 group
->signing_id_trie
.root
= NULL_TRIE_IDX
;
4004 lck_rw_done(&group
->lck
);
4006 zfree(flow_divert_group_zone
, group
);
4015 flow_divert_kctl_send(kern_ctl_ref kctlref __unused
, uint32_t unit __unused
, void *unitinfo
, mbuf_t m
, int flags __unused
)
4017 return flow_divert_input(m
, (struct flow_divert_group
*)unitinfo
);
4021 flow_divert_kctl_rcvd(kern_ctl_ref kctlref __unused
, uint32_t unit __unused
, void *unitinfo
, int flags __unused
)
4023 struct flow_divert_group
*group
= (struct flow_divert_group
*)unitinfo
;
4025 if (!OSTestAndClear(GROUP_BIT_CTL_ENQUEUE_BLOCKED
, &group
->atomic_bits
)) {
4026 struct flow_divert_pcb
*fd_cb
;
4027 SLIST_HEAD(, flow_divert_pcb
) tmp_list
;
4029 lck_rw_lock_shared(&g_flow_divert_group_lck
);
4030 lck_rw_lock_exclusive(&group
->lck
);
4032 while (!MBUFQ_EMPTY(&group
->send_queue
)) {
4034 FDLOG0(LOG_DEBUG
, &nil_pcb
, "trying ctl_enqueuembuf again");
4035 next_packet
= MBUFQ_FIRST(&group
->send_queue
);
4036 int error
= ctl_enqueuembuf(g_flow_divert_kctl_ref
, group
->ctl_unit
, next_packet
, CTL_DATA_EOR
);
4038 FDLOG(LOG_DEBUG
, &nil_pcb
, "ctl_enqueuembuf returned an error: %d", error
);
4039 OSTestAndSet(GROUP_BIT_CTL_ENQUEUE_BLOCKED
, &group
->atomic_bits
);
4040 lck_rw_done(&group
->lck
);
4041 lck_rw_done(&g_flow_divert_group_lck
);
4044 MBUFQ_DEQUEUE(&group
->send_queue
, next_packet
);
4047 SLIST_INIT(&tmp_list
);
4049 RB_FOREACH(fd_cb
, fd_pcb_tree
, &group
->pcb_tree
) {
4051 SLIST_INSERT_HEAD(&tmp_list
, fd_cb
, tmp_list_entry
);
4054 lck_rw_done(&group
->lck
);
4056 SLIST_FOREACH(fd_cb
, &tmp_list
, tmp_list_entry
) {
4058 if (fd_cb
->so
!= NULL
) {
4059 socket_lock(fd_cb
->so
, 0);
4060 if (fd_cb
->group
!= NULL
) {
4061 flow_divert_send_buffered_data(fd_cb
, FALSE
);
4063 socket_unlock(fd_cb
->so
, 0);
4069 lck_rw_done(&g_flow_divert_group_lck
);
4074 flow_divert_kctl_init(void)
4076 struct kern_ctl_reg ctl_reg
;
4079 memset(&ctl_reg
, 0, sizeof(ctl_reg
));
4081 strlcpy(ctl_reg
.ctl_name
, FLOW_DIVERT_CONTROL_NAME
, sizeof(ctl_reg
.ctl_name
));
4082 ctl_reg
.ctl_name
[sizeof(ctl_reg
.ctl_name
) - 1] = '\0';
4083 ctl_reg
.ctl_flags
= CTL_FLAG_PRIVILEGED
| CTL_FLAG_REG_EXTENDED
;
4084 ctl_reg
.ctl_sendsize
= FD_CTL_SENDBUFF_SIZE
;
4085 ctl_reg
.ctl_recvsize
= FD_CTL_RCVBUFF_SIZE
;
4087 ctl_reg
.ctl_connect
= flow_divert_kctl_connect
;
4088 ctl_reg
.ctl_disconnect
= flow_divert_kctl_disconnect
;
4089 ctl_reg
.ctl_send
= flow_divert_kctl_send
;
4090 ctl_reg
.ctl_rcvd
= flow_divert_kctl_rcvd
;
4092 result
= ctl_register(&ctl_reg
, &g_flow_divert_kctl_ref
);
4095 FDLOG(LOG_ERR
, &nil_pcb
, "flow_divert_kctl_init - ctl_register failed: %d\n", result
);
4103 flow_divert_init(void)
4105 memset(&nil_pcb
, 0, sizeof(nil_pcb
));
4106 nil_pcb
.log_level
= LOG_NOTICE
;
4108 g_tcp_protosw
= pffindproto(AF_INET
, IPPROTO_TCP
, SOCK_STREAM
);
4110 VERIFY(g_tcp_protosw
!= NULL
);
4112 memcpy(&g_flow_divert_in_protosw
, g_tcp_protosw
, sizeof(g_flow_divert_in_protosw
));
4113 memcpy(&g_flow_divert_in_usrreqs
, g_tcp_protosw
->pr_usrreqs
, sizeof(g_flow_divert_in_usrreqs
));
4115 g_flow_divert_in_usrreqs
.pru_connect
= flow_divert_connect_out
;
4116 g_flow_divert_in_usrreqs
.pru_connectx
= flow_divert_connectx_out
;
4117 g_flow_divert_in_usrreqs
.pru_disconnect
= flow_divert_close
;
4118 g_flow_divert_in_usrreqs
.pru_disconnectx
= flow_divert_disconnectx
;
4119 g_flow_divert_in_usrreqs
.pru_rcvd
= flow_divert_rcvd
;
4120 g_flow_divert_in_usrreqs
.pru_send
= flow_divert_data_out
;
4121 g_flow_divert_in_usrreqs
.pru_shutdown
= flow_divert_shutdown
;
4122 g_flow_divert_in_usrreqs
.pru_preconnect
= flow_divert_preconnect
;
4124 g_flow_divert_in_protosw
.pr_usrreqs
= &g_flow_divert_in_usrreqs
;
4125 g_flow_divert_in_protosw
.pr_ctloutput
= flow_divert_ctloutput
;
4128 * Socket filters shouldn't attach/detach to/from this protosw
4129 * since pr_protosw is to be used instead, which points to the
4130 * real protocol; if they do, it is a bug and we should panic.
4132 g_flow_divert_in_protosw
.pr_filter_head
.tqh_first
=
4133 (struct socket_filter
*)(uintptr_t)0xdeadbeefdeadbeef;
4134 g_flow_divert_in_protosw
.pr_filter_head
.tqh_last
=
4135 (struct socket_filter
**)(uintptr_t)0xdeadbeefdeadbeef;
4138 g_udp_protosw
= pffindproto(AF_INET
, IPPROTO_UDP
, SOCK_DGRAM
);
4139 VERIFY(g_udp_protosw
!= NULL
);
4141 memcpy(&g_flow_divert_in_udp_protosw
, g_udp_protosw
, sizeof(g_flow_divert_in_udp_protosw
));
4142 memcpy(&g_flow_divert_in_udp_usrreqs
, g_udp_protosw
->pr_usrreqs
, sizeof(g_flow_divert_in_udp_usrreqs
));
4144 g_flow_divert_in_udp_usrreqs
.pru_connect
= flow_divert_connect_out
;
4145 g_flow_divert_in_udp_usrreqs
.pru_connectx
= flow_divert_connectx_out
;
4146 g_flow_divert_in_udp_usrreqs
.pru_disconnect
= flow_divert_close
;
4147 g_flow_divert_in_udp_usrreqs
.pru_disconnectx
= flow_divert_disconnectx
;
4148 g_flow_divert_in_udp_usrreqs
.pru_rcvd
= flow_divert_rcvd
;
4149 g_flow_divert_in_udp_usrreqs
.pru_send
= flow_divert_data_out
;
4150 g_flow_divert_in_udp_usrreqs
.pru_shutdown
= flow_divert_shutdown
;
4151 g_flow_divert_in_udp_usrreqs
.pru_sosend_list
= pru_sosend_list_notsupp
;
4152 g_flow_divert_in_udp_usrreqs
.pru_soreceive_list
= pru_soreceive_list_notsupp
;
4153 g_flow_divert_in_udp_usrreqs
.pru_preconnect
= flow_divert_preconnect
;
4155 g_flow_divert_in_udp_protosw
.pr_usrreqs
= &g_flow_divert_in_usrreqs
;
4156 g_flow_divert_in_udp_protosw
.pr_ctloutput
= flow_divert_ctloutput
;
4159 * Socket filters shouldn't attach/detach to/from this protosw
4160 * since pr_protosw is to be used instead, which points to the
4161 * real protocol; if they do, it is a bug and we should panic.
4163 g_flow_divert_in_udp_protosw
.pr_filter_head
.tqh_first
=
4164 (struct socket_filter
*)(uintptr_t)0xdeadbeefdeadbeef;
4165 g_flow_divert_in_udp_protosw
.pr_filter_head
.tqh_last
=
4166 (struct socket_filter
**)(uintptr_t)0xdeadbeefdeadbeef;
4168 g_tcp6_protosw
= (struct ip6protosw
*)pffindproto(AF_INET6
, IPPROTO_TCP
, SOCK_STREAM
);
4170 VERIFY(g_tcp6_protosw
!= NULL
);
4172 memcpy(&g_flow_divert_in6_protosw
, g_tcp6_protosw
, sizeof(g_flow_divert_in6_protosw
));
4173 memcpy(&g_flow_divert_in6_usrreqs
, g_tcp6_protosw
->pr_usrreqs
, sizeof(g_flow_divert_in6_usrreqs
));
4175 g_flow_divert_in6_usrreqs
.pru_connect
= flow_divert_connect_out
;
4176 g_flow_divert_in6_usrreqs
.pru_connectx
= flow_divert_connectx6_out
;
4177 g_flow_divert_in6_usrreqs
.pru_disconnect
= flow_divert_close
;
4178 g_flow_divert_in6_usrreqs
.pru_disconnectx
= flow_divert_disconnectx
;
4179 g_flow_divert_in6_usrreqs
.pru_rcvd
= flow_divert_rcvd
;
4180 g_flow_divert_in6_usrreqs
.pru_send
= flow_divert_data_out
;
4181 g_flow_divert_in6_usrreqs
.pru_shutdown
= flow_divert_shutdown
;
4182 g_flow_divert_in6_usrreqs
.pru_preconnect
= flow_divert_preconnect
;
4184 g_flow_divert_in6_protosw
.pr_usrreqs
= &g_flow_divert_in6_usrreqs
;
4185 g_flow_divert_in6_protosw
.pr_ctloutput
= flow_divert_ctloutput
;
4187 * Socket filters shouldn't attach/detach to/from this protosw
4188 * since pr_protosw is to be used instead, which points to the
4189 * real protocol; if they do, it is a bug and we should panic.
4191 g_flow_divert_in6_protosw
.pr_filter_head
.tqh_first
=
4192 (struct socket_filter
*)(uintptr_t)0xdeadbeefdeadbeef;
4193 g_flow_divert_in6_protosw
.pr_filter_head
.tqh_last
=
4194 (struct socket_filter
**)(uintptr_t)0xdeadbeefdeadbeef;
4197 g_udp6_protosw
= (struct ip6protosw
*)pffindproto(AF_INET6
, IPPROTO_UDP
, SOCK_DGRAM
);
4199 VERIFY(g_udp6_protosw
!= NULL
);
4201 memcpy(&g_flow_divert_in6_udp_protosw
, g_udp6_protosw
, sizeof(g_flow_divert_in6_udp_protosw
));
4202 memcpy(&g_flow_divert_in6_udp_usrreqs
, g_udp6_protosw
->pr_usrreqs
, sizeof(g_flow_divert_in6_udp_usrreqs
));
4204 g_flow_divert_in6_udp_usrreqs
.pru_connect
= flow_divert_connect_out
;
4205 g_flow_divert_in6_udp_usrreqs
.pru_connectx
= flow_divert_connectx6_out
;
4206 g_flow_divert_in6_udp_usrreqs
.pru_disconnect
= flow_divert_close
;
4207 g_flow_divert_in6_udp_usrreqs
.pru_disconnectx
= flow_divert_disconnectx
;
4208 g_flow_divert_in6_udp_usrreqs
.pru_rcvd
= flow_divert_rcvd
;
4209 g_flow_divert_in6_udp_usrreqs
.pru_send
= flow_divert_data_out
;
4210 g_flow_divert_in6_udp_usrreqs
.pru_shutdown
= flow_divert_shutdown
;
4211 g_flow_divert_in6_udp_usrreqs
.pru_sosend_list
= pru_sosend_list_notsupp
;
4212 g_flow_divert_in6_udp_usrreqs
.pru_soreceive_list
= pru_soreceive_list_notsupp
;
4213 g_flow_divert_in6_udp_usrreqs
.pru_preconnect
= flow_divert_preconnect
;
4215 g_flow_divert_in6_udp_protosw
.pr_usrreqs
= &g_flow_divert_in6_udp_usrreqs
;
4216 g_flow_divert_in6_udp_protosw
.pr_ctloutput
= flow_divert_ctloutput
;
4218 * Socket filters shouldn't attach/detach to/from this protosw
4219 * since pr_protosw is to be used instead, which points to the
4220 * real protocol; if they do, it is a bug and we should panic.
4222 g_flow_divert_in6_udp_protosw
.pr_filter_head
.tqh_first
=
4223 (struct socket_filter
*)(uintptr_t)0xdeadbeefdeadbeef;
4224 g_flow_divert_in6_udp_protosw
.pr_filter_head
.tqh_last
=
4225 (struct socket_filter
**)(uintptr_t)0xdeadbeefdeadbeef;
4227 flow_divert_grp_attr
= lck_grp_attr_alloc_init();
4228 if (flow_divert_grp_attr
== NULL
) {
4229 FDLOG0(LOG_ERR
, &nil_pcb
, "lck_grp_attr_alloc_init failed");
4230 g_init_result
= ENOMEM
;
4234 flow_divert_mtx_grp
= lck_grp_alloc_init(FLOW_DIVERT_CONTROL_NAME
, flow_divert_grp_attr
);
4235 if (flow_divert_mtx_grp
== NULL
) {
4236 FDLOG0(LOG_ERR
, &nil_pcb
, "lck_grp_alloc_init failed");
4237 g_init_result
= ENOMEM
;
4241 flow_divert_mtx_attr
= lck_attr_alloc_init();
4242 if (flow_divert_mtx_attr
== NULL
) {
4243 FDLOG0(LOG_ERR
, &nil_pcb
, "lck_attr_alloc_init failed");
4244 g_init_result
= ENOMEM
;
4248 g_init_result
= flow_divert_kctl_init();
4249 if (g_init_result
) {
4253 lck_rw_init(&g_flow_divert_group_lck
, flow_divert_mtx_grp
, flow_divert_mtx_attr
);
4256 if (g_init_result
!= 0) {
4257 if (flow_divert_mtx_attr
!= NULL
) {
4258 lck_attr_free(flow_divert_mtx_attr
);
4259 flow_divert_mtx_attr
= NULL
;
4261 if (flow_divert_mtx_grp
!= NULL
) {
4262 lck_grp_free(flow_divert_mtx_grp
);
4263 flow_divert_mtx_grp
= NULL
;
4265 if (flow_divert_grp_attr
!= NULL
) {
4266 lck_grp_attr_free(flow_divert_grp_attr
);
4267 flow_divert_grp_attr
= NULL
;
4270 if (g_flow_divert_kctl_ref
!= NULL
) {
4271 ctl_deregister(g_flow_divert_kctl_ref
);
4272 g_flow_divert_kctl_ref
= NULL
;