]> git.saurik.com Git - apple/xnu.git/blob - bsd/netinet/flow_divert.c
1a405129f0bcc0cb701feb11c81583857e84813f
[apple/xnu.git] / bsd / netinet / flow_divert.c
1 /*
2 * Copyright (c) 2012-2017 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28
29 #include <string.h>
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>
36 #include <sys/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>
43 #include <sys/ubc.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>
55 #include <netinet/in.h>
56 #include <netinet/in_var.h>
57 #include <netinet/tcp.h>
58 #include <netinet/tcp_var.h>
59 #include <netinet/tcp_fsm.h>
60 #include <netinet/flow_divert.h>
61 #include <netinet/flow_divert_proto.h>
62 #if INET6
63 #include <netinet6/in6_pcb.h>
64 #include <netinet6/ip6protosw.h>
65 #endif /* INET6 */
66 #include <dev/random/randomdev.h>
67 #include <libkern/crypto/sha1.h>
68 #include <libkern/crypto/crypto_internal.h>
69 #include <os/log.h>
70 #include <corecrypto/cc.h>
71 #if CONTENT_FILTER
72 #include <net/content_filter.h>
73 #endif /* CONTENT_FILTER */
74
75 #define FLOW_DIVERT_CONNECT_STARTED 0x00000001
76 #define FLOW_DIVERT_READ_CLOSED 0x00000002
77 #define FLOW_DIVERT_WRITE_CLOSED 0x00000004
78 #define FLOW_DIVERT_TUNNEL_RD_CLOSED 0x00000008
79 #define FLOW_DIVERT_TUNNEL_WR_CLOSED 0x00000010
80 #define FLOW_DIVERT_TRANSFERRED 0x00000020
81 #define FLOW_DIVERT_HAS_HMAC 0x00000040
82
83 #define FDLOG(level, pcb, format, ...) \
84 os_log_with_type(OS_LOG_DEFAULT, flow_divert_syslog_type_to_oslog_type(level), "(%u): " format "\n", (pcb)->hash, __VA_ARGS__)
85
86 #define FDLOG0(level, pcb, msg) \
87 os_log_with_type(OS_LOG_DEFAULT, flow_divert_syslog_type_to_oslog_type(level), "(%u): " msg "\n", (pcb)->hash)
88
89 #define FDRETAIN(pcb) if ((pcb) != NULL) OSIncrementAtomic(&(pcb)->ref_count)
90 #define FDRELEASE(pcb) \
91 do { \
92 if ((pcb) != NULL && 1 == OSDecrementAtomic(&(pcb)->ref_count)) { \
93 flow_divert_pcb_destroy(pcb); \
94 } \
95 } while (0)
96
97 #define FDLOCK(pcb) lck_mtx_lock(&(pcb)->mtx)
98 #define FDUNLOCK(pcb) lck_mtx_unlock(&(pcb)->mtx)
99
100 #define FD_CTL_SENDBUFF_SIZE (128 * 1024)
101 #define FD_CTL_RCVBUFF_SIZE (128 * 1024)
102
103 #define GROUP_BIT_CTL_ENQUEUE_BLOCKED 0
104
105 #define GROUP_COUNT_MAX 32
106 #define FLOW_DIVERT_MAX_NAME_SIZE 4096
107 #define FLOW_DIVERT_MAX_KEY_SIZE 1024
108 #define FLOW_DIVERT_MAX_TRIE_MEMORY (1024 * 1024)
109
110 struct flow_divert_trie_node {
111 uint16_t start;
112 uint16_t length;
113 uint16_t child_map;
114 };
115
116 #define CHILD_MAP_SIZE 256
117 #define NULL_TRIE_IDX 0xffff
118 #define TRIE_NODE(t, i) ((t)->nodes[(i)])
119 #define TRIE_CHILD(t, i, b) (((t)->child_maps + (CHILD_MAP_SIZE * TRIE_NODE(t, i).child_map))[(b)])
120 #define TRIE_BYTE(t, i) ((t)->bytes[(i)])
121
122 static struct flow_divert_pcb nil_pcb;
123
124 decl_lck_rw_data(static, g_flow_divert_group_lck);
125 static struct flow_divert_group **g_flow_divert_groups = NULL;
126 static uint32_t g_active_group_count = 0;
127
128 static lck_grp_attr_t *flow_divert_grp_attr = NULL;
129 static lck_attr_t *flow_divert_mtx_attr = NULL;
130 static lck_grp_t *flow_divert_mtx_grp = NULL;
131 static errno_t g_init_result = 0;
132
133 static kern_ctl_ref g_flow_divert_kctl_ref = NULL;
134
135 static struct protosw g_flow_divert_in_protosw;
136 static struct pr_usrreqs g_flow_divert_in_usrreqs;
137 static struct protosw g_flow_divert_in_udp_protosw;
138 static struct pr_usrreqs g_flow_divert_in_udp_usrreqs;
139 #if INET6
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;
144 #endif /* INET6 */
145
146 static struct protosw *g_tcp_protosw = NULL;
147 static struct ip6protosw *g_tcp6_protosw = NULL;
148 static struct protosw *g_udp_protosw = NULL;
149 static struct ip6protosw *g_udp6_protosw = NULL;
150
151 static errno_t
152 flow_divert_dup_addr(sa_family_t family, struct sockaddr *addr, struct sockaddr **dup);
153
154 static errno_t
155 flow_divert_inp_to_sockaddr(const struct inpcb *inp, struct sockaddr **local_socket);
156
157 static boolean_t
158 flow_divert_is_sockaddr_valid(struct sockaddr *addr);
159
160 static int
161 flow_divert_append_target_endpoint_tlv(mbuf_t connect_packet, struct sockaddr *toaddr);
162
163 struct sockaddr *
164 flow_divert_get_buffered_target_address(mbuf_t buffer);
165
166 static boolean_t
167 flow_divert_has_pcb_local_address(const struct inpcb *inp);
168
169 static void
170 flow_divert_disconnect_socket(struct socket *so);
171
172 static inline uint8_t
173 flow_divert_syslog_type_to_oslog_type(int syslog_type)
174 {
175 switch (syslog_type) {
176 case LOG_ERR: return OS_LOG_TYPE_ERROR;
177 case LOG_INFO: return OS_LOG_TYPE_INFO;
178 case LOG_DEBUG: return OS_LOG_TYPE_DEBUG;
179 default: return OS_LOG_TYPE_DEFAULT;
180 }
181 }
182
183 static inline int
184 flow_divert_pcb_cmp(const struct flow_divert_pcb *pcb_a, const struct flow_divert_pcb *pcb_b)
185 {
186 return memcmp(&pcb_a->hash, &pcb_b->hash, sizeof(pcb_a->hash));
187 }
188
189 RB_PROTOTYPE(fd_pcb_tree, flow_divert_pcb, rb_link, flow_divert_pcb_cmp);
190 RB_GENERATE(fd_pcb_tree, flow_divert_pcb, rb_link, flow_divert_pcb_cmp);
191
192 static const char *
193 flow_divert_packet_type2str(uint8_t packet_type)
194 {
195 switch (packet_type) {
196 case FLOW_DIVERT_PKT_CONNECT:
197 return "connect";
198 case FLOW_DIVERT_PKT_CONNECT_RESULT:
199 return "connect result";
200 case FLOW_DIVERT_PKT_DATA:
201 return "data";
202 case FLOW_DIVERT_PKT_CLOSE:
203 return "close";
204 case FLOW_DIVERT_PKT_READ_NOTIFY:
205 return "read notification";
206 case FLOW_DIVERT_PKT_PROPERTIES_UPDATE:
207 return "properties update";
208 case FLOW_DIVERT_PKT_APP_MAP_CREATE:
209 return "app map create";
210 default:
211 return "unknown";
212 }
213 }
214
215 static struct flow_divert_pcb *
216 flow_divert_pcb_lookup(uint32_t hash, struct flow_divert_group *group)
217 {
218 struct flow_divert_pcb key_item;
219 struct flow_divert_pcb *fd_cb = NULL;
220
221 key_item.hash = hash;
222
223 lck_rw_lock_shared(&group->lck);
224 fd_cb = RB_FIND(fd_pcb_tree, &group->pcb_tree, &key_item);
225 FDRETAIN(fd_cb);
226 lck_rw_done(&group->lck);
227
228 return fd_cb;
229 }
230
231 static errno_t
232 flow_divert_pcb_insert(struct flow_divert_pcb *fd_cb, uint32_t ctl_unit)
233 {
234 errno_t error = 0;
235 struct flow_divert_pcb *exist = NULL;
236 struct flow_divert_group *group;
237 static uint32_t g_nextkey = 1;
238 static uint32_t g_hash_seed = 0;
239 int try_count = 0;
240
241 if (ctl_unit == 0 || ctl_unit >= GROUP_COUNT_MAX) {
242 return EINVAL;
243 }
244
245 socket_unlock(fd_cb->so, 0);
246 lck_rw_lock_shared(&g_flow_divert_group_lck);
247
248 if (g_flow_divert_groups == NULL || g_active_group_count == 0) {
249 FDLOG0(LOG_ERR, &nil_pcb, "No active groups, flow divert cannot be used for this socket");
250 error = ENETUNREACH;
251 goto done;
252 }
253
254 group = g_flow_divert_groups[ctl_unit];
255 if (group == NULL) {
256 FDLOG(LOG_ERR, &nil_pcb, "Group for control unit %u is NULL, flow divert cannot be used for this socket", ctl_unit);
257 error = ENETUNREACH;
258 goto done;
259 }
260
261 socket_lock(fd_cb->so, 0);
262
263 do {
264 uint32_t key[2];
265 uint32_t idx;
266
267 key[0] = g_nextkey++;
268 key[1] = RandomULong();
269
270 if (g_hash_seed == 0) {
271 g_hash_seed = RandomULong();
272 }
273
274 fd_cb->hash = net_flowhash(key, sizeof(key), g_hash_seed);
275
276 for (idx = 1; idx < GROUP_COUNT_MAX; idx++) {
277 struct flow_divert_group *curr_group = g_flow_divert_groups[idx];
278 if (curr_group != NULL && curr_group != group) {
279 lck_rw_lock_shared(&curr_group->lck);
280 exist = RB_FIND(fd_pcb_tree, &curr_group->pcb_tree, fd_cb);
281 lck_rw_done(&curr_group->lck);
282 if (exist != NULL) {
283 break;
284 }
285 }
286 }
287
288 if (exist == NULL) {
289 lck_rw_lock_exclusive(&group->lck);
290 exist = RB_INSERT(fd_pcb_tree, &group->pcb_tree, fd_cb);
291 lck_rw_done(&group->lck);
292 }
293 } while (exist != NULL && try_count++ < 3);
294
295 if (exist == NULL) {
296 fd_cb->group = group;
297 FDRETAIN(fd_cb); /* The group now has a reference */
298 } else {
299 fd_cb->hash = 0;
300 error = EEXIST;
301 }
302
303 socket_unlock(fd_cb->so, 0);
304
305 done:
306 lck_rw_done(&g_flow_divert_group_lck);
307 socket_lock(fd_cb->so, 0);
308
309 return error;
310 }
311
312 static struct flow_divert_pcb *
313 flow_divert_pcb_create(socket_t so)
314 {
315 struct flow_divert_pcb *new_pcb = NULL;
316
317 MALLOC_ZONE(new_pcb, struct flow_divert_pcb *, sizeof(*new_pcb), M_FLOW_DIVERT_PCB, M_WAITOK);
318 if (new_pcb == NULL) {
319 FDLOG0(LOG_ERR, &nil_pcb, "failed to allocate a pcb");
320 return NULL;
321 }
322
323 memset(new_pcb, 0, sizeof(*new_pcb));
324
325 lck_mtx_init(&new_pcb->mtx, flow_divert_mtx_grp, flow_divert_mtx_attr);
326 new_pcb->so = so;
327 new_pcb->log_level = nil_pcb.log_level;
328
329 FDRETAIN(new_pcb); /* Represents the socket's reference */
330
331 return new_pcb;
332 }
333
334 static void
335 flow_divert_pcb_destroy(struct flow_divert_pcb *fd_cb)
336 {
337 FDLOG(LOG_INFO, fd_cb, "Destroying, app tx %u, app rx %u, tunnel tx %u, tunnel rx %u",
338 fd_cb->bytes_written_by_app, fd_cb->bytes_read_by_app, fd_cb->bytes_sent, fd_cb->bytes_received);
339
340 if (fd_cb->local_address != NULL) {
341 FREE(fd_cb->local_address, M_SONAME);
342 }
343 if (fd_cb->remote_address != NULL) {
344 FREE(fd_cb->remote_address, M_SONAME);
345 }
346 if (fd_cb->connect_token != NULL) {
347 mbuf_freem(fd_cb->connect_token);
348 }
349 if (fd_cb->connect_packet != NULL) {
350 mbuf_freem(fd_cb->connect_packet);
351 }
352 if (fd_cb->app_data != NULL) {
353 FREE(fd_cb->app_data, M_TEMP);
354 }
355 FREE_ZONE(fd_cb, sizeof(*fd_cb), M_FLOW_DIVERT_PCB);
356 }
357
358 static void
359 flow_divert_pcb_remove(struct flow_divert_pcb *fd_cb)
360 {
361 if (fd_cb->group != NULL) {
362 struct flow_divert_group *group = fd_cb->group;
363 lck_rw_lock_exclusive(&group->lck);
364 FDLOG(LOG_INFO, fd_cb, "Removing from group %d, ref count = %d", group->ctl_unit, fd_cb->ref_count);
365 RB_REMOVE(fd_pcb_tree, &group->pcb_tree, fd_cb);
366 fd_cb->group = NULL;
367 FDRELEASE(fd_cb); /* Release the group's reference */
368 lck_rw_done(&group->lck);
369 }
370 }
371
372 static int
373 flow_divert_packet_init(struct flow_divert_pcb *fd_cb, uint8_t packet_type, mbuf_t *packet)
374 {
375 struct flow_divert_packet_header hdr;
376 int error = 0;
377
378 error = mbuf_gethdr(MBUF_DONTWAIT, MBUF_TYPE_HEADER, packet);
379 if (error) {
380 FDLOG(LOG_ERR, fd_cb, "failed to allocate the header mbuf: %d", error);
381 return error;
382 }
383
384 hdr.packet_type = packet_type;
385 hdr.conn_id = htonl(fd_cb->hash);
386
387 /* Lay down the header */
388 error = mbuf_copyback(*packet, 0, sizeof(hdr), &hdr, MBUF_DONTWAIT);
389 if (error) {
390 FDLOG(LOG_ERR, fd_cb, "mbuf_copyback(hdr) failed: %d", error);
391 mbuf_freem(*packet);
392 *packet = NULL;
393 return error;
394 }
395
396 return 0;
397 }
398
399 static int
400 flow_divert_packet_append_tlv(mbuf_t packet, uint8_t type, uint32_t length, const void *value)
401 {
402 uint32_t net_length = htonl(length);
403 int error = 0;
404
405 error = mbuf_copyback(packet, mbuf_pkthdr_len(packet), sizeof(type), &type, MBUF_DONTWAIT);
406 if (error) {
407 FDLOG(LOG_ERR, &nil_pcb, "failed to append the type (%d)", type);
408 return error;
409 }
410
411 error = mbuf_copyback(packet, mbuf_pkthdr_len(packet), sizeof(net_length), &net_length, MBUF_DONTWAIT);
412 if (error) {
413 FDLOG(LOG_ERR, &nil_pcb, "failed to append the length (%u)", length);
414 return error;
415 }
416
417 error = mbuf_copyback(packet, mbuf_pkthdr_len(packet), length, value, MBUF_DONTWAIT);
418 if (error) {
419 FDLOG0(LOG_ERR, &nil_pcb, "failed to append the value");
420 return error;
421 }
422
423 return error;
424 }
425
426 static int
427 flow_divert_packet_find_tlv(mbuf_t packet, int offset, uint8_t type, int *err, int next)
428 {
429 size_t cursor = offset;
430 int error = 0;
431 uint32_t curr_length;
432 uint8_t curr_type;
433
434 *err = 0;
435
436 do {
437 if (!next) {
438 error = mbuf_copydata(packet, cursor, sizeof(curr_type), &curr_type);
439 if (error) {
440 *err = ENOENT;
441 return -1;
442 }
443 } else {
444 next = 0;
445 curr_type = FLOW_DIVERT_TLV_NIL;
446 }
447
448 if (curr_type != type) {
449 cursor += sizeof(curr_type);
450 error = mbuf_copydata(packet, cursor, sizeof(curr_length), &curr_length);
451 if (error) {
452 *err = error;
453 return -1;
454 }
455
456 cursor += (sizeof(curr_length) + ntohl(curr_length));
457 }
458 } while (curr_type != type);
459
460 return cursor;
461 }
462
463 static int
464 flow_divert_packet_get_tlv(mbuf_t packet, int offset, uint8_t type, size_t buff_len, void *buff, uint32_t *val_size)
465 {
466 int error = 0;
467 uint32_t length;
468 int tlv_offset;
469
470 tlv_offset = flow_divert_packet_find_tlv(packet, offset, type, &error, 0);
471 if (tlv_offset < 0) {
472 return error;
473 }
474
475 error = mbuf_copydata(packet, tlv_offset + sizeof(type), sizeof(length), &length);
476 if (error) {
477 return error;
478 }
479
480 length = ntohl(length);
481
482 uint32_t data_offset = tlv_offset + sizeof(type) + sizeof(length);
483
484 if (length > (mbuf_pkthdr_len(packet) - data_offset)) {
485 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));
486 return EINVAL;
487 }
488
489 if (val_size != NULL) {
490 *val_size = length;
491 }
492
493 if (buff != NULL && buff_len > 0) {
494 memset(buff, 0, buff_len);
495 size_t to_copy = (length < buff_len) ? length : buff_len;
496 error = mbuf_copydata(packet, data_offset, to_copy, buff);
497 if (error) {
498 return error;
499 }
500 }
501
502 return 0;
503 }
504
505 static int
506 flow_divert_packet_compute_hmac(mbuf_t packet, struct flow_divert_group *group, uint8_t *hmac)
507 {
508 mbuf_t curr_mbuf = packet;
509
510 if (g_crypto_funcs == NULL || group->token_key == NULL) {
511 return ENOPROTOOPT;
512 }
513
514 cchmac_di_decl(g_crypto_funcs->ccsha1_di, hmac_ctx);
515 g_crypto_funcs->cchmac_init_fn(g_crypto_funcs->ccsha1_di, hmac_ctx, group->token_key_size, group->token_key);
516
517 while (curr_mbuf != NULL) {
518 g_crypto_funcs->cchmac_update_fn(g_crypto_funcs->ccsha1_di, hmac_ctx, mbuf_len(curr_mbuf), mbuf_data(curr_mbuf));
519 curr_mbuf = mbuf_next(curr_mbuf);
520 }
521
522 g_crypto_funcs->cchmac_final_fn(g_crypto_funcs->ccsha1_di, hmac_ctx, hmac);
523
524 return 0;
525 }
526
527 static int
528 flow_divert_packet_verify_hmac(mbuf_t packet, uint32_t ctl_unit)
529 {
530 int error = 0;
531 struct flow_divert_group *group = NULL;
532 int hmac_offset;
533 uint8_t packet_hmac[SHA_DIGEST_LENGTH];
534 uint8_t computed_hmac[SHA_DIGEST_LENGTH];
535 mbuf_t tail;
536
537 lck_rw_lock_shared(&g_flow_divert_group_lck);
538
539 if (g_flow_divert_groups != NULL && g_active_group_count > 0) {
540 group = g_flow_divert_groups[ctl_unit];
541 }
542
543 if (group == NULL) {
544 lck_rw_done(&g_flow_divert_group_lck);
545 return ENOPROTOOPT;
546 }
547
548 lck_rw_lock_shared(&group->lck);
549
550 if (group->token_key == NULL) {
551 error = ENOPROTOOPT;
552 goto done;
553 }
554
555 hmac_offset = flow_divert_packet_find_tlv(packet, 0, FLOW_DIVERT_TLV_HMAC, &error, 0);
556 if (hmac_offset < 0) {
557 goto done;
558 }
559
560 error = flow_divert_packet_get_tlv(packet, hmac_offset, FLOW_DIVERT_TLV_HMAC, sizeof(packet_hmac), packet_hmac, NULL);
561 if (error) {
562 goto done;
563 }
564
565 /* Chop off the HMAC TLV */
566 error = mbuf_split(packet, hmac_offset, MBUF_WAITOK, &tail);
567 if (error) {
568 goto done;
569 }
570
571 mbuf_free(tail);
572
573 error = flow_divert_packet_compute_hmac(packet, group, computed_hmac);
574 if (error) {
575 goto done;
576 }
577
578 if (cc_cmp_safe(sizeof(packet_hmac), packet_hmac, computed_hmac)) {
579 FDLOG0(LOG_WARNING, &nil_pcb, "HMAC in token does not match computed HMAC");
580 error = EINVAL;
581 goto done;
582 }
583
584 done:
585 lck_rw_done(&group->lck);
586 lck_rw_done(&g_flow_divert_group_lck);
587 return error;
588 }
589
590 static void
591 flow_divert_add_data_statistics(struct flow_divert_pcb *fd_cb, int data_len, Boolean send)
592 {
593 struct inpcb *inp = NULL;
594 struct ifnet *ifp = NULL;
595 Boolean cell = FALSE;
596 Boolean wifi = FALSE;
597 Boolean wired = FALSE;
598
599 inp = sotoinpcb(fd_cb->so);
600 if (inp == NULL) {
601 return;
602 }
603
604 ifp = inp->inp_last_outifp;
605 if (ifp != NULL) {
606 cell = IFNET_IS_CELLULAR(ifp);
607 wifi = (!cell && IFNET_IS_WIFI(ifp));
608 wired = (!wifi && IFNET_IS_WIRED(ifp));
609 }
610
611 if (send) {
612 INP_ADD_STAT(inp, cell, wifi, wired, txpackets, 1);
613 INP_ADD_STAT(inp, cell, wifi, wired, txbytes, data_len);
614 } else {
615 INP_ADD_STAT(inp, cell, wifi, wired, rxpackets, 1);
616 INP_ADD_STAT(inp, cell, wifi, wired, rxbytes, data_len);
617 }
618 inp_set_activity_bitmap(inp);
619 }
620
621 static errno_t
622 flow_divert_check_no_cellular(struct flow_divert_pcb *fd_cb)
623 {
624 struct inpcb *inp = NULL;
625
626 inp = sotoinpcb(fd_cb->so);
627 if (inp && INP_NO_CELLULAR(inp) && inp->inp_last_outifp &&
628 IFNET_IS_CELLULAR(inp->inp_last_outifp)) {
629 return EHOSTUNREACH;
630 }
631
632 return 0;
633 }
634
635 static errno_t
636 flow_divert_check_no_expensive(struct flow_divert_pcb *fd_cb)
637 {
638 struct inpcb *inp = NULL;
639
640 inp = sotoinpcb(fd_cb->so);
641 if (inp && INP_NO_EXPENSIVE(inp) && inp->inp_last_outifp &&
642 IFNET_IS_EXPENSIVE(inp->inp_last_outifp)) {
643 return EHOSTUNREACH;
644 }
645
646 return 0;
647 }
648
649 static errno_t
650 flow_divert_check_no_constrained(struct flow_divert_pcb *fd_cb)
651 {
652 struct inpcb *inp = NULL;
653
654 inp = sotoinpcb(fd_cb->so);
655 if (inp && INP_NO_CONSTRAINED(inp) && inp->inp_last_outifp &&
656 IFNET_IS_CONSTRAINED(inp->inp_last_outifp)) {
657 return EHOSTUNREACH;
658 }
659
660 return 0;
661 }
662
663 static void
664 flow_divert_update_closed_state(struct flow_divert_pcb *fd_cb, int how, Boolean tunnel)
665 {
666 if (how != SHUT_RD) {
667 fd_cb->flags |= FLOW_DIVERT_WRITE_CLOSED;
668 if (tunnel || !(fd_cb->flags & FLOW_DIVERT_CONNECT_STARTED)) {
669 fd_cb->flags |= FLOW_DIVERT_TUNNEL_WR_CLOSED;
670 /* If the tunnel is not accepting writes any more, then flush the send buffer */
671 sbflush(&fd_cb->so->so_snd);
672 }
673 }
674 if (how != SHUT_WR) {
675 fd_cb->flags |= FLOW_DIVERT_READ_CLOSED;
676 if (tunnel || !(fd_cb->flags & FLOW_DIVERT_CONNECT_STARTED)) {
677 fd_cb->flags |= FLOW_DIVERT_TUNNEL_RD_CLOSED;
678 }
679 }
680 }
681
682 static uint16_t
683 trie_node_alloc(struct flow_divert_trie *trie)
684 {
685 if (trie->nodes_free_next < trie->nodes_count) {
686 uint16_t node_idx = trie->nodes_free_next++;
687 TRIE_NODE(trie, node_idx).child_map = NULL_TRIE_IDX;
688 return node_idx;
689 } else {
690 return NULL_TRIE_IDX;
691 }
692 }
693
694 static uint16_t
695 trie_child_map_alloc(struct flow_divert_trie *trie)
696 {
697 if (trie->child_maps_free_next < trie->child_maps_count) {
698 return trie->child_maps_free_next++;
699 } else {
700 return NULL_TRIE_IDX;
701 }
702 }
703
704 static uint16_t
705 trie_bytes_move(struct flow_divert_trie *trie, uint16_t bytes_idx, size_t bytes_size)
706 {
707 uint16_t start = trie->bytes_free_next;
708 if (start + bytes_size <= trie->bytes_count) {
709 if (start != bytes_idx) {
710 memmove(&TRIE_BYTE(trie, start), &TRIE_BYTE(trie, bytes_idx), bytes_size);
711 }
712 trie->bytes_free_next += bytes_size;
713 return start;
714 } else {
715 return NULL_TRIE_IDX;
716 }
717 }
718
719 static uint16_t
720 flow_divert_trie_insert(struct flow_divert_trie *trie, uint16_t string_start, size_t string_len)
721 {
722 uint16_t current = trie->root;
723 uint16_t child = trie->root;
724 uint16_t string_end = string_start + string_len;
725 uint16_t string_idx = string_start;
726 uint16_t string_remainder = string_len;
727
728 while (child != NULL_TRIE_IDX) {
729 uint16_t parent = current;
730 uint16_t node_idx;
731 uint16_t current_end;
732
733 current = child;
734 child = NULL_TRIE_IDX;
735
736 current_end = TRIE_NODE(trie, current).start + TRIE_NODE(trie, current).length;
737
738 for (node_idx = TRIE_NODE(trie, current).start;
739 node_idx < current_end &&
740 string_idx < string_end &&
741 TRIE_BYTE(trie, node_idx) == TRIE_BYTE(trie, string_idx);
742 node_idx++, string_idx++) {
743 ;
744 }
745
746 string_remainder = string_end - string_idx;
747
748 if (node_idx < (TRIE_NODE(trie, current).start + TRIE_NODE(trie, current).length)) {
749 /*
750 * We did not reach the end of the current node's string.
751 * We need to split the current node into two:
752 * 1. A new node that contains the prefix of the node that matches
753 * the prefix of the string being inserted.
754 * 2. The current node modified to point to the remainder
755 * of the current node's string.
756 */
757 uint16_t prefix = trie_node_alloc(trie);
758 if (prefix == NULL_TRIE_IDX) {
759 FDLOG0(LOG_ERR, &nil_pcb, "Ran out of trie nodes while splitting an existing node");
760 return NULL_TRIE_IDX;
761 }
762
763 /*
764 * Prefix points to the portion of the current nodes's string that has matched
765 * the input string thus far.
766 */
767 TRIE_NODE(trie, prefix).start = TRIE_NODE(trie, current).start;
768 TRIE_NODE(trie, prefix).length = (node_idx - TRIE_NODE(trie, current).start);
769
770 /*
771 * Prefix has the current node as the child corresponding to the first byte
772 * after the split.
773 */
774 TRIE_NODE(trie, prefix).child_map = trie_child_map_alloc(trie);
775 if (TRIE_NODE(trie, prefix).child_map == NULL_TRIE_IDX) {
776 FDLOG0(LOG_ERR, &nil_pcb, "Ran out of child maps while splitting an existing node");
777 return NULL_TRIE_IDX;
778 }
779 TRIE_CHILD(trie, prefix, TRIE_BYTE(trie, node_idx)) = current;
780
781 /* Parent has the prefix as the child correspoding to the first byte in the prefix */
782 TRIE_CHILD(trie, parent, TRIE_BYTE(trie, TRIE_NODE(trie, prefix).start)) = prefix;
783
784 /* Current node is adjusted to point to the remainder */
785 TRIE_NODE(trie, current).start = node_idx;
786 TRIE_NODE(trie, current).length -= TRIE_NODE(trie, prefix).length;
787
788 /* We want to insert the new leaf (if any) as a child of the prefix */
789 current = prefix;
790 }
791
792 if (string_remainder > 0) {
793 /*
794 * We still have bytes in the string that have not been matched yet.
795 * If the current node has children, iterate to the child corresponding
796 * to the next byte in the string.
797 */
798 if (TRIE_NODE(trie, current).child_map != NULL_TRIE_IDX) {
799 child = TRIE_CHILD(trie, current, TRIE_BYTE(trie, string_idx));
800 }
801 }
802 } /* while (child != NULL_TRIE_IDX) */
803
804 if (string_remainder > 0) {
805 /* Add a new leaf containing the remainder of the string */
806 uint16_t leaf = trie_node_alloc(trie);
807 if (leaf == NULL_TRIE_IDX) {
808 FDLOG0(LOG_ERR, &nil_pcb, "Ran out of trie nodes while inserting a new leaf");
809 return NULL_TRIE_IDX;
810 }
811
812 TRIE_NODE(trie, leaf).start = trie_bytes_move(trie, string_idx, string_remainder);
813 if (TRIE_NODE(trie, leaf).start == NULL_TRIE_IDX) {
814 FDLOG0(LOG_ERR, &nil_pcb, "Ran out of bytes while inserting a new leaf");
815 return NULL_TRIE_IDX;
816 }
817 TRIE_NODE(trie, leaf).length = string_remainder;
818
819 /* Set the new leaf as the child of the current node */
820 if (TRIE_NODE(trie, current).child_map == NULL_TRIE_IDX) {
821 TRIE_NODE(trie, current).child_map = trie_child_map_alloc(trie);
822 if (TRIE_NODE(trie, current).child_map == NULL_TRIE_IDX) {
823 FDLOG0(LOG_ERR, &nil_pcb, "Ran out of child maps while inserting a new leaf");
824 return NULL_TRIE_IDX;
825 }
826 }
827 TRIE_CHILD(trie, current, TRIE_BYTE(trie, TRIE_NODE(trie, leaf).start)) = leaf;
828 current = leaf;
829 } /* else duplicate or this string is a prefix of one of the existing strings */
830
831 return current;
832 }
833
834 #define APPLE_WEBCLIP_ID_PREFIX "com.apple.webapp"
835 static uint16_t
836 flow_divert_trie_search(struct flow_divert_trie *trie, const uint8_t *string_bytes)
837 {
838 uint16_t current = trie->root;
839 uint16_t string_idx = 0;
840
841 while (current != NULL_TRIE_IDX) {
842 uint16_t next = NULL_TRIE_IDX;
843 uint16_t node_end = TRIE_NODE(trie, current).start + TRIE_NODE(trie, current).length;
844 uint16_t node_idx;
845
846 for (node_idx = TRIE_NODE(trie, current).start;
847 node_idx < node_end && string_bytes[string_idx] != '\0' && string_bytes[string_idx] == TRIE_BYTE(trie, node_idx);
848 node_idx++, string_idx++) {
849 ;
850 }
851
852 if (node_idx == node_end) {
853 if (string_bytes[string_idx] == '\0') {
854 return current; /* Got an exact match */
855 } else if (string_idx == strlen(APPLE_WEBCLIP_ID_PREFIX) &&
856 0 == strncmp((const char *)string_bytes, APPLE_WEBCLIP_ID_PREFIX, string_idx)) {
857 return current; /* Got an apple webclip id prefix match */
858 } else if (TRIE_NODE(trie, current).child_map != NULL_TRIE_IDX) {
859 next = TRIE_CHILD(trie, current, string_bytes[string_idx]);
860 }
861 }
862 current = next;
863 }
864
865 return NULL_TRIE_IDX;
866 }
867
868 struct uuid_search_info {
869 uuid_t target_uuid;
870 char *found_signing_id;
871 boolean_t found_multiple_signing_ids;
872 proc_t found_proc;
873 };
874
875 static int
876 flow_divert_find_proc_by_uuid_callout(proc_t p, void *arg)
877 {
878 struct uuid_search_info *info = (struct uuid_search_info *)arg;
879 int result = PROC_RETURNED_DONE; /* By default, we didn't find the process */
880
881 if (info->found_signing_id != NULL) {
882 if (!info->found_multiple_signing_ids) {
883 /* All processes that were found had the same signing identifier, so just claim this first one and be done. */
884 info->found_proc = p;
885 result = PROC_CLAIMED_DONE;
886 } else {
887 uuid_string_t uuid_str;
888 uuid_unparse(info->target_uuid, uuid_str);
889 FDLOG(LOG_WARNING, &nil_pcb, "Found multiple processes with UUID %s with different signing identifiers", uuid_str);
890 }
891 FREE(info->found_signing_id, M_TEMP);
892 info->found_signing_id = NULL;
893 }
894
895 if (result == PROC_RETURNED_DONE) {
896 uuid_string_t uuid_str;
897 uuid_unparse(info->target_uuid, uuid_str);
898 FDLOG(LOG_WARNING, &nil_pcb, "Failed to find a process with UUID %s", uuid_str);
899 }
900
901 return result;
902 }
903
904 static int
905 flow_divert_find_proc_by_uuid_filter(proc_t p, void *arg)
906 {
907 struct uuid_search_info *info = (struct uuid_search_info *)arg;
908 int include = 0;
909
910 if (info->found_multiple_signing_ids) {
911 return include;
912 }
913
914 include = (uuid_compare(p->p_uuid, info->target_uuid) == 0);
915 if (include) {
916 const char *signing_id = cs_identity_get(p);
917 if (signing_id != NULL) {
918 FDLOG(LOG_INFO, &nil_pcb, "Found process %d with signing identifier %s", p->p_pid, signing_id);
919 size_t signing_id_size = strlen(signing_id) + 1;
920 if (info->found_signing_id == NULL) {
921 MALLOC(info->found_signing_id, char *, signing_id_size, M_TEMP, M_WAITOK);
922 memcpy(info->found_signing_id, signing_id, signing_id_size);
923 } else if (memcmp(signing_id, info->found_signing_id, signing_id_size)) {
924 info->found_multiple_signing_ids = TRUE;
925 }
926 } else {
927 info->found_multiple_signing_ids = TRUE;
928 }
929 include = !info->found_multiple_signing_ids;
930 }
931
932 return include;
933 }
934
935 static proc_t
936 flow_divert_find_proc_by_uuid(uuid_t uuid)
937 {
938 struct uuid_search_info info;
939
940 if (LOG_INFO <= nil_pcb.log_level) {
941 uuid_string_t uuid_str;
942 uuid_unparse(uuid, uuid_str);
943 FDLOG(LOG_INFO, &nil_pcb, "Looking for process with UUID %s", uuid_str);
944 }
945
946 memset(&info, 0, sizeof(info));
947 info.found_proc = PROC_NULL;
948 uuid_copy(info.target_uuid, uuid);
949
950 proc_iterate(PROC_ALLPROCLIST, flow_divert_find_proc_by_uuid_callout, &info, flow_divert_find_proc_by_uuid_filter, &info);
951
952 return info.found_proc;
953 }
954
955 static int
956 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)
957 {
958 int error = 0;
959 int cdhash_error = 0;
960 unsigned char cdhash[SHA1_RESULTLEN] = { 0 };
961 audit_token_t audit_token = {};
962 const char *proc_cs_id = signing_id;
963
964 proc_lock(proc);
965
966 if (proc_cs_id == NULL) {
967 if (proc->p_csflags & (CS_VALID | CS_DEBUGGED)) {
968 proc_cs_id = cs_identity_get(proc);
969 } else {
970 FDLOG0(LOG_ERR, fd_cb, "Signature of proc is invalid");
971 }
972 }
973
974 if (is_effective) {
975 lck_rw_lock_shared(&fd_cb->group->lck);
976 if (!(fd_cb->group->flags & FLOW_DIVERT_GROUP_FLAG_NO_APP_MAP)) {
977 if (proc_cs_id != NULL) {
978 uint16_t result = flow_divert_trie_search(&fd_cb->group->signing_id_trie, (const uint8_t *)proc_cs_id);
979 if (result == NULL_TRIE_IDX) {
980 FDLOG(LOG_WARNING, fd_cb, "%s did not match", proc_cs_id);
981 error = EPERM;
982 } else {
983 FDLOG(LOG_INFO, fd_cb, "%s matched", proc_cs_id);
984 }
985 } else {
986 error = EPERM;
987 }
988 }
989 lck_rw_done(&fd_cb->group->lck);
990 }
991
992 if (error != 0) {
993 goto done;
994 }
995
996 /*
997 * If signing_id is not NULL then it came from the flow divert token and will be added
998 * as part of the token, so there is no need to add it here.
999 */
1000 if (signing_id == NULL && proc_cs_id != NULL) {
1001 error = flow_divert_packet_append_tlv(connect_packet,
1002 (is_effective ? FLOW_DIVERT_TLV_SIGNING_ID : FLOW_DIVERT_TLV_APP_REAL_SIGNING_ID),
1003 strlen(proc_cs_id),
1004 proc_cs_id);
1005 if (error != 0) {
1006 FDLOG(LOG_ERR, fd_cb, "failed to append the signing ID: %d", error);
1007 goto done;
1008 }
1009 }
1010
1011 cdhash_error = proc_getcdhash(proc, cdhash);
1012 if (cdhash_error == 0) {
1013 error = flow_divert_packet_append_tlv(connect_packet,
1014 (is_effective ? FLOW_DIVERT_TLV_CDHASH : FLOW_DIVERT_TLV_APP_REAL_CDHASH),
1015 sizeof(cdhash),
1016 cdhash);
1017 if (error) {
1018 FDLOG(LOG_ERR, fd_cb, "failed to append the cdhash: %d", error);
1019 goto done;
1020 }
1021 } else {
1022 FDLOG(LOG_ERR, fd_cb, "failed to get the cdhash: %d", cdhash_error);
1023 }
1024
1025 task_t task = proc_task(proc);
1026 if (task != TASK_NULL) {
1027 mach_msg_type_number_t count = TASK_AUDIT_TOKEN_COUNT;
1028 kern_return_t rc = task_info(task, TASK_AUDIT_TOKEN, (task_info_t)&audit_token, &count);
1029 if (rc == KERN_SUCCESS) {
1030 int append_error = flow_divert_packet_append_tlv(connect_packet,
1031 (is_effective ? FLOW_DIVERT_TLV_APP_AUDIT_TOKEN : FLOW_DIVERT_TLV_APP_REAL_AUDIT_TOKEN),
1032 sizeof(audit_token_t),
1033 &audit_token);
1034 if (append_error) {
1035 FDLOG(LOG_ERR, fd_cb, "failed to append app audit token: %d", append_error);
1036 }
1037 }
1038 }
1039
1040 done:
1041 proc_unlock(proc);
1042
1043 return error;
1044 }
1045
1046 static int
1047 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)
1048 {
1049 int error = 0;
1050 proc_t effective_proc = PROC_NULL;
1051 proc_t responsible_proc = PROC_NULL;
1052 proc_t real_proc = proc_find(so->last_pid);
1053 bool release_real_proc = true;
1054
1055 proc_t src_proc = PROC_NULL;
1056 proc_t real_src_proc = PROC_NULL;
1057
1058 if (real_proc == PROC_NULL) {
1059 FDLOG(LOG_ERR, fd_cb, "failed to find the real proc record for %d", so->last_pid);
1060 release_real_proc = false;
1061 real_proc = proc;
1062 if (real_proc == PROC_NULL) {
1063 real_proc = current_proc();
1064 }
1065 }
1066
1067 if (so->so_flags & SOF_DELEGATED) {
1068 if (real_proc->p_pid != so->e_pid) {
1069 effective_proc = proc_find(so->e_pid);
1070 } else if (uuid_compare(real_proc->p_uuid, so->e_uuid)) {
1071 effective_proc = flow_divert_find_proc_by_uuid(so->e_uuid);
1072 }
1073 }
1074
1075 #if defined(XNU_TARGET_OS_OSX)
1076 lck_rw_lock_shared(&fd_cb->group->lck);
1077 if (!(fd_cb->group->flags & FLOW_DIVERT_GROUP_FLAG_NO_APP_MAP)) {
1078 if (so->so_rpid > 0) {
1079 responsible_proc = proc_find(so->so_rpid);
1080 }
1081 }
1082 lck_rw_done(&fd_cb->group->lck);
1083 #endif
1084
1085 real_src_proc = real_proc;
1086
1087 if (responsible_proc != PROC_NULL) {
1088 src_proc = responsible_proc;
1089 if (effective_proc != NULL) {
1090 real_src_proc = effective_proc;
1091 }
1092 } else if (effective_proc != PROC_NULL) {
1093 src_proc = effective_proc;
1094 } else {
1095 src_proc = real_proc;
1096 }
1097
1098 error = flow_divert_add_proc_info(fd_cb, src_proc, signing_id, connect_packet, true);
1099 if (error != 0) {
1100 goto done;
1101 }
1102
1103 if (real_src_proc != NULL && real_src_proc != src_proc) {
1104 error = flow_divert_add_proc_info(fd_cb, real_src_proc, NULL, connect_packet, false);
1105 if (error != 0) {
1106 goto done;
1107 }
1108 }
1109
1110 done:
1111 if (responsible_proc != PROC_NULL) {
1112 proc_rele(responsible_proc);
1113 }
1114
1115 if (effective_proc != PROC_NULL) {
1116 proc_rele(effective_proc);
1117 }
1118
1119 if (real_proc != PROC_NULL && release_real_proc) {
1120 proc_rele(real_proc);
1121 }
1122
1123 return error;
1124 }
1125
1126 static int
1127 flow_divert_send_packet(struct flow_divert_pcb *fd_cb, mbuf_t packet, Boolean enqueue)
1128 {
1129 int error;
1130
1131 if (fd_cb->group == NULL) {
1132 fd_cb->so->so_error = ECONNABORTED;
1133 flow_divert_disconnect_socket(fd_cb->so);
1134 return ECONNABORTED;
1135 }
1136
1137 lck_rw_lock_shared(&fd_cb->group->lck);
1138
1139 if (MBUFQ_EMPTY(&fd_cb->group->send_queue)) {
1140 error = ctl_enqueuembuf(g_flow_divert_kctl_ref, fd_cb->group->ctl_unit, packet, CTL_DATA_EOR);
1141 } else {
1142 error = ENOBUFS;
1143 }
1144
1145 if (error == ENOBUFS) {
1146 if (enqueue) {
1147 if (!lck_rw_lock_shared_to_exclusive(&fd_cb->group->lck)) {
1148 lck_rw_lock_exclusive(&fd_cb->group->lck);
1149 }
1150 MBUFQ_ENQUEUE(&fd_cb->group->send_queue, packet);
1151 error = 0;
1152 }
1153 OSTestAndSet(GROUP_BIT_CTL_ENQUEUE_BLOCKED, &fd_cb->group->atomic_bits);
1154 }
1155
1156 lck_rw_done(&fd_cb->group->lck);
1157
1158 return error;
1159 }
1160
1161 static int
1162 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)
1163 {
1164 int error = 0;
1165 int flow_type = 0;
1166 char *signing_id = NULL;
1167 mbuf_t connect_packet = NULL;
1168 cfil_sock_id_t cfil_sock_id = CFIL_SOCK_ID_NONE;
1169 const void *cfil_id = NULL;
1170 size_t cfil_id_size = 0;
1171 struct inpcb *inp = sotoinpcb(so);
1172 struct ifnet *ifp = NULL;
1173
1174 error = flow_divert_packet_init(fd_cb, FLOW_DIVERT_PKT_CONNECT, &connect_packet);
1175 if (error) {
1176 goto done;
1177 }
1178
1179
1180 if (fd_cb->connect_token != NULL && (fd_cb->flags & FLOW_DIVERT_HAS_HMAC)) {
1181 uint32_t sid_size = 0;
1182 int find_error = flow_divert_packet_get_tlv(fd_cb->connect_token, 0, FLOW_DIVERT_TLV_SIGNING_ID, 0, NULL, &sid_size);
1183 if (find_error == 0 && sid_size > 0) {
1184 MALLOC(signing_id, char *, sid_size + 1, M_TEMP, M_WAITOK | M_ZERO);
1185 if (signing_id != NULL) {
1186 flow_divert_packet_get_tlv(fd_cb->connect_token, 0, FLOW_DIVERT_TLV_SIGNING_ID, sid_size, signing_id, NULL);
1187 FDLOG(LOG_INFO, fd_cb, "Got %s from token", signing_id);
1188 }
1189 }
1190 }
1191
1192 socket_unlock(so, 0);
1193
1194 error = flow_divert_add_all_proc_info(fd_cb, so, p, signing_id, connect_packet);
1195
1196 socket_lock(so, 0);
1197
1198 if (signing_id != NULL) {
1199 FREE(signing_id, M_TEMP);
1200 }
1201
1202 if (error) {
1203 FDLOG(LOG_ERR, fd_cb, "Failed to add source proc info: %d", error);
1204 goto done;
1205 }
1206
1207 error = flow_divert_packet_append_tlv(connect_packet,
1208 FLOW_DIVERT_TLV_TRAFFIC_CLASS,
1209 sizeof(fd_cb->so->so_traffic_class),
1210 &fd_cb->so->so_traffic_class);
1211 if (error) {
1212 goto done;
1213 }
1214
1215 if (SOCK_TYPE(fd_cb->so) == SOCK_STREAM) {
1216 flow_type = FLOW_DIVERT_FLOW_TYPE_TCP;
1217 } else if (SOCK_TYPE(fd_cb->so) == SOCK_DGRAM) {
1218 flow_type = FLOW_DIVERT_FLOW_TYPE_UDP;
1219 } else {
1220 error = EINVAL;
1221 goto done;
1222 }
1223 error = flow_divert_packet_append_tlv(connect_packet,
1224 FLOW_DIVERT_TLV_FLOW_TYPE,
1225 sizeof(flow_type),
1226 &flow_type);
1227
1228 if (error) {
1229 goto done;
1230 }
1231
1232 if (fd_cb->connect_token != NULL) {
1233 unsigned int token_len = m_length(fd_cb->connect_token);
1234 mbuf_concatenate(connect_packet, fd_cb->connect_token);
1235 mbuf_pkthdr_adjustlen(connect_packet, token_len);
1236 fd_cb->connect_token = NULL;
1237 } else {
1238 uint32_t ctl_unit = htonl(fd_cb->control_group_unit);
1239
1240 error = flow_divert_packet_append_tlv(connect_packet, FLOW_DIVERT_TLV_CTL_UNIT, sizeof(ctl_unit), &ctl_unit);
1241 if (error) {
1242 goto done;
1243 }
1244
1245 error = flow_divert_append_target_endpoint_tlv(connect_packet, to);
1246 if (error) {
1247 goto done;
1248 }
1249 }
1250
1251 if (fd_cb->local_address != NULL) {
1252 error = EALREADY;
1253 goto done;
1254 } else {
1255 if (flow_divert_has_pcb_local_address(inp)) {
1256 error = flow_divert_inp_to_sockaddr(inp, &fd_cb->local_address);
1257 if (error) {
1258 FDLOG0(LOG_ERR, fd_cb, "failed to get the local socket address.");
1259 goto done;
1260 }
1261 }
1262 }
1263
1264 if (fd_cb->local_address != NULL) {
1265 /* socket is bound. */
1266 error = flow_divert_packet_append_tlv(connect_packet, FLOW_DIVERT_TLV_LOCAL_ADDR,
1267 fd_cb->local_address->sa_len, fd_cb->local_address);
1268 if (error) {
1269 goto done;
1270 }
1271 }
1272
1273 if ((inp->inp_flags | INP_BOUND_IF) && inp->inp_boundifp != NULL) {
1274 ifp = inp->inp_boundifp;
1275 } else if (inp->inp_last_outifp != NULL) {
1276 ifp = inp->inp_last_outifp;
1277 }
1278
1279 if (ifp != NULL) {
1280 uint32_t flow_if_index = ifp->if_index;
1281 error = flow_divert_packet_append_tlv(connect_packet, FLOW_DIVERT_TLV_OUT_IF_INDEX,
1282 sizeof(flow_if_index), &flow_if_index);
1283 if (error) {
1284 goto done;
1285 }
1286 }
1287
1288 if (so->so_flags1 & SOF1_DATA_IDEMPOTENT) {
1289 uint32_t flags = FLOW_DIVERT_TOKEN_FLAG_TFO;
1290 error = flow_divert_packet_append_tlv(connect_packet, FLOW_DIVERT_TLV_FLAGS, sizeof(flags), &flags);
1291 if (error) {
1292 goto done;
1293 }
1294 }
1295
1296 cfil_sock_id = cfil_sock_id_from_socket(so);
1297 if (cfil_sock_id != CFIL_SOCK_ID_NONE) {
1298 cfil_id = &cfil_sock_id;
1299 cfil_id_size = sizeof(cfil_sock_id);
1300 } else if (so->so_flags1 & SOF1_CONTENT_FILTER_SKIP) {
1301 cfil_id = &inp->necp_client_uuid;
1302 cfil_id_size = sizeof(inp->necp_client_uuid);
1303 }
1304
1305 if (cfil_id != NULL && cfil_id_size > 0 && cfil_id_size <= sizeof(uuid_t)) {
1306 error = flow_divert_packet_append_tlv(connect_packet, FLOW_DIVERT_TLV_CFIL_ID, cfil_id_size, cfil_id);
1307 if (error) {
1308 goto done;
1309 }
1310 }
1311
1312 done:
1313 if (!error) {
1314 *out_connect_packet = connect_packet;
1315 } else if (connect_packet != NULL) {
1316 mbuf_freem(connect_packet);
1317 }
1318
1319 return error;
1320 }
1321
1322 static int
1323 flow_divert_send_connect_result(struct flow_divert_pcb *fd_cb)
1324 {
1325 int error = 0;
1326 mbuf_t packet = NULL;
1327 int rbuff_space = 0;
1328
1329 error = flow_divert_packet_init(fd_cb, FLOW_DIVERT_PKT_CONNECT_RESULT, &packet);
1330 if (error) {
1331 FDLOG(LOG_ERR, fd_cb, "failed to create a connect result packet: %d", error);
1332 goto done;
1333 }
1334
1335 rbuff_space = fd_cb->so->so_rcv.sb_hiwat;
1336 if (rbuff_space < 0) {
1337 rbuff_space = 0;
1338 }
1339 rbuff_space = htonl(rbuff_space);
1340 error = flow_divert_packet_append_tlv(packet,
1341 FLOW_DIVERT_TLV_SPACE_AVAILABLE,
1342 sizeof(rbuff_space),
1343 &rbuff_space);
1344 if (error) {
1345 goto done;
1346 }
1347
1348 error = flow_divert_send_packet(fd_cb, packet, TRUE);
1349 if (error) {
1350 goto done;
1351 }
1352
1353 done:
1354 if (error && packet != NULL) {
1355 mbuf_freem(packet);
1356 }
1357
1358 return error;
1359 }
1360
1361 static int
1362 flow_divert_send_close(struct flow_divert_pcb *fd_cb, int how)
1363 {
1364 int error = 0;
1365 mbuf_t packet = NULL;
1366 uint32_t zero = 0;
1367
1368 error = flow_divert_packet_init(fd_cb, FLOW_DIVERT_PKT_CLOSE, &packet);
1369 if (error) {
1370 FDLOG(LOG_ERR, fd_cb, "failed to create a close packet: %d", error);
1371 goto done;
1372 }
1373
1374 error = flow_divert_packet_append_tlv(packet, FLOW_DIVERT_TLV_ERROR_CODE, sizeof(zero), &zero);
1375 if (error) {
1376 FDLOG(LOG_ERR, fd_cb, "failed to add the error code TLV: %d", error);
1377 goto done;
1378 }
1379
1380 how = htonl(how);
1381 error = flow_divert_packet_append_tlv(packet, FLOW_DIVERT_TLV_HOW, sizeof(how), &how);
1382 if (error) {
1383 FDLOG(LOG_ERR, fd_cb, "failed to add the how flag: %d", error);
1384 goto done;
1385 }
1386
1387 error = flow_divert_send_packet(fd_cb, packet, TRUE);
1388 if (error) {
1389 goto done;
1390 }
1391
1392 done:
1393 if (error && packet != NULL) {
1394 mbuf_free(packet);
1395 }
1396
1397 return error;
1398 }
1399
1400 static int
1401 flow_divert_tunnel_how_closed(struct flow_divert_pcb *fd_cb)
1402 {
1403 if ((fd_cb->flags & (FLOW_DIVERT_TUNNEL_RD_CLOSED | FLOW_DIVERT_TUNNEL_WR_CLOSED)) ==
1404 (FLOW_DIVERT_TUNNEL_RD_CLOSED | FLOW_DIVERT_TUNNEL_WR_CLOSED)) {
1405 return SHUT_RDWR;
1406 } else if (fd_cb->flags & FLOW_DIVERT_TUNNEL_RD_CLOSED) {
1407 return SHUT_RD;
1408 } else if (fd_cb->flags & FLOW_DIVERT_TUNNEL_WR_CLOSED) {
1409 return SHUT_WR;
1410 }
1411
1412 return -1;
1413 }
1414
1415 /*
1416 * Determine what close messages if any need to be sent to the tunnel. Returns TRUE if the tunnel is closed for both reads and
1417 * writes. Returns FALSE otherwise.
1418 */
1419 static void
1420 flow_divert_send_close_if_needed(struct flow_divert_pcb *fd_cb)
1421 {
1422 int how = -1;
1423
1424 /* Do not send any close messages if there is still data in the send buffer */
1425 if (fd_cb->so->so_snd.sb_cc == 0) {
1426 if ((fd_cb->flags & (FLOW_DIVERT_READ_CLOSED | FLOW_DIVERT_TUNNEL_RD_CLOSED)) == FLOW_DIVERT_READ_CLOSED) {
1427 /* Socket closed reads, but tunnel did not. Tell tunnel to close reads */
1428 how = SHUT_RD;
1429 }
1430 if ((fd_cb->flags & (FLOW_DIVERT_WRITE_CLOSED | FLOW_DIVERT_TUNNEL_WR_CLOSED)) == FLOW_DIVERT_WRITE_CLOSED) {
1431 /* Socket closed writes, but tunnel did not. Tell tunnel to close writes */
1432 if (how == SHUT_RD) {
1433 how = SHUT_RDWR;
1434 } else {
1435 how = SHUT_WR;
1436 }
1437 }
1438 }
1439
1440 if (how != -1) {
1441 FDLOG(LOG_INFO, fd_cb, "sending close, how = %d", how);
1442 if (flow_divert_send_close(fd_cb, how) != ENOBUFS) {
1443 /* Successfully sent the close packet. Record the ways in which the tunnel has been closed */
1444 if (how != SHUT_RD) {
1445 fd_cb->flags |= FLOW_DIVERT_TUNNEL_WR_CLOSED;
1446 }
1447 if (how != SHUT_WR) {
1448 fd_cb->flags |= FLOW_DIVERT_TUNNEL_RD_CLOSED;
1449 }
1450 }
1451 }
1452
1453 if (flow_divert_tunnel_how_closed(fd_cb) == SHUT_RDWR) {
1454 flow_divert_disconnect_socket(fd_cb->so);
1455 }
1456 }
1457
1458 static errno_t
1459 flow_divert_send_data_packet(struct flow_divert_pcb *fd_cb, mbuf_t data, size_t data_len, struct sockaddr *toaddr, Boolean force)
1460 {
1461 mbuf_t packet;
1462 mbuf_t last;
1463 int error = 0;
1464
1465 error = flow_divert_packet_init(fd_cb, FLOW_DIVERT_PKT_DATA, &packet);
1466 if (error) {
1467 FDLOG(LOG_ERR, fd_cb, "flow_divert_packet_init failed: %d", error);
1468 return error;
1469 }
1470
1471 if (toaddr != NULL) {
1472 error = flow_divert_append_target_endpoint_tlv(packet, toaddr);
1473 if (error) {
1474 FDLOG(LOG_ERR, fd_cb, "flow_divert_append_target_endpoint_tlv() failed: %d", error);
1475 return error;
1476 }
1477 }
1478
1479 if (data_len > 0 && data != NULL) {
1480 last = m_last(packet);
1481 mbuf_setnext(last, data);
1482 mbuf_pkthdr_adjustlen(packet, data_len);
1483 }
1484 error = flow_divert_send_packet(fd_cb, packet, force);
1485
1486 if (error) {
1487 mbuf_setnext(last, NULL);
1488 mbuf_freem(packet);
1489 } else {
1490 fd_cb->bytes_sent += data_len;
1491 flow_divert_add_data_statistics(fd_cb, data_len, TRUE);
1492 }
1493
1494 return error;
1495 }
1496
1497 static void
1498 flow_divert_send_buffered_data(struct flow_divert_pcb *fd_cb, Boolean force)
1499 {
1500 size_t to_send;
1501 size_t sent = 0;
1502 int error = 0;
1503 mbuf_t buffer;
1504
1505 to_send = fd_cb->so->so_snd.sb_cc;
1506 buffer = fd_cb->so->so_snd.sb_mb;
1507
1508 if (buffer == NULL && to_send > 0) {
1509 FDLOG(LOG_ERR, fd_cb, "Send buffer is NULL, but size is supposed to be %lu", to_send);
1510 return;
1511 }
1512
1513 /* Ignore the send window if force is enabled */
1514 if (!force && (to_send > fd_cb->send_window)) {
1515 to_send = fd_cb->send_window;
1516 }
1517
1518 if (SOCK_TYPE(fd_cb->so) == SOCK_STREAM) {
1519 while (sent < to_send) {
1520 mbuf_t data;
1521 size_t data_len;
1522
1523 data_len = to_send - sent;
1524 if (data_len > FLOW_DIVERT_CHUNK_SIZE) {
1525 data_len = FLOW_DIVERT_CHUNK_SIZE;
1526 }
1527
1528 error = mbuf_copym(buffer, sent, data_len, MBUF_DONTWAIT, &data);
1529 if (error) {
1530 FDLOG(LOG_ERR, fd_cb, "mbuf_copym failed: %d", error);
1531 break;
1532 }
1533
1534 error = flow_divert_send_data_packet(fd_cb, data, data_len, NULL, force);
1535 if (error) {
1536 mbuf_freem(data);
1537 break;
1538 }
1539
1540 sent += data_len;
1541 }
1542 sbdrop(&fd_cb->so->so_snd, sent);
1543 sowwakeup(fd_cb->so);
1544 } else if (SOCK_TYPE(fd_cb->so) == SOCK_DGRAM) {
1545 mbuf_t data;
1546 mbuf_t m;
1547 size_t data_len;
1548
1549 while (buffer) {
1550 struct sockaddr *toaddr = flow_divert_get_buffered_target_address(buffer);
1551
1552 m = buffer;
1553 if (toaddr != NULL) {
1554 /* look for data in the chain */
1555 do {
1556 m = m->m_next;
1557 if (m != NULL && m->m_type == MT_DATA) {
1558 break;
1559 }
1560 } while (m);
1561 if (m == NULL) {
1562 /* unexpected */
1563 FDLOG0(LOG_ERR, fd_cb, "failed to find type MT_DATA in the mbuf chain.");
1564 goto move_on;
1565 }
1566 }
1567 data_len = mbuf_pkthdr_len(m);
1568 if (data_len > 0) {
1569 FDLOG(LOG_DEBUG, fd_cb, "mbuf_copym() data_len = %lu", data_len);
1570 error = mbuf_copym(m, 0, data_len, MBUF_DONTWAIT, &data);
1571 if (error) {
1572 FDLOG(LOG_ERR, fd_cb, "mbuf_copym failed: %d", error);
1573 break;
1574 }
1575 } else {
1576 data = NULL;
1577 }
1578 error = flow_divert_send_data_packet(fd_cb, data, data_len, toaddr, force);
1579 if (error) {
1580 mbuf_freem(data);
1581 break;
1582 }
1583 sent += data_len;
1584 move_on:
1585 buffer = buffer->m_nextpkt;
1586 (void) sbdroprecord(&(fd_cb->so->so_snd));
1587 }
1588 }
1589
1590 if (sent > 0) {
1591 FDLOG(LOG_DEBUG, fd_cb, "sent %lu bytes of buffered data", sent);
1592 if (fd_cb->send_window >= sent) {
1593 fd_cb->send_window -= sent;
1594 } else {
1595 fd_cb->send_window = 0;
1596 }
1597 }
1598 }
1599
1600 static int
1601 flow_divert_send_app_data(struct flow_divert_pcb *fd_cb, mbuf_t data, struct sockaddr *toaddr)
1602 {
1603 size_t to_send = mbuf_pkthdr_len(data);
1604 int error = 0;
1605
1606 if (to_send > fd_cb->send_window) {
1607 to_send = fd_cb->send_window;
1608 }
1609
1610 if (fd_cb->so->so_snd.sb_cc > 0) {
1611 to_send = 0; /* If the send buffer is non-empty, then we can't send anything */
1612 }
1613
1614 if (SOCK_TYPE(fd_cb->so) == SOCK_STREAM) {
1615 size_t sent = 0;
1616 mbuf_t remaining_data = data;
1617 mbuf_t pkt_data = NULL;
1618 while (sent < to_send && remaining_data != NULL) {
1619 size_t pkt_data_len;
1620
1621 pkt_data = remaining_data;
1622
1623 if ((to_send - sent) > FLOW_DIVERT_CHUNK_SIZE) {
1624 pkt_data_len = FLOW_DIVERT_CHUNK_SIZE;
1625 } else {
1626 pkt_data_len = to_send - sent;
1627 }
1628
1629 if (pkt_data_len < mbuf_pkthdr_len(pkt_data)) {
1630 error = mbuf_split(pkt_data, pkt_data_len, MBUF_DONTWAIT, &remaining_data);
1631 if (error) {
1632 FDLOG(LOG_ERR, fd_cb, "mbuf_split failed: %d", error);
1633 pkt_data = NULL;
1634 break;
1635 }
1636 } else {
1637 remaining_data = NULL;
1638 }
1639
1640 error = flow_divert_send_data_packet(fd_cb, pkt_data, pkt_data_len, NULL, FALSE);
1641
1642 if (error) {
1643 break;
1644 }
1645
1646 pkt_data = NULL;
1647 sent += pkt_data_len;
1648 }
1649
1650 fd_cb->send_window -= sent;
1651
1652 error = 0;
1653
1654 if (pkt_data != NULL) {
1655 if (sbspace(&fd_cb->so->so_snd) > 0) {
1656 if (!sbappendstream(&fd_cb->so->so_snd, pkt_data)) {
1657 FDLOG(LOG_ERR, fd_cb, "sbappendstream failed with pkt_data, send buffer size = %u, send_window = %u\n",
1658 fd_cb->so->so_snd.sb_cc, fd_cb->send_window);
1659 }
1660 } else {
1661 error = ENOBUFS;
1662 }
1663 }
1664
1665 if (remaining_data != NULL) {
1666 if (sbspace(&fd_cb->so->so_snd) > 0) {
1667 if (!sbappendstream(&fd_cb->so->so_snd, remaining_data)) {
1668 FDLOG(LOG_ERR, fd_cb, "sbappendstream failed with remaining_data, send buffer size = %u, send_window = %u\n",
1669 fd_cb->so->so_snd.sb_cc, fd_cb->send_window);
1670 }
1671 } else {
1672 error = ENOBUFS;
1673 }
1674 }
1675 } else if (SOCK_TYPE(fd_cb->so) == SOCK_DGRAM) {
1676 if (to_send || mbuf_pkthdr_len(data) == 0) {
1677 error = flow_divert_send_data_packet(fd_cb, data, to_send, toaddr, FALSE);
1678 if (error) {
1679 FDLOG(LOG_ERR, fd_cb, "flow_divert_send_data_packet failed. send data size = %lu", to_send);
1680 } else {
1681 fd_cb->send_window -= to_send;
1682 }
1683 } else {
1684 /* buffer it */
1685 if (sbspace(&fd_cb->so->so_snd) >= (int)mbuf_pkthdr_len(data)) {
1686 if (toaddr != NULL) {
1687 if (!sbappendaddr(&fd_cb->so->so_snd, toaddr, data, NULL, &error)) {
1688 FDLOG(LOG_ERR, fd_cb,
1689 "sbappendaddr failed. send buffer size = %u, send_window = %u, error = %d\n",
1690 fd_cb->so->so_snd.sb_cc, fd_cb->send_window, error);
1691 }
1692 } else {
1693 if (!sbappendrecord(&fd_cb->so->so_snd, data)) {
1694 FDLOG(LOG_ERR, fd_cb,
1695 "sbappendrecord failed. send buffer size = %u, send_window = %u, error = %d\n",
1696 fd_cb->so->so_snd.sb_cc, fd_cb->send_window, error);
1697 }
1698 }
1699 } else {
1700 error = ENOBUFS;
1701 }
1702 }
1703 }
1704
1705 return error;
1706 }
1707
1708 static int
1709 flow_divert_send_read_notification(struct flow_divert_pcb *fd_cb, uint32_t read_count)
1710 {
1711 int error = 0;
1712 mbuf_t packet = NULL;
1713 uint32_t net_read_count = htonl(read_count);
1714
1715 error = flow_divert_packet_init(fd_cb, FLOW_DIVERT_PKT_READ_NOTIFY, &packet);
1716 if (error) {
1717 FDLOG(LOG_ERR, fd_cb, "failed to create a read notification packet: %d", error);
1718 goto done;
1719 }
1720
1721 error = flow_divert_packet_append_tlv(packet, FLOW_DIVERT_TLV_READ_COUNT, sizeof(net_read_count), &net_read_count);
1722 if (error) {
1723 FDLOG(LOG_ERR, fd_cb, "failed to add the read count: %d", error);
1724 goto done;
1725 }
1726
1727 error = flow_divert_send_packet(fd_cb, packet, TRUE);
1728 if (error) {
1729 goto done;
1730 }
1731
1732 done:
1733 if (error && packet != NULL) {
1734 mbuf_free(packet);
1735 }
1736
1737 return error;
1738 }
1739
1740 static int
1741 flow_divert_send_traffic_class_update(struct flow_divert_pcb *fd_cb, int traffic_class)
1742 {
1743 int error = 0;
1744 mbuf_t packet = NULL;
1745
1746 error = flow_divert_packet_init(fd_cb, FLOW_DIVERT_PKT_PROPERTIES_UPDATE, &packet);
1747 if (error) {
1748 FDLOG(LOG_ERR, fd_cb, "failed to create a properties update packet: %d", error);
1749 goto done;
1750 }
1751
1752 error = flow_divert_packet_append_tlv(packet, FLOW_DIVERT_TLV_TRAFFIC_CLASS, sizeof(traffic_class), &traffic_class);
1753 if (error) {
1754 FDLOG(LOG_ERR, fd_cb, "failed to add the traffic class: %d", error);
1755 goto done;
1756 }
1757
1758 error = flow_divert_send_packet(fd_cb, packet, TRUE);
1759 if (error) {
1760 goto done;
1761 }
1762
1763 done:
1764 if (error && packet != NULL) {
1765 mbuf_free(packet);
1766 }
1767
1768 return error;
1769 }
1770
1771 static void
1772 flow_divert_handle_connect_result(struct flow_divert_pcb *fd_cb, mbuf_t packet, int offset)
1773 {
1774 uint32_t connect_error;
1775 uint32_t ctl_unit = 0;
1776 int error = 0;
1777 struct flow_divert_group *grp = NULL;
1778 struct sockaddr_storage local_address;
1779 int out_if_index = 0;
1780 struct sockaddr_storage remote_address;
1781 uint32_t send_window;
1782 uint32_t app_data_length = 0;
1783
1784 memset(&local_address, 0, sizeof(local_address));
1785 memset(&remote_address, 0, sizeof(remote_address));
1786
1787 error = flow_divert_packet_get_tlv(packet, offset, FLOW_DIVERT_TLV_ERROR_CODE, sizeof(connect_error), &connect_error, NULL);
1788 if (error) {
1789 FDLOG(LOG_ERR, fd_cb, "failed to get the connect result: %d", error);
1790 return;
1791 }
1792
1793 FDLOG(LOG_INFO, fd_cb, "received connect result %u", connect_error);
1794
1795 error = flow_divert_packet_get_tlv(packet, offset, FLOW_DIVERT_TLV_SPACE_AVAILABLE, sizeof(send_window), &send_window, NULL);
1796 if (error) {
1797 FDLOG(LOG_ERR, fd_cb, "failed to get the send window: %d", error);
1798 return;
1799 }
1800
1801 error = flow_divert_packet_get_tlv(packet, offset, FLOW_DIVERT_TLV_CTL_UNIT, sizeof(ctl_unit), &ctl_unit, NULL);
1802 if (error) {
1803 FDLOG0(LOG_INFO, fd_cb, "No control unit provided in the connect result");
1804 }
1805
1806 error = flow_divert_packet_get_tlv(packet, offset, FLOW_DIVERT_TLV_LOCAL_ADDR, sizeof(local_address), &local_address, NULL);
1807 if (error) {
1808 FDLOG0(LOG_INFO, fd_cb, "No local address provided");
1809 }
1810
1811 error = flow_divert_packet_get_tlv(packet, offset, FLOW_DIVERT_TLV_REMOTE_ADDR, sizeof(remote_address), &remote_address, NULL);
1812 if (error) {
1813 FDLOG0(LOG_INFO, fd_cb, "No remote address provided");
1814 }
1815
1816 error = flow_divert_packet_get_tlv(packet, offset, FLOW_DIVERT_TLV_OUT_IF_INDEX, sizeof(out_if_index), &out_if_index, NULL);
1817 if (error) {
1818 FDLOG0(LOG_INFO, fd_cb, "No output if index provided");
1819 }
1820
1821 error = flow_divert_packet_get_tlv(packet, offset, FLOW_DIVERT_TLV_APP_DATA, 0, NULL, &app_data_length);
1822 if (error) {
1823 FDLOG0(LOG_INFO, fd_cb, "No application data provided in connect result");
1824 }
1825
1826 error = 0;
1827 connect_error = ntohl(connect_error);
1828 ctl_unit = ntohl(ctl_unit);
1829
1830 lck_rw_lock_shared(&g_flow_divert_group_lck);
1831
1832 if (connect_error == 0 && ctl_unit > 0) {
1833 if (ctl_unit >= GROUP_COUNT_MAX) {
1834 FDLOG(LOG_ERR, fd_cb, "Connect result contains an invalid control unit: %u", ctl_unit);
1835 error = EINVAL;
1836 } else if (g_flow_divert_groups == NULL || g_active_group_count == 0) {
1837 FDLOG0(LOG_ERR, fd_cb, "No active groups, dropping connection");
1838 error = EINVAL;
1839 } else {
1840 grp = g_flow_divert_groups[ctl_unit];
1841 if (grp == NULL) {
1842 error = ECONNRESET;
1843 }
1844 }
1845 }
1846
1847 FDLOCK(fd_cb);
1848 if (fd_cb->so != NULL) {
1849 struct inpcb *inp = NULL;
1850 struct ifnet *ifp = NULL;
1851 struct flow_divert_group *old_group;
1852
1853 socket_lock(fd_cb->so, 0);
1854
1855 if (!(fd_cb->so->so_state & SS_ISCONNECTING)) {
1856 goto done;
1857 }
1858
1859 inp = sotoinpcb(fd_cb->so);
1860
1861 if (connect_error || error) {
1862 goto set_socket_state;
1863 }
1864
1865 if (local_address.ss_family == 0 && fd_cb->local_address == NULL) {
1866 error = EINVAL;
1867 goto set_socket_state;
1868 }
1869 if (local_address.ss_family != 0 && fd_cb->local_address == NULL) {
1870 if (local_address.ss_len > sizeof(local_address)) {
1871 local_address.ss_len = sizeof(local_address);
1872 }
1873 fd_cb->local_address = dup_sockaddr((struct sockaddr *)&local_address, 1);
1874 }
1875 if (flow_divert_is_sockaddr_valid((struct sockaddr *)&local_address)) {
1876 if (inp->inp_vflag & INP_IPV4 && local_address.ss_family == AF_INET) {
1877 struct sockaddr_in *local_in_address = (struct sockaddr_in *)&local_address;
1878 inp->inp_lport = local_in_address->sin_port;
1879 memcpy(&inp->inp_laddr, &local_in_address->sin_addr, sizeof(struct in_addr));
1880 } else if (inp->inp_vflag & INP_IPV6 && local_address.ss_family == AF_INET6) {
1881 struct sockaddr_in6 *local_in6_address = (struct sockaddr_in6 *)&local_address;
1882 inp->inp_lport = local_in6_address->sin6_port;
1883 memcpy(&inp->in6p_laddr, &local_in6_address->sin6_addr, sizeof(struct in6_addr));
1884 }
1885 }
1886
1887 if (remote_address.ss_family != 0) {
1888 if (fd_cb->remote_address != NULL) {
1889 FREE(fd_cb->remote_address, M_SONAME);
1890 fd_cb->remote_address = NULL;
1891 }
1892 if (remote_address.ss_len > sizeof(remote_address)) {
1893 remote_address.ss_len = sizeof(remote_address);
1894 }
1895 fd_cb->remote_address = dup_sockaddr((struct sockaddr *)&remote_address, 1);
1896 if (flow_divert_is_sockaddr_valid((struct sockaddr *)&remote_address)) {
1897 if (inp->inp_vflag & INP_IPV4 && remote_address.ss_family == AF_INET) {
1898 struct sockaddr_in *remote_in_address = (struct sockaddr_in *)&remote_address;
1899 inp->inp_fport = remote_in_address->sin_port;
1900 memcpy(&inp->inp_faddr, &remote_in_address->sin_addr, sizeof(struct in_addr));
1901 } else if (inp->inp_vflag & INP_IPV6 && remote_address.ss_family == AF_INET6) {
1902 struct sockaddr_in6 *remote_in6_address = (struct sockaddr_in6 *)&remote_address;
1903 inp->inp_fport = remote_in6_address->sin6_port;
1904 memcpy(&inp->in6p_faddr, &remote_in6_address->sin6_addr, sizeof(struct in6_addr));
1905 }
1906 }
1907 } else {
1908 error = EINVAL;
1909 goto set_socket_state;
1910 }
1911
1912 if (app_data_length > 0) {
1913 uint8_t *app_data = NULL;
1914 MALLOC(app_data, uint8_t *, app_data_length, M_TEMP, M_WAITOK);
1915 if (app_data != NULL) {
1916 error = flow_divert_packet_get_tlv(packet, offset, FLOW_DIVERT_TLV_APP_DATA, app_data_length, app_data, NULL);
1917 if (error == 0) {
1918 FDLOG(LOG_INFO, fd_cb, "Got %u bytes of app data from the connect result", app_data_length);
1919 if (fd_cb->app_data != NULL) {
1920 FREE(fd_cb->app_data, M_TEMP);
1921 }
1922 fd_cb->app_data = app_data;
1923 fd_cb->app_data_length = app_data_length;
1924 } else {
1925 FDLOG(LOG_ERR, fd_cb, "Failed to copy %u bytes of application data from the connect result packet", app_data_length);
1926 FREE(app_data, M_TEMP);
1927 }
1928 } else {
1929 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);
1930 }
1931 }
1932
1933 ifnet_head_lock_shared();
1934 if (out_if_index > 0 && out_if_index <= if_index) {
1935 ifp = ifindex2ifnet[out_if_index];
1936 }
1937
1938 if (ifp != NULL) {
1939 inp->inp_last_outifp = ifp;
1940 } else {
1941 error = EINVAL;
1942 }
1943 ifnet_head_done();
1944
1945 if (error) {
1946 goto set_socket_state;
1947 }
1948
1949 if (fd_cb->group == NULL) {
1950 error = EINVAL;
1951 goto set_socket_state;
1952 }
1953
1954 if (grp != NULL) {
1955 old_group = fd_cb->group;
1956
1957 lck_rw_lock_exclusive(&old_group->lck);
1958 lck_rw_lock_exclusive(&grp->lck);
1959
1960 RB_REMOVE(fd_pcb_tree, &old_group->pcb_tree, fd_cb);
1961 if (RB_INSERT(fd_pcb_tree, &grp->pcb_tree, fd_cb) != NULL) {
1962 panic("group with unit %u already contains a connection with hash %u", grp->ctl_unit, fd_cb->hash);
1963 }
1964
1965 fd_cb->group = grp;
1966
1967 lck_rw_done(&grp->lck);
1968 lck_rw_done(&old_group->lck);
1969 }
1970
1971 fd_cb->send_window = ntohl(send_window);
1972
1973 set_socket_state:
1974 if (!connect_error && !error) {
1975 FDLOG0(LOG_INFO, fd_cb, "sending connect result");
1976 error = flow_divert_send_connect_result(fd_cb);
1977 }
1978
1979 if (connect_error || error) {
1980 if (!connect_error) {
1981 flow_divert_update_closed_state(fd_cb, SHUT_RDWR, FALSE);
1982 fd_cb->so->so_error = error;
1983 flow_divert_send_close_if_needed(fd_cb);
1984 } else {
1985 flow_divert_update_closed_state(fd_cb, SHUT_RDWR, TRUE);
1986 fd_cb->so->so_error = connect_error;
1987 }
1988 flow_divert_disconnect_socket(fd_cb->so);
1989 } else {
1990 #if NECP
1991 /* Update NECP client with connected five-tuple */
1992 if (!uuid_is_null(inp->necp_client_uuid)) {
1993 socket_unlock(fd_cb->so, 0);
1994 necp_client_assign_from_socket(fd_cb->so->last_pid, inp->necp_client_uuid, inp);
1995 socket_lock(fd_cb->so, 0);
1996 }
1997 #endif /* NECP */
1998
1999 flow_divert_send_buffered_data(fd_cb, FALSE);
2000 soisconnected(fd_cb->so);
2001 }
2002
2003 done:
2004 socket_unlock(fd_cb->so, 0);
2005 }
2006 FDUNLOCK(fd_cb);
2007
2008 lck_rw_done(&g_flow_divert_group_lck);
2009 }
2010
2011 static void
2012 flow_divert_handle_close(struct flow_divert_pcb *fd_cb, mbuf_t packet, int offset)
2013 {
2014 uint32_t close_error;
2015 int error = 0;
2016 int how;
2017
2018 error = flow_divert_packet_get_tlv(packet, offset, FLOW_DIVERT_TLV_ERROR_CODE, sizeof(close_error), &close_error, NULL);
2019 if (error) {
2020 FDLOG(LOG_ERR, fd_cb, "failed to get the close error: %d", error);
2021 return;
2022 }
2023
2024 error = flow_divert_packet_get_tlv(packet, offset, FLOW_DIVERT_TLV_HOW, sizeof(how), &how, NULL);
2025 if (error) {
2026 FDLOG(LOG_ERR, fd_cb, "failed to get the close how flag: %d", error);
2027 return;
2028 }
2029
2030 how = ntohl(how);
2031
2032 FDLOG(LOG_INFO, fd_cb, "close received, how = %d", how);
2033
2034 FDLOCK(fd_cb);
2035 if (fd_cb->so != NULL) {
2036 socket_lock(fd_cb->so, 0);
2037
2038 fd_cb->so->so_error = ntohl(close_error);
2039
2040 flow_divert_update_closed_state(fd_cb, how, TRUE);
2041
2042 how = flow_divert_tunnel_how_closed(fd_cb);
2043 if (how == SHUT_RDWR) {
2044 flow_divert_disconnect_socket(fd_cb->so);
2045 } else if (how == SHUT_RD) {
2046 socantrcvmore(fd_cb->so);
2047 } else if (how == SHUT_WR) {
2048 socantsendmore(fd_cb->so);
2049 }
2050
2051 socket_unlock(fd_cb->so, 0);
2052 }
2053 FDUNLOCK(fd_cb);
2054 }
2055
2056 static mbuf_t
2057 flow_divert_get_control_mbuf(struct flow_divert_pcb *fd_cb)
2058 {
2059 struct inpcb *inp = sotoinpcb(fd_cb->so);
2060 if ((inp->inp_vflag & INP_IPV4) && (inp->inp_flags & INP_RECVDSTADDR)) {
2061 struct in_addr ia = { };
2062
2063 if (fd_cb->local_address != NULL && fd_cb->local_address->sa_family == AF_INET && fd_cb->local_address->sa_len >= sizeof(struct sockaddr_in)) {
2064 struct sockaddr_in *sin = (struct sockaddr_in *)(void *)fd_cb->local_address;
2065 bcopy(&sin->sin_addr, &ia, sizeof(struct in_addr));
2066 }
2067
2068 return sbcreatecontrol((caddr_t)&ia, sizeof(ia), IP_RECVDSTADDR, IPPROTO_IP);
2069 } else if ((inp->inp_vflag & INP_IPV6) && (inp->inp_flags & IN6P_PKTINFO)) {
2070 struct in6_pktinfo pi6;
2071 memset(&pi6, 0, sizeof(pi6));
2072
2073 if (fd_cb->local_address != NULL && fd_cb->local_address->sa_family == AF_INET6 && fd_cb->local_address->sa_len >= sizeof(struct sockaddr_in6)) {
2074 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)(void *)fd_cb->local_address;
2075 bcopy(&sin6->sin6_addr, &pi6.ipi6_addr, sizeof(struct in6_addr));
2076 pi6.ipi6_ifindex = 0;
2077 }
2078
2079 return sbcreatecontrol((caddr_t)&pi6, sizeof(pi6), IPV6_PKTINFO, IPPROTO_IPV6);
2080 }
2081 return NULL;
2082 }
2083
2084 static void
2085 flow_divert_handle_data(struct flow_divert_pcb *fd_cb, mbuf_t packet, size_t offset)
2086 {
2087 FDLOCK(fd_cb);
2088 if (fd_cb->so != NULL) {
2089 int error = 0;
2090 mbuf_t data = NULL;
2091 size_t data_size;
2092 struct sockaddr_storage remote_address;
2093 boolean_t got_remote_sa = FALSE;
2094
2095 socket_lock(fd_cb->so, 0);
2096
2097 if (SOCK_TYPE(fd_cb->so) == SOCK_DGRAM) {
2098 uint32_t val_size = 0;
2099
2100 /* check if we got remote address with data */
2101 memset(&remote_address, 0, sizeof(remote_address));
2102 error = flow_divert_packet_get_tlv(packet, offset, FLOW_DIVERT_TLV_REMOTE_ADDR, sizeof(remote_address), &remote_address, &val_size);
2103 if (error || val_size > sizeof(remote_address)) {
2104 FDLOG0(LOG_INFO, fd_cb, "No remote address provided");
2105 error = 0;
2106 } else {
2107 /* validate the address */
2108 if (flow_divert_is_sockaddr_valid((struct sockaddr *)&remote_address)) {
2109 got_remote_sa = TRUE;
2110 }
2111 offset += (sizeof(uint8_t) + sizeof(uint32_t) + val_size);
2112 }
2113 }
2114
2115 data_size = (mbuf_pkthdr_len(packet) - offset);
2116
2117 FDLOG(LOG_DEBUG, fd_cb, "received %lu bytes of data", data_size);
2118
2119 error = mbuf_split(packet, offset, MBUF_DONTWAIT, &data);
2120 if (error || data == NULL) {
2121 FDLOG(LOG_ERR, fd_cb, "mbuf_split failed: %d", error);
2122 } else {
2123 if (flow_divert_check_no_cellular(fd_cb) ||
2124 flow_divert_check_no_expensive(fd_cb) ||
2125 flow_divert_check_no_constrained(fd_cb)) {
2126 flow_divert_update_closed_state(fd_cb, SHUT_RDWR, TRUE);
2127 flow_divert_send_close(fd_cb, SHUT_RDWR);
2128 flow_divert_disconnect_socket(fd_cb->so);
2129 } else if (!(fd_cb->so->so_state & SS_CANTRCVMORE)) {
2130 if (SOCK_TYPE(fd_cb->so) == SOCK_STREAM) {
2131 int appended = sbappendstream(&fd_cb->so->so_rcv, data);
2132 fd_cb->bytes_received += data_size;
2133 flow_divert_add_data_statistics(fd_cb, data_size, FALSE);
2134 fd_cb->sb_size += data_size;
2135 if (appended) {
2136 sorwakeup(fd_cb->so);
2137 }
2138 data = NULL;
2139 } else if (SOCK_TYPE(fd_cb->so) == SOCK_DGRAM) {
2140 struct sockaddr *append_sa;
2141 mbuf_t mctl;
2142
2143 if (got_remote_sa == TRUE) {
2144 error = flow_divert_dup_addr(fd_cb->so->so_proto->pr_domain->dom_family,
2145 (struct sockaddr *)&remote_address, &append_sa);
2146 } else {
2147 error = flow_divert_dup_addr(fd_cb->so->so_proto->pr_domain->dom_family,
2148 fd_cb->remote_address, &append_sa);
2149 }
2150 if (error) {
2151 FDLOG0(LOG_ERR, fd_cb, "failed to dup the socket address.");
2152 }
2153
2154 mctl = flow_divert_get_control_mbuf(fd_cb);
2155 int append_error = 0;
2156 if (sbappendaddr(&fd_cb->so->so_rcv, append_sa, data, mctl, &append_error) || append_error == EJUSTRETURN) {
2157 fd_cb->bytes_received += data_size;
2158 flow_divert_add_data_statistics(fd_cb, data_size, FALSE);
2159 fd_cb->sb_size += data_size;
2160 if (append_error == 0) {
2161 sorwakeup(fd_cb->so);
2162 }
2163 data = NULL;
2164 }
2165 if (!error) {
2166 FREE(append_sa, M_TEMP);
2167 }
2168 }
2169 }
2170 }
2171 socket_unlock(fd_cb->so, 0);
2172 }
2173 FDUNLOCK(fd_cb);
2174 }
2175
2176 static void
2177 flow_divert_handle_read_notification(struct flow_divert_pcb *fd_cb, mbuf_t packet, int offset)
2178 {
2179 uint32_t read_count;
2180 int error = 0;
2181
2182 error = flow_divert_packet_get_tlv(packet, offset, FLOW_DIVERT_TLV_READ_COUNT, sizeof(read_count), &read_count, NULL);
2183 if (error) {
2184 FDLOG(LOG_ERR, fd_cb, "failed to get the read count: %d", error);
2185 return;
2186 }
2187
2188 FDLOG(LOG_DEBUG, fd_cb, "received a read notification for %u bytes", ntohl(read_count));
2189
2190 FDLOCK(fd_cb);
2191 if (fd_cb->so != NULL) {
2192 socket_lock(fd_cb->so, 0);
2193 fd_cb->send_window += ntohl(read_count);
2194 flow_divert_send_buffered_data(fd_cb, FALSE);
2195 socket_unlock(fd_cb->so, 0);
2196 }
2197 FDUNLOCK(fd_cb);
2198 }
2199
2200 static void
2201 flow_divert_handle_group_init(struct flow_divert_group *group, mbuf_t packet, int offset)
2202 {
2203 int error = 0;
2204 uint32_t key_size = 0;
2205 int log_level;
2206 uint32_t flags = 0;
2207
2208 error = flow_divert_packet_get_tlv(packet, offset, FLOW_DIVERT_TLV_TOKEN_KEY, 0, NULL, &key_size);
2209 if (error) {
2210 FDLOG(LOG_ERR, &nil_pcb, "failed to get the key size: %d", error);
2211 return;
2212 }
2213
2214 if (key_size == 0 || key_size > FLOW_DIVERT_MAX_KEY_SIZE) {
2215 FDLOG(LOG_ERR, &nil_pcb, "Invalid key size: %u", key_size);
2216 return;
2217 }
2218
2219 error = flow_divert_packet_get_tlv(packet, offset, FLOW_DIVERT_TLV_LOG_LEVEL, sizeof(log_level), &log_level, NULL);
2220 if (!error) {
2221 nil_pcb.log_level = log_level;
2222 }
2223
2224 lck_rw_lock_exclusive(&group->lck);
2225
2226 if (group->token_key != NULL) {
2227 FREE(group->token_key, M_TEMP);
2228 group->token_key = NULL;
2229 }
2230
2231 MALLOC(group->token_key, uint8_t *, key_size, M_TEMP, M_WAITOK);
2232 error = flow_divert_packet_get_tlv(packet, offset, FLOW_DIVERT_TLV_TOKEN_KEY, key_size, group->token_key, NULL);
2233 if (error) {
2234 FDLOG(LOG_ERR, &nil_pcb, "failed to get the token key: %d", error);
2235 FREE(group->token_key, M_TEMP);
2236 group->token_key = NULL;
2237 lck_rw_done(&group->lck);
2238 return;
2239 }
2240
2241 group->token_key_size = key_size;
2242
2243 error = flow_divert_packet_get_tlv(packet, offset, FLOW_DIVERT_TLV_FLAGS, sizeof(flags), &flags, NULL);
2244 if (!error) {
2245 group->flags = flags;
2246 }
2247
2248 lck_rw_done(&group->lck);
2249 }
2250
2251 static void
2252 flow_divert_handle_properties_update(struct flow_divert_pcb *fd_cb, mbuf_t packet, int offset)
2253 {
2254 int error = 0;
2255 struct sockaddr_storage local_address;
2256 int out_if_index = 0;
2257 struct sockaddr_storage remote_address;
2258 uint32_t app_data_length = 0;
2259
2260 FDLOG0(LOG_INFO, fd_cb, "received a properties update");
2261
2262 memset(&local_address, 0, sizeof(local_address));
2263 memset(&remote_address, 0, sizeof(remote_address));
2264
2265 error = flow_divert_packet_get_tlv(packet, offset, FLOW_DIVERT_TLV_LOCAL_ADDR, sizeof(local_address), &local_address, NULL);
2266 if (error) {
2267 FDLOG0(LOG_INFO, fd_cb, "No local address provided in properties update");
2268 }
2269
2270 error = flow_divert_packet_get_tlv(packet, offset, FLOW_DIVERT_TLV_REMOTE_ADDR, sizeof(remote_address), &remote_address, NULL);
2271 if (error) {
2272 FDLOG0(LOG_INFO, fd_cb, "No remote address provided in properties update");
2273 }
2274
2275 error = flow_divert_packet_get_tlv(packet, offset, FLOW_DIVERT_TLV_OUT_IF_INDEX, sizeof(out_if_index), &out_if_index, NULL);
2276 if (error) {
2277 FDLOG0(LOG_INFO, fd_cb, "No output if index provided in properties update");
2278 }
2279
2280 error = flow_divert_packet_get_tlv(packet, offset, FLOW_DIVERT_TLV_APP_DATA, 0, NULL, &app_data_length);
2281 if (error) {
2282 FDLOG0(LOG_INFO, fd_cb, "No application data provided in properties update");
2283 }
2284
2285 FDLOCK(fd_cb);
2286 if (fd_cb->so != NULL) {
2287 socket_lock(fd_cb->so, 0);
2288
2289 if (local_address.ss_family != 0) {
2290 if (local_address.ss_len > sizeof(local_address)) {
2291 local_address.ss_len = sizeof(local_address);
2292 }
2293 if (fd_cb->local_address != NULL) {
2294 FREE(fd_cb->local_address, M_SONAME);
2295 fd_cb->local_address = NULL;
2296 }
2297 fd_cb->local_address = dup_sockaddr((struct sockaddr *)&local_address, 1);
2298 }
2299
2300 if (remote_address.ss_family != 0) {
2301 if (remote_address.ss_len > sizeof(remote_address)) {
2302 remote_address.ss_len = sizeof(remote_address);
2303 }
2304 if (fd_cb->remote_address != NULL) {
2305 FREE(fd_cb->remote_address, M_SONAME);
2306 fd_cb->remote_address = NULL;
2307 }
2308 fd_cb->remote_address = dup_sockaddr((struct sockaddr *)&remote_address, 1);
2309 }
2310
2311 if (out_if_index > 0) {
2312 struct inpcb *inp = NULL;
2313 struct ifnet *ifp = NULL;
2314
2315 inp = sotoinpcb(fd_cb->so);
2316
2317 ifnet_head_lock_shared();
2318 if (out_if_index <= if_index) {
2319 ifp = ifindex2ifnet[out_if_index];
2320 }
2321
2322 if (ifp != NULL) {
2323 inp->inp_last_outifp = ifp;
2324 }
2325 ifnet_head_done();
2326 }
2327
2328 if (app_data_length > 0) {
2329 uint8_t *app_data = NULL;
2330 MALLOC(app_data, uint8_t *, app_data_length, M_TEMP, M_WAITOK);
2331 if (app_data != NULL) {
2332 error = flow_divert_packet_get_tlv(packet, offset, FLOW_DIVERT_TLV_APP_DATA, app_data_length, app_data, NULL);
2333 if (error == 0) {
2334 if (fd_cb->app_data != NULL) {
2335 FREE(fd_cb->app_data, M_TEMP);
2336 }
2337 fd_cb->app_data = app_data;
2338 fd_cb->app_data_length = app_data_length;
2339 } else {
2340 FDLOG(LOG_ERR, fd_cb, "Failed to copy %u bytes of application data from the properties update packet", app_data_length);
2341 FREE(app_data, M_TEMP);
2342 }
2343 } else {
2344 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);
2345 }
2346 }
2347
2348 socket_unlock(fd_cb->so, 0);
2349 }
2350 FDUNLOCK(fd_cb);
2351 }
2352
2353 static void
2354 flow_divert_handle_app_map_create(struct flow_divert_group *group, mbuf_t packet, int offset)
2355 {
2356 size_t bytes_mem_size;
2357 size_t child_maps_mem_size;
2358 int cursor;
2359 int error = 0;
2360 struct flow_divert_trie new_trie;
2361 int insert_error = 0;
2362 size_t nodes_mem_size;
2363 int prefix_count = -1;
2364 int signing_id_count = 0;
2365 size_t trie_memory_size = 0;
2366
2367 lck_rw_lock_exclusive(&group->lck);
2368
2369 /* Re-set the current trie */
2370 if (group->signing_id_trie.memory != NULL) {
2371 FREE(group->signing_id_trie.memory, M_TEMP);
2372 }
2373 memset(&group->signing_id_trie, 0, sizeof(group->signing_id_trie));
2374 group->signing_id_trie.root = NULL_TRIE_IDX;
2375
2376 memset(&new_trie, 0, sizeof(new_trie));
2377
2378 /* Get the number of shared prefixes in the new set of signing ID strings */
2379 error = flow_divert_packet_get_tlv(packet, offset, FLOW_DIVERT_TLV_PREFIX_COUNT, sizeof(prefix_count), &prefix_count, NULL);
2380
2381 if (prefix_count < 0 || error) {
2382 FDLOG(LOG_ERR, &nil_pcb, "Invalid prefix count (%d) or an error occurred while reading the prefix count: %d", prefix_count, error);
2383 lck_rw_done(&group->lck);
2384 return;
2385 }
2386
2387 /* Compute the number of signing IDs and the total amount of bytes needed to store them */
2388 for (cursor = flow_divert_packet_find_tlv(packet, offset, FLOW_DIVERT_TLV_SIGNING_ID, &error, 0);
2389 cursor >= 0;
2390 cursor = flow_divert_packet_find_tlv(packet, cursor, FLOW_DIVERT_TLV_SIGNING_ID, &error, 1)) {
2391 uint32_t sid_size = 0;
2392 error = flow_divert_packet_get_tlv(packet, cursor, FLOW_DIVERT_TLV_SIGNING_ID, 0, NULL, &sid_size);
2393 if (error || sid_size == 0) {
2394 FDLOG(LOG_ERR, &nil_pcb, "Failed to get the length of the signing identifier at offset %d: %d", cursor, error);
2395 signing_id_count = 0;
2396 break;
2397 }
2398 new_trie.bytes_count += sid_size;
2399 signing_id_count++;
2400 }
2401
2402 if (signing_id_count == 0) {
2403 lck_rw_done(&group->lck);
2404 return;
2405 }
2406
2407 new_trie.nodes_count = (prefix_count + signing_id_count + 1); /* + 1 for the root node */
2408 new_trie.child_maps_count = (prefix_count + 1); /* + 1 for the root node */
2409
2410 FDLOG(LOG_INFO, &nil_pcb, "Nodes count = %lu, child maps count = %lu, bytes_count = %lu",
2411 new_trie.nodes_count, new_trie.child_maps_count, new_trie.bytes_count);
2412
2413 if (os_mul_overflow(sizeof(*new_trie.nodes), new_trie.nodes_count, &nodes_mem_size) ||
2414 os_mul3_overflow(sizeof(*new_trie.child_maps), CHILD_MAP_SIZE, new_trie.child_maps_count, &child_maps_mem_size) ||
2415 os_mul_overflow(sizeof(*new_trie.bytes), new_trie.bytes_count, &bytes_mem_size) ||
2416 os_add3_overflow(nodes_mem_size, child_maps_mem_size, bytes_mem_size, &trie_memory_size)) {
2417 FDLOG0(LOG_ERR, &nil_pcb, "Overflow while computing trie memory sizes");
2418 lck_rw_done(&group->lck);
2419 return;
2420 }
2421
2422 if (trie_memory_size > FLOW_DIVERT_MAX_TRIE_MEMORY) {
2423 FDLOG(LOG_ERR, &nil_pcb, "Trie memory size (%lu) is too big (maximum is %u)", trie_memory_size, FLOW_DIVERT_MAX_TRIE_MEMORY);
2424 lck_rw_done(&group->lck);
2425 return;
2426 }
2427
2428 MALLOC(new_trie.memory, void *, trie_memory_size, M_TEMP, M_WAITOK);
2429 if (new_trie.memory == NULL) {
2430 FDLOG(LOG_ERR, &nil_pcb, "Failed to allocate %lu bytes of memory for the signing ID trie",
2431 nodes_mem_size + child_maps_mem_size + bytes_mem_size);
2432 lck_rw_done(&group->lck);
2433 return;
2434 }
2435
2436 /* Initialize the free lists */
2437 new_trie.nodes = (struct flow_divert_trie_node *)new_trie.memory;
2438 new_trie.nodes_free_next = 0;
2439 memset(new_trie.nodes, 0, nodes_mem_size);
2440
2441 new_trie.child_maps = (uint16_t *)(void *)((uint8_t *)new_trie.memory + nodes_mem_size);
2442 new_trie.child_maps_free_next = 0;
2443 memset(new_trie.child_maps, 0xff, child_maps_mem_size);
2444
2445 new_trie.bytes = (uint8_t *)(void *)((uint8_t *)new_trie.memory + nodes_mem_size + child_maps_mem_size);
2446 new_trie.bytes_free_next = 0;
2447 memset(new_trie.bytes, 0, bytes_mem_size);
2448
2449 /* The root is an empty node */
2450 new_trie.root = trie_node_alloc(&new_trie);
2451
2452 /* Add each signing ID to the trie */
2453 for (cursor = flow_divert_packet_find_tlv(packet, offset, FLOW_DIVERT_TLV_SIGNING_ID, &error, 0);
2454 cursor >= 0;
2455 cursor = flow_divert_packet_find_tlv(packet, cursor, FLOW_DIVERT_TLV_SIGNING_ID, &error, 1)) {
2456 uint32_t sid_size = 0;
2457 error = flow_divert_packet_get_tlv(packet, cursor, FLOW_DIVERT_TLV_SIGNING_ID, 0, NULL, &sid_size);
2458 if (error || sid_size == 0) {
2459 FDLOG(LOG_ERR, &nil_pcb, "Failed to get the length of the signing identifier at offset %d while building: %d", cursor, error);
2460 insert_error = EINVAL;
2461 break;
2462 }
2463 if (new_trie.bytes_free_next + sid_size <= new_trie.bytes_count) {
2464 uint16_t new_node_idx;
2465 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);
2466 if (error) {
2467 FDLOG(LOG_ERR, &nil_pcb, "Failed to read the signing identifier at offset %d: %d", cursor, error);
2468 insert_error = EINVAL;
2469 break;
2470 }
2471 new_node_idx = flow_divert_trie_insert(&new_trie, new_trie.bytes_free_next, sid_size);
2472 if (new_node_idx == NULL_TRIE_IDX) {
2473 insert_error = EINVAL;
2474 break;
2475 }
2476 } else {
2477 FDLOG0(LOG_ERR, &nil_pcb, "No place to put signing ID for insertion");
2478 insert_error = ENOBUFS;
2479 break;
2480 }
2481 }
2482
2483 if (!insert_error) {
2484 group->signing_id_trie = new_trie;
2485 } else {
2486 FREE(new_trie.memory, M_TEMP);
2487 }
2488
2489 lck_rw_done(&group->lck);
2490 }
2491
2492 static int
2493 flow_divert_input(mbuf_t packet, struct flow_divert_group *group)
2494 {
2495 struct flow_divert_packet_header hdr;
2496 int error = 0;
2497 struct flow_divert_pcb *fd_cb;
2498
2499 if (mbuf_pkthdr_len(packet) < sizeof(hdr)) {
2500 FDLOG(LOG_ERR, &nil_pcb, "got a bad packet, length (%lu) < sizeof hdr (%lu)", mbuf_pkthdr_len(packet), sizeof(hdr));
2501 error = EINVAL;
2502 goto done;
2503 }
2504
2505 if (mbuf_pkthdr_len(packet) > FD_CTL_RCVBUFF_SIZE) {
2506 FDLOG(LOG_ERR, &nil_pcb, "got a bad packet, length (%lu) > %d", mbuf_pkthdr_len(packet), FD_CTL_RCVBUFF_SIZE);
2507 error = EINVAL;
2508 goto done;
2509 }
2510
2511 error = mbuf_copydata(packet, 0, sizeof(hdr), &hdr);
2512 if (error) {
2513 FDLOG(LOG_ERR, &nil_pcb, "mbuf_copydata failed for the header: %d", error);
2514 error = ENOBUFS;
2515 goto done;
2516 }
2517
2518 hdr.conn_id = ntohl(hdr.conn_id);
2519
2520 if (hdr.conn_id == 0) {
2521 switch (hdr.packet_type) {
2522 case FLOW_DIVERT_PKT_GROUP_INIT:
2523 flow_divert_handle_group_init(group, packet, sizeof(hdr));
2524 break;
2525 case FLOW_DIVERT_PKT_APP_MAP_CREATE:
2526 flow_divert_handle_app_map_create(group, packet, sizeof(hdr));
2527 break;
2528 default:
2529 FDLOG(LOG_WARNING, &nil_pcb, "got an unknown message type: %d", hdr.packet_type);
2530 break;
2531 }
2532 goto done;
2533 }
2534
2535 fd_cb = flow_divert_pcb_lookup(hdr.conn_id, group); /* This retains the PCB */
2536 if (fd_cb == NULL) {
2537 if (hdr.packet_type != FLOW_DIVERT_PKT_CLOSE && hdr.packet_type != FLOW_DIVERT_PKT_READ_NOTIFY) {
2538 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);
2539 }
2540 goto done;
2541 }
2542
2543 switch (hdr.packet_type) {
2544 case FLOW_DIVERT_PKT_CONNECT_RESULT:
2545 flow_divert_handle_connect_result(fd_cb, packet, sizeof(hdr));
2546 break;
2547 case FLOW_DIVERT_PKT_CLOSE:
2548 flow_divert_handle_close(fd_cb, packet, sizeof(hdr));
2549 break;
2550 case FLOW_DIVERT_PKT_DATA:
2551 flow_divert_handle_data(fd_cb, packet, sizeof(hdr));
2552 break;
2553 case FLOW_DIVERT_PKT_READ_NOTIFY:
2554 flow_divert_handle_read_notification(fd_cb, packet, sizeof(hdr));
2555 break;
2556 case FLOW_DIVERT_PKT_PROPERTIES_UPDATE:
2557 flow_divert_handle_properties_update(fd_cb, packet, sizeof(hdr));
2558 break;
2559 default:
2560 FDLOG(LOG_WARNING, fd_cb, "got an unknown message type: %d", hdr.packet_type);
2561 break;
2562 }
2563
2564 FDRELEASE(fd_cb);
2565
2566 done:
2567 mbuf_freem(packet);
2568 return error;
2569 }
2570
2571 static void
2572 flow_divert_close_all(struct flow_divert_group *group)
2573 {
2574 struct flow_divert_pcb *fd_cb;
2575 SLIST_HEAD(, flow_divert_pcb) tmp_list;
2576
2577 SLIST_INIT(&tmp_list);
2578
2579 lck_rw_lock_exclusive(&group->lck);
2580
2581 MBUFQ_DRAIN(&group->send_queue);
2582
2583 RB_FOREACH(fd_cb, fd_pcb_tree, &group->pcb_tree) {
2584 FDRETAIN(fd_cb);
2585 SLIST_INSERT_HEAD(&tmp_list, fd_cb, tmp_list_entry);
2586 }
2587
2588 lck_rw_done(&group->lck);
2589
2590 while (!SLIST_EMPTY(&tmp_list)) {
2591 fd_cb = SLIST_FIRST(&tmp_list);
2592 FDLOCK(fd_cb);
2593 SLIST_REMOVE_HEAD(&tmp_list, tmp_list_entry);
2594 if (fd_cb->so != NULL) {
2595 socket_lock(fd_cb->so, 0);
2596 flow_divert_pcb_remove(fd_cb);
2597 flow_divert_update_closed_state(fd_cb, SHUT_RDWR, TRUE);
2598 fd_cb->so->so_error = ECONNABORTED;
2599 flow_divert_disconnect_socket(fd_cb->so);
2600 socket_unlock(fd_cb->so, 0);
2601 }
2602 FDUNLOCK(fd_cb);
2603 FDRELEASE(fd_cb);
2604 }
2605 }
2606
2607 void
2608 flow_divert_detach(struct socket *so)
2609 {
2610 struct flow_divert_pcb *fd_cb = so->so_fd_pcb;
2611
2612 VERIFY((so->so_flags & SOF_FLOW_DIVERT) && so->so_fd_pcb != NULL);
2613
2614 so->so_flags &= ~SOF_FLOW_DIVERT;
2615 so->so_fd_pcb = NULL;
2616
2617 FDLOG(LOG_INFO, fd_cb, "Detaching, ref count = %d", fd_cb->ref_count);
2618
2619 if (fd_cb->group != NULL) {
2620 /* Last-ditch effort to send any buffered data */
2621 flow_divert_send_buffered_data(fd_cb, TRUE);
2622
2623 flow_divert_update_closed_state(fd_cb, SHUT_RDWR, FALSE);
2624 flow_divert_send_close_if_needed(fd_cb);
2625 /* Remove from the group */
2626 flow_divert_pcb_remove(fd_cb);
2627 }
2628
2629 socket_unlock(so, 0);
2630 FDLOCK(fd_cb);
2631 fd_cb->so = NULL;
2632 FDUNLOCK(fd_cb);
2633 socket_lock(so, 0);
2634
2635 FDRELEASE(fd_cb); /* Release the socket's reference */
2636 }
2637
2638 static int
2639 flow_divert_close(struct socket *so)
2640 {
2641 struct flow_divert_pcb *fd_cb = so->so_fd_pcb;
2642
2643 VERIFY((so->so_flags & SOF_FLOW_DIVERT) && so->so_fd_pcb != NULL);
2644
2645 FDLOG0(LOG_INFO, fd_cb, "Closing");
2646
2647 if (SOCK_TYPE(so) == SOCK_STREAM) {
2648 soisdisconnecting(so);
2649 sbflush(&so->so_rcv);
2650 }
2651
2652 flow_divert_send_buffered_data(fd_cb, TRUE);
2653 flow_divert_update_closed_state(fd_cb, SHUT_RDWR, FALSE);
2654 flow_divert_send_close_if_needed(fd_cb);
2655
2656 /* Remove from the group */
2657 flow_divert_pcb_remove(fd_cb);
2658
2659 return 0;
2660 }
2661
2662 static int
2663 flow_divert_disconnectx(struct socket *so, sae_associd_t aid,
2664 sae_connid_t cid __unused)
2665 {
2666 if (aid != SAE_ASSOCID_ANY && aid != SAE_ASSOCID_ALL) {
2667 return EINVAL;
2668 }
2669
2670 return flow_divert_close(so);
2671 }
2672
2673 static int
2674 flow_divert_shutdown(struct socket *so)
2675 {
2676 struct flow_divert_pcb *fd_cb = so->so_fd_pcb;
2677
2678 VERIFY((so->so_flags & SOF_FLOW_DIVERT) && so->so_fd_pcb != NULL);
2679
2680 FDLOG0(LOG_INFO, fd_cb, "Can't send more");
2681
2682 socantsendmore(so);
2683
2684 flow_divert_update_closed_state(fd_cb, SHUT_WR, FALSE);
2685 flow_divert_send_close_if_needed(fd_cb);
2686
2687 return 0;
2688 }
2689
2690 static int
2691 flow_divert_rcvd(struct socket *so, int flags __unused)
2692 {
2693 struct flow_divert_pcb *fd_cb = so->so_fd_pcb;
2694 uint32_t latest_sb_size;
2695 uint32_t read_count;
2696
2697 VERIFY((so->so_flags & SOF_FLOW_DIVERT) && so->so_fd_pcb != NULL);
2698
2699 latest_sb_size = fd_cb->so->so_rcv.sb_cc;
2700
2701 if (fd_cb->sb_size < latest_sb_size) {
2702 panic("flow divert rcvd event handler (%u): saved rcv buffer size (%u) is less than latest rcv buffer size (%u)",
2703 fd_cb->hash, fd_cb->sb_size, latest_sb_size);
2704 }
2705
2706 read_count = fd_cb->sb_size - latest_sb_size;
2707
2708 FDLOG(LOG_DEBUG, fd_cb, "app read %u bytes", read_count);
2709
2710 if (read_count > 0 && flow_divert_send_read_notification(fd_cb, read_count) == 0) {
2711 fd_cb->bytes_read_by_app += read_count;
2712 fd_cb->sb_size = latest_sb_size;
2713 }
2714
2715 return 0;
2716 }
2717
2718 static int
2719 flow_divert_append_target_endpoint_tlv(mbuf_t connect_packet, struct sockaddr *toaddr)
2720 {
2721 int error = 0;
2722 int port = 0;
2723
2724 if (!flow_divert_is_sockaddr_valid(toaddr)) {
2725 FDLOG(LOG_ERR, &nil_pcb, "Invalid target address, family = %u, length = %u", toaddr->sa_family, toaddr->sa_len);
2726 error = EINVAL;
2727 goto done;
2728 }
2729
2730 error = flow_divert_packet_append_tlv(connect_packet, FLOW_DIVERT_TLV_TARGET_ADDRESS, toaddr->sa_len, toaddr);
2731 if (error) {
2732 goto done;
2733 }
2734
2735 if (toaddr->sa_family == AF_INET) {
2736 port = ntohs((satosin(toaddr))->sin_port);
2737 }
2738 #if INET6
2739 else {
2740 port = ntohs((satosin6(toaddr))->sin6_port);
2741 }
2742 #endif
2743
2744 error = flow_divert_packet_append_tlv(connect_packet, FLOW_DIVERT_TLV_TARGET_PORT, sizeof(port), &port);
2745 if (error) {
2746 goto done;
2747 }
2748
2749 done:
2750 return error;
2751 }
2752
2753 struct sockaddr *
2754 flow_divert_get_buffered_target_address(mbuf_t buffer)
2755 {
2756 if (buffer != NULL && buffer->m_type == MT_SONAME) {
2757 struct sockaddr *toaddr = mtod(buffer, struct sockaddr *);
2758 if (toaddr != NULL && flow_divert_is_sockaddr_valid(toaddr)) {
2759 return toaddr;
2760 }
2761 }
2762 return NULL;
2763 }
2764
2765 static boolean_t
2766 flow_divert_is_sockaddr_valid(struct sockaddr *addr)
2767 {
2768 switch (addr->sa_family) {
2769 case AF_INET:
2770 if (addr->sa_len < sizeof(struct sockaddr_in)) {
2771 return FALSE;
2772 }
2773 break;
2774 #if INET6
2775 case AF_INET6:
2776 if (addr->sa_len < sizeof(struct sockaddr_in6)) {
2777 return FALSE;
2778 }
2779 break;
2780 #endif /* INET6 */
2781 default:
2782 return FALSE;
2783 }
2784 return TRUE;
2785 }
2786
2787 static errno_t
2788 flow_divert_inp_to_sockaddr(const struct inpcb *inp, struct sockaddr **local_socket)
2789 {
2790 int error = 0;
2791 union sockaddr_in_4_6 sin46;
2792
2793 bzero(&sin46, sizeof(sin46));
2794 if (inp->inp_vflag & INP_IPV4) {
2795 struct sockaddr_in *sin = &sin46.sin;
2796
2797 sin->sin_family = AF_INET;
2798 sin->sin_len = sizeof(*sin);
2799 sin->sin_port = inp->inp_lport;
2800 sin->sin_addr = inp->inp_laddr;
2801 } else if (inp->inp_vflag & INP_IPV6) {
2802 struct sockaddr_in6 *sin6 = &sin46.sin6;
2803
2804 sin6->sin6_len = sizeof(*sin6);
2805 sin6->sin6_family = AF_INET6;
2806 sin6->sin6_port = inp->inp_lport;
2807 sin6->sin6_addr = inp->in6p_laddr;
2808 }
2809 *local_socket = dup_sockaddr((struct sockaddr *)&sin46, 1);
2810 if (*local_socket == NULL) {
2811 error = ENOBUFS;
2812 }
2813 return error;
2814 }
2815
2816 static boolean_t
2817 flow_divert_has_pcb_local_address(const struct inpcb *inp)
2818 {
2819 return inp->inp_lport != 0;
2820 }
2821
2822 static errno_t
2823 flow_divert_dup_addr(sa_family_t family, struct sockaddr *addr,
2824 struct sockaddr **dup)
2825 {
2826 int error = 0;
2827 struct sockaddr *result;
2828 struct sockaddr_storage ss;
2829
2830 if (addr != NULL) {
2831 result = addr;
2832 } else {
2833 memset(&ss, 0, sizeof(ss));
2834 ss.ss_family = family;
2835 if (ss.ss_family == AF_INET) {
2836 ss.ss_len = sizeof(struct sockaddr_in);
2837 }
2838 #if INET6
2839 else if (ss.ss_family == AF_INET6) {
2840 ss.ss_len = sizeof(struct sockaddr_in6);
2841 }
2842 #endif /* INET6 */
2843 else {
2844 error = EINVAL;
2845 }
2846 result = (struct sockaddr *)&ss;
2847 }
2848
2849 if (!error) {
2850 *dup = dup_sockaddr(result, 1);
2851 if (*dup == NULL) {
2852 error = ENOBUFS;
2853 }
2854 }
2855
2856 return error;
2857 }
2858
2859 static void
2860 flow_divert_disconnect_socket(struct socket *so)
2861 {
2862 soisdisconnected(so);
2863 if (SOCK_TYPE(so) == SOCK_DGRAM) {
2864 struct inpcb *inp = NULL;
2865
2866 inp = sotoinpcb(so);
2867 if (inp != NULL) {
2868 #if INET6
2869 if (SOCK_CHECK_DOM(so, PF_INET6)) {
2870 in6_pcbdetach(inp);
2871 } else
2872 #endif /* INET6 */
2873 in_pcbdetach(inp);
2874 }
2875 }
2876 }
2877
2878 static errno_t
2879 flow_divert_getpeername(struct socket *so, struct sockaddr **sa)
2880 {
2881 struct flow_divert_pcb *fd_cb = so->so_fd_pcb;
2882
2883 VERIFY((so->so_flags & SOF_FLOW_DIVERT) && so->so_fd_pcb != NULL);
2884
2885 return flow_divert_dup_addr(so->so_proto->pr_domain->dom_family,
2886 fd_cb->remote_address,
2887 sa);
2888 }
2889
2890 static errno_t
2891 flow_divert_getsockaddr(struct socket *so, struct sockaddr **sa)
2892 {
2893 struct flow_divert_pcb *fd_cb = so->so_fd_pcb;
2894
2895 VERIFY((so->so_flags & SOF_FLOW_DIVERT) && so->so_fd_pcb != NULL);
2896
2897 return flow_divert_dup_addr(so->so_proto->pr_domain->dom_family,
2898 fd_cb->local_address,
2899 sa);
2900 }
2901
2902 static errno_t
2903 flow_divert_ctloutput(struct socket *so, struct sockopt *sopt)
2904 {
2905 struct flow_divert_pcb *fd_cb = so->so_fd_pcb;
2906
2907 VERIFY((so->so_flags & SOF_FLOW_DIVERT) && so->so_fd_pcb != NULL);
2908
2909 if (sopt->sopt_name == SO_TRAFFIC_CLASS) {
2910 if (sopt->sopt_dir == SOPT_SET && fd_cb->flags & FLOW_DIVERT_CONNECT_STARTED) {
2911 flow_divert_send_traffic_class_update(fd_cb, so->so_traffic_class);
2912 }
2913 }
2914
2915 if (SOCK_DOM(so) == PF_INET) {
2916 return g_tcp_protosw->pr_ctloutput(so, sopt);
2917 }
2918 #if INET6
2919 else if (SOCK_DOM(so) == PF_INET6) {
2920 return g_tcp6_protosw->pr_ctloutput(so, sopt);
2921 }
2922 #endif
2923 return 0;
2924 }
2925
2926 errno_t
2927 flow_divert_connect_out(struct socket *so, struct sockaddr *to, proc_t p)
2928 {
2929 struct flow_divert_pcb *fd_cb = so->so_fd_pcb;
2930 int error = 0;
2931 struct inpcb *inp = sotoinpcb(so);
2932 struct sockaddr_in *sinp;
2933 mbuf_t connect_packet = NULL;
2934 int do_send = 1;
2935
2936 VERIFY((so->so_flags & SOF_FLOW_DIVERT) && so->so_fd_pcb != NULL);
2937
2938 if (fd_cb->group == NULL) {
2939 error = ENETUNREACH;
2940 goto done;
2941 }
2942
2943 if (inp == NULL) {
2944 error = EINVAL;
2945 goto done;
2946 } else if (inp->inp_state == INPCB_STATE_DEAD) {
2947 if (so->so_error) {
2948 error = so->so_error;
2949 so->so_error = 0;
2950 } else {
2951 error = EINVAL;
2952 }
2953 goto done;
2954 }
2955
2956 if ((fd_cb->flags & FLOW_DIVERT_CONNECT_STARTED) && !(fd_cb->flags & FLOW_DIVERT_TRANSFERRED)) {
2957 error = EALREADY;
2958 goto done;
2959 }
2960
2961 if (fd_cb->flags & FLOW_DIVERT_TRANSFERRED) {
2962 FDLOG0(LOG_INFO, fd_cb, "fully transferred");
2963 fd_cb->flags &= ~FLOW_DIVERT_TRANSFERRED;
2964 if (fd_cb->remote_address != NULL) {
2965 soisconnected(fd_cb->so);
2966 goto done;
2967 }
2968 }
2969
2970 FDLOG0(LOG_INFO, fd_cb, "Connecting");
2971
2972 if (fd_cb->connect_packet == NULL) {
2973 if (to == NULL) {
2974 FDLOG0(LOG_ERR, fd_cb, "No destination address available when creating connect packet");
2975 error = EINVAL;
2976 goto done;
2977 }
2978
2979 sinp = (struct sockaddr_in *)(void *)to;
2980 if (sinp->sin_family == AF_INET && IN_MULTICAST(ntohl(sinp->sin_addr.s_addr))) {
2981 error = EAFNOSUPPORT;
2982 goto done;
2983 }
2984
2985 error = flow_divert_create_connect_packet(fd_cb, to, so, p, &connect_packet);
2986 if (error) {
2987 goto done;
2988 }
2989
2990 if (so->so_flags1 & SOF1_PRECONNECT_DATA) {
2991 FDLOG0(LOG_INFO, fd_cb, "Delaying sending the connect packet until send or receive");
2992 do_send = 0;
2993 }
2994 } else {
2995 FDLOG0(LOG_INFO, fd_cb, "Sending saved connect packet");
2996 connect_packet = fd_cb->connect_packet;
2997 fd_cb->connect_packet = NULL;
2998 }
2999
3000 if (do_send) {
3001 error = flow_divert_send_packet(fd_cb, connect_packet, TRUE);
3002 if (error) {
3003 goto done;
3004 }
3005
3006 fd_cb->flags |= FLOW_DIVERT_CONNECT_STARTED;
3007 } else {
3008 fd_cb->connect_packet = connect_packet;
3009 connect_packet = NULL;
3010 }
3011
3012 soisconnecting(so);
3013
3014 done:
3015 if (error && connect_packet != NULL) {
3016 mbuf_freem(connect_packet);
3017 }
3018 return error;
3019 }
3020
3021 static int
3022 flow_divert_connectx_out_common(struct socket *so, struct sockaddr *dst,
3023 struct proc *p, sae_connid_t *pcid, struct uio *auio, user_ssize_t *bytes_written)
3024 {
3025 struct inpcb *inp = sotoinpcb(so);
3026 int error;
3027
3028 if (inp == NULL) {
3029 return EINVAL;
3030 }
3031
3032 VERIFY(dst != NULL);
3033
3034 error = flow_divert_connect_out(so, dst, p);
3035
3036 if (error != 0) {
3037 return error;
3038 }
3039
3040 /* if there is data, send it */
3041 if (auio != NULL) {
3042 user_ssize_t datalen = 0;
3043
3044 socket_unlock(so, 0);
3045
3046 VERIFY(bytes_written != NULL);
3047
3048 datalen = uio_resid(auio);
3049 error = so->so_proto->pr_usrreqs->pru_sosend(so, NULL, (uio_t)auio, NULL, NULL, 0);
3050 socket_lock(so, 0);
3051
3052 if (error == 0 || error == EWOULDBLOCK) {
3053 *bytes_written = datalen - uio_resid(auio);
3054 }
3055
3056 /*
3057 * sosend returns EWOULDBLOCK if it's a non-blocking
3058 * socket or a timeout occured (this allows to return
3059 * the amount of queued data through sendit()).
3060 *
3061 * However, connectx() returns EINPROGRESS in case of a
3062 * blocking socket. So we change the return value here.
3063 */
3064 if (error == EWOULDBLOCK) {
3065 error = EINPROGRESS;
3066 }
3067 }
3068
3069 if (error == 0 && pcid != NULL) {
3070 *pcid = 1; /* there is only 1 connection for a TCP */
3071 }
3072
3073 return error;
3074 }
3075
3076 static int
3077 flow_divert_connectx_out(struct socket *so, struct sockaddr *src __unused,
3078 struct sockaddr *dst, struct proc *p, uint32_t ifscope __unused,
3079 sae_associd_t aid __unused, sae_connid_t *pcid, uint32_t flags __unused, void *arg __unused,
3080 uint32_t arglen __unused, struct uio *uio, user_ssize_t *bytes_written)
3081 {
3082 return flow_divert_connectx_out_common(so, dst, p, pcid, uio, bytes_written);
3083 }
3084
3085 #if INET6
3086 static int
3087 flow_divert_connectx6_out(struct socket *so, struct sockaddr *src __unused,
3088 struct sockaddr *dst, struct proc *p, uint32_t ifscope __unused,
3089 sae_associd_t aid __unused, sae_connid_t *pcid, uint32_t flags __unused, void *arg __unused,
3090 uint32_t arglen __unused, struct uio *uio, user_ssize_t *bytes_written)
3091 {
3092 return flow_divert_connectx_out_common(so, dst, p, pcid, uio, bytes_written);
3093 }
3094 #endif /* INET6 */
3095
3096 static int
3097 flow_divert_getconninfo(struct socket *so, sae_connid_t cid, uint32_t *flags,
3098 uint32_t *ifindex, int32_t *soerror, user_addr_t src, socklen_t *src_len,
3099 user_addr_t dst, socklen_t *dst_len, uint32_t *aux_type,
3100 user_addr_t aux_data __unused, uint32_t *aux_len)
3101 {
3102 int error = 0;
3103 struct flow_divert_pcb *fd_cb = so->so_fd_pcb;
3104 struct ifnet *ifp = NULL;
3105 struct inpcb *inp = sotoinpcb(so);
3106
3107 VERIFY((so->so_flags & SOF_FLOW_DIVERT));
3108
3109 if (so->so_fd_pcb == NULL || inp == NULL) {
3110 error = EINVAL;
3111 goto out;
3112 }
3113
3114 if (cid != SAE_CONNID_ANY && cid != SAE_CONNID_ALL && cid != 1) {
3115 error = EINVAL;
3116 goto out;
3117 }
3118
3119 ifp = inp->inp_last_outifp;
3120 *ifindex = ((ifp != NULL) ? ifp->if_index : 0);
3121 *soerror = so->so_error;
3122 *flags = 0;
3123
3124 if (so->so_state & SS_ISCONNECTED) {
3125 *flags |= (CIF_CONNECTED | CIF_PREFERRED);
3126 }
3127
3128 if (fd_cb->local_address == NULL) {
3129 struct sockaddr_in sin;
3130 bzero(&sin, sizeof(sin));
3131 sin.sin_len = sizeof(sin);
3132 sin.sin_family = AF_INET;
3133 *src_len = sin.sin_len;
3134 if (src != USER_ADDR_NULL) {
3135 error = copyout(&sin, src, sin.sin_len);
3136 if (error != 0) {
3137 goto out;
3138 }
3139 }
3140 } else {
3141 *src_len = fd_cb->local_address->sa_len;
3142 if (src != USER_ADDR_NULL) {
3143 error = copyout(fd_cb->local_address, src, fd_cb->local_address->sa_len);
3144 if (error != 0) {
3145 goto out;
3146 }
3147 }
3148 }
3149
3150 if (fd_cb->remote_address == NULL) {
3151 struct sockaddr_in sin;
3152 bzero(&sin, sizeof(sin));
3153 sin.sin_len = sizeof(sin);
3154 sin.sin_family = AF_INET;
3155 *dst_len = sin.sin_len;
3156 if (dst != USER_ADDR_NULL) {
3157 error = copyout(&sin, dst, sin.sin_len);
3158 if (error != 0) {
3159 goto out;
3160 }
3161 }
3162 } else {
3163 *dst_len = fd_cb->remote_address->sa_len;
3164 if (dst != USER_ADDR_NULL) {
3165 error = copyout(fd_cb->remote_address, dst, fd_cb->remote_address->sa_len);
3166 if (error != 0) {
3167 goto out;
3168 }
3169 }
3170 }
3171
3172 *aux_type = 0;
3173 *aux_len = 0;
3174
3175 out:
3176 return error;
3177 }
3178
3179 static int
3180 flow_divert_control(struct socket *so, u_long cmd, caddr_t data, struct ifnet *ifp __unused, struct proc *p __unused)
3181 {
3182 int error = 0;
3183
3184 switch (cmd) {
3185 case SIOCGCONNINFO32: {
3186 struct so_cinforeq32 cifr;
3187 bcopy(data, &cifr, sizeof(cifr));
3188 error = flow_divert_getconninfo(so, cifr.scir_cid, &cifr.scir_flags,
3189 &cifr.scir_ifindex, &cifr.scir_error, cifr.scir_src,
3190 &cifr.scir_src_len, cifr.scir_dst, &cifr.scir_dst_len,
3191 &cifr.scir_aux_type, cifr.scir_aux_data,
3192 &cifr.scir_aux_len);
3193 if (error == 0) {
3194 bcopy(&cifr, data, sizeof(cifr));
3195 }
3196 break;
3197 }
3198
3199 case SIOCGCONNINFO64: {
3200 struct so_cinforeq64 cifr;
3201 bcopy(data, &cifr, sizeof(cifr));
3202 error = flow_divert_getconninfo(so, cifr.scir_cid, &cifr.scir_flags,
3203 &cifr.scir_ifindex, &cifr.scir_error, cifr.scir_src,
3204 &cifr.scir_src_len, cifr.scir_dst, &cifr.scir_dst_len,
3205 &cifr.scir_aux_type, cifr.scir_aux_data,
3206 &cifr.scir_aux_len);
3207 if (error == 0) {
3208 bcopy(&cifr, data, sizeof(cifr));
3209 }
3210 break;
3211 }
3212
3213 default:
3214 error = EOPNOTSUPP;
3215 }
3216
3217 return error;
3218 }
3219
3220 static int
3221 flow_divert_in_control(struct socket *so, u_long cmd, caddr_t data, struct ifnet *ifp, struct proc *p)
3222 {
3223 int error = flow_divert_control(so, cmd, data, ifp, p);
3224
3225 if (error == EOPNOTSUPP) {
3226 error = in_control(so, cmd, data, ifp, p);
3227 }
3228
3229 return error;
3230 }
3231
3232 static int
3233 flow_divert_in6_control(struct socket *so, u_long cmd, caddr_t data, struct ifnet *ifp, struct proc *p)
3234 {
3235 int error = flow_divert_control(so, cmd, data, ifp, p);
3236
3237 if (error == EOPNOTSUPP) {
3238 error = in6_control(so, cmd, data, ifp, p);
3239 }
3240
3241 return error;
3242 }
3243
3244 static errno_t
3245 flow_divert_data_out(struct socket *so, int flags, mbuf_t data, struct sockaddr *to, mbuf_t control, struct proc *p)
3246 {
3247 struct flow_divert_pcb *fd_cb = so->so_fd_pcb;
3248 int error = 0;
3249 struct inpcb *inp;
3250
3251 VERIFY((so->so_flags & SOF_FLOW_DIVERT) && so->so_fd_pcb != NULL);
3252
3253 inp = sotoinpcb(so);
3254 if (inp == NULL || inp->inp_state == INPCB_STATE_DEAD) {
3255 error = ECONNRESET;
3256 goto done;
3257 }
3258
3259 if (control && mbuf_len(control) > 0) {
3260 error = EINVAL;
3261 goto done;
3262 }
3263
3264 if (flags & MSG_OOB) {
3265 error = EINVAL;
3266 goto done; /* We don't support OOB data */
3267 }
3268
3269 error = flow_divert_check_no_cellular(fd_cb) ||
3270 flow_divert_check_no_expensive(fd_cb) ||
3271 flow_divert_check_no_constrained(fd_cb);
3272 if (error) {
3273 goto done;
3274 }
3275
3276 /* Implicit connect */
3277 if (!(fd_cb->flags & FLOW_DIVERT_CONNECT_STARTED)) {
3278 FDLOG0(LOG_INFO, fd_cb, "implicit connect");
3279
3280 #if CONTENT_FILTER
3281 /*
3282 * If the socket is subject to a UDP Content Filter and no remote address is passed in,
3283 * retrieve the CFIL saved remote address from the mbuf and use it.
3284 */
3285 if (to == NULL && so->so_cfil_db) {
3286 struct sockaddr *cfil_faddr = NULL;
3287 struct m_tag *cfil_tag = cfil_udp_get_socket_state(data, NULL, NULL, &cfil_faddr);
3288 if (cfil_tag) {
3289 to = (struct sockaddr *)(void *)cfil_faddr;
3290 }
3291 FDLOG(LOG_INFO, fd_cb, "Using remote address from CFIL saved state: %p", to);
3292 }
3293 #endif
3294 error = flow_divert_connect_out(so, to, p);
3295 if (error) {
3296 goto done;
3297 }
3298
3299 if (so->so_flags1 & SOF1_DATA_IDEMPOTENT) {
3300 /* Open up the send window so that the data will get sent right away */
3301 fd_cb->send_window = mbuf_pkthdr_len(data);
3302 }
3303 }
3304
3305 FDLOG(LOG_DEBUG, fd_cb, "app wrote %lu bytes", mbuf_pkthdr_len(data));
3306
3307 fd_cb->bytes_written_by_app += mbuf_pkthdr_len(data);
3308 error = flow_divert_send_app_data(fd_cb, data, to);
3309 if (error) {
3310 goto done;
3311 }
3312
3313 data = NULL;
3314
3315 if (flags & PRUS_EOF) {
3316 flow_divert_shutdown(so);
3317 }
3318
3319 done:
3320 if (data) {
3321 mbuf_freem(data);
3322 }
3323 if (control) {
3324 mbuf_free(control);
3325 }
3326 return error;
3327 }
3328
3329 static int
3330 flow_divert_preconnect(struct socket *so)
3331 {
3332 struct flow_divert_pcb *fd_cb = so->so_fd_pcb;
3333 int error = 0;
3334
3335 if (!(fd_cb->flags & FLOW_DIVERT_CONNECT_STARTED) && fd_cb->connect_packet != NULL) {
3336 FDLOG0(LOG_INFO, fd_cb, "Pre-connect read: sending saved connect packet");
3337 mbuf_t connect_packet = fd_cb->connect_packet;
3338 fd_cb->connect_packet = NULL;
3339
3340 error = flow_divert_send_packet(fd_cb, connect_packet, TRUE);
3341 if (error) {
3342 mbuf_freem(connect_packet);
3343 }
3344
3345 fd_cb->flags |= FLOW_DIVERT_CONNECT_STARTED;
3346 }
3347
3348 soclearfastopen(so);
3349
3350 return error;
3351 }
3352
3353 static void
3354 flow_divert_set_protosw(struct socket *so)
3355 {
3356 so->so_flags |= SOF_FLOW_DIVERT;
3357 if (SOCK_DOM(so) == PF_INET) {
3358 so->so_proto = &g_flow_divert_in_protosw;
3359 }
3360 #if INET6
3361 else {
3362 so->so_proto = (struct protosw *)&g_flow_divert_in6_protosw;
3363 }
3364 #endif /* INET6 */
3365 }
3366
3367 static void
3368 flow_divert_set_udp_protosw(struct socket *so)
3369 {
3370 so->so_flags |= SOF_FLOW_DIVERT;
3371 if (SOCK_DOM(so) == PF_INET) {
3372 so->so_proto = &g_flow_divert_in_udp_protosw;
3373 }
3374 #if INET6
3375 else {
3376 so->so_proto = (struct protosw *)&g_flow_divert_in6_udp_protosw;
3377 }
3378 #endif /* INET6 */
3379 }
3380
3381 static errno_t
3382 flow_divert_attach(struct socket *so, uint32_t flow_id, uint32_t ctl_unit)
3383 {
3384 int error = 0;
3385 struct flow_divert_pcb *fd_cb = NULL;
3386 struct ifnet *ifp = NULL;
3387 struct inpcb *inp = NULL;
3388 struct socket *old_so;
3389 mbuf_t recv_data = NULL;
3390
3391 socket_unlock(so, 0);
3392
3393 FDLOG(LOG_INFO, &nil_pcb, "Attaching socket to flow %u", flow_id);
3394
3395 /* Find the flow divert control block */
3396 lck_rw_lock_shared(&g_flow_divert_group_lck);
3397 if (g_flow_divert_groups != NULL && g_active_group_count > 0) {
3398 struct flow_divert_group *group = g_flow_divert_groups[ctl_unit];
3399 if (group != NULL) {
3400 fd_cb = flow_divert_pcb_lookup(flow_id, group);
3401 }
3402 }
3403 lck_rw_done(&g_flow_divert_group_lck);
3404
3405 if (fd_cb == NULL) {
3406 error = ENOENT;
3407 goto done;
3408 }
3409
3410 FDLOCK(fd_cb);
3411
3412 /* Dis-associate the flow divert control block from its current socket */
3413 old_so = fd_cb->so;
3414
3415 inp = sotoinpcb(old_so);
3416
3417 VERIFY(inp != NULL);
3418
3419 socket_lock(old_so, 0);
3420 flow_divert_disconnect_socket(old_so);
3421 old_so->so_flags &= ~SOF_FLOW_DIVERT;
3422 old_so->so_fd_pcb = NULL;
3423 if (SOCK_TYPE(old_so) == SOCK_STREAM) {
3424 old_so->so_proto = pffindproto(SOCK_DOM(old_so), IPPROTO_TCP, SOCK_STREAM);
3425 } else if (SOCK_TYPE(old_so) == SOCK_DGRAM) {
3426 old_so->so_proto = pffindproto(SOCK_DOM(old_so), IPPROTO_UDP, SOCK_DGRAM);
3427 }
3428 fd_cb->so = NULL;
3429 /* Save the output interface */
3430 ifp = inp->inp_last_outifp;
3431 if (old_so->so_rcv.sb_cc > 0) {
3432 error = mbuf_dup(old_so->so_rcv.sb_mb, MBUF_DONTWAIT, &recv_data);
3433 sbflush(&old_so->so_rcv);
3434 }
3435 socket_unlock(old_so, 0);
3436
3437 /* Associate the new socket with the flow divert control block */
3438 socket_lock(so, 0);
3439 so->so_fd_pcb = fd_cb;
3440 inp = sotoinpcb(so);
3441 inp->inp_last_outifp = ifp;
3442 if (recv_data != NULL) {
3443 if (sbappendstream(&so->so_rcv, recv_data)) {
3444 sorwakeup(so);
3445 }
3446 }
3447 flow_divert_set_protosw(so);
3448 socket_unlock(so, 0);
3449
3450 fd_cb->so = so;
3451 fd_cb->flags |= FLOW_DIVERT_TRANSFERRED;
3452
3453 FDUNLOCK(fd_cb);
3454
3455 done:
3456 socket_lock(so, 0);
3457
3458 if (fd_cb != NULL) {
3459 FDRELEASE(fd_cb); /* Release the reference obtained via flow_divert_pcb_lookup */
3460 }
3461
3462 return error;
3463 }
3464
3465 errno_t
3466 flow_divert_implicit_data_out(struct socket *so, int flags, mbuf_t data, struct sockaddr *to, mbuf_t control, struct proc *p)
3467 {
3468 struct flow_divert_pcb *fd_cb = so->so_fd_pcb;
3469 struct inpcb *inp;
3470 int error = 0;
3471
3472 inp = sotoinpcb(so);
3473 if (inp == NULL) {
3474 return EINVAL;
3475 }
3476
3477 if (fd_cb == NULL) {
3478 uint32_t fd_ctl_unit = necp_socket_get_flow_divert_control_unit(inp);
3479 if (fd_ctl_unit > 0) {
3480 error = flow_divert_pcb_init(so, fd_ctl_unit);
3481 fd_cb = so->so_fd_pcb;
3482 if (error != 0 || fd_cb == NULL) {
3483 goto done;
3484 }
3485 } else {
3486 error = ENETDOWN;
3487 goto done;
3488 }
3489 }
3490 return flow_divert_data_out(so, flags, data, to, control, p);
3491
3492 done:
3493 if (data) {
3494 mbuf_freem(data);
3495 }
3496 if (control) {
3497 mbuf_free(control);
3498 }
3499
3500 return error;
3501 }
3502
3503 errno_t
3504 flow_divert_pcb_init(struct socket *so, uint32_t ctl_unit)
3505 {
3506 errno_t error = 0;
3507 struct flow_divert_pcb *fd_cb;
3508
3509 if (so->so_flags & SOF_FLOW_DIVERT) {
3510 return EALREADY;
3511 }
3512
3513 fd_cb = flow_divert_pcb_create(so);
3514 if (fd_cb != NULL) {
3515 error = flow_divert_pcb_insert(fd_cb, ctl_unit);
3516 if (error) {
3517 FDLOG(LOG_ERR, fd_cb, "pcb insert failed: %d", error);
3518 FDRELEASE(fd_cb);
3519 } else {
3520 fd_cb->control_group_unit = ctl_unit;
3521 so->so_fd_pcb = fd_cb;
3522
3523 if (SOCK_TYPE(so) == SOCK_STREAM) {
3524 flow_divert_set_protosw(so);
3525 } else if (SOCK_TYPE(so) == SOCK_DGRAM) {
3526 flow_divert_set_udp_protosw(so);
3527 }
3528
3529 FDLOG0(LOG_INFO, fd_cb, "Created");
3530 }
3531 } else {
3532 error = ENOMEM;
3533 }
3534
3535 return error;
3536 }
3537
3538 errno_t
3539 flow_divert_token_set(struct socket *so, struct sockopt *sopt)
3540 {
3541 uint32_t ctl_unit = 0;
3542 uint32_t key_unit = 0;
3543 uint32_t flow_id = 0;
3544 int error = 0;
3545 int hmac_error = 0;
3546 mbuf_t token = NULL;
3547
3548 if (so->so_flags & SOF_FLOW_DIVERT) {
3549 error = EALREADY;
3550 goto done;
3551 }
3552
3553 if (g_init_result) {
3554 FDLOG(LOG_ERR, &nil_pcb, "flow_divert_init failed (%d), cannot use flow divert", g_init_result);
3555 error = ENOPROTOOPT;
3556 goto done;
3557 }
3558
3559 if ((SOCK_TYPE(so) != SOCK_STREAM && SOCK_TYPE(so) != SOCK_DGRAM) ||
3560 (SOCK_PROTO(so) != IPPROTO_TCP && SOCK_PROTO(so) != IPPROTO_UDP) ||
3561 (SOCK_DOM(so) != PF_INET
3562 #if INET6
3563 && SOCK_DOM(so) != PF_INET6
3564 #endif
3565 )) {
3566 error = EINVAL;
3567 goto done;
3568 } else {
3569 if (SOCK_TYPE(so) == SOCK_STREAM && SOCK_PROTO(so) == IPPROTO_TCP) {
3570 struct tcpcb *tp = sototcpcb(so);
3571 if (tp == NULL || tp->t_state != TCPS_CLOSED) {
3572 error = EINVAL;
3573 goto done;
3574 }
3575 }
3576 }
3577
3578 error = soopt_getm(sopt, &token);
3579 if (error) {
3580 token = NULL;
3581 goto done;
3582 }
3583
3584 error = soopt_mcopyin(sopt, token);
3585 if (error) {
3586 token = NULL;
3587 goto done;
3588 }
3589
3590 error = flow_divert_packet_get_tlv(token, 0, FLOW_DIVERT_TLV_KEY_UNIT, sizeof(key_unit), (void *)&key_unit, NULL);
3591 if (!error) {
3592 key_unit = ntohl(key_unit);
3593 if (key_unit >= GROUP_COUNT_MAX) {
3594 key_unit = 0;
3595 }
3596 } else if (error != ENOENT) {
3597 FDLOG(LOG_ERR, &nil_pcb, "Failed to get the key unit from the token: %d", error);
3598 goto done;
3599 } else {
3600 key_unit = 0;
3601 }
3602
3603 error = flow_divert_packet_get_tlv(token, 0, FLOW_DIVERT_TLV_CTL_UNIT, sizeof(ctl_unit), (void *)&ctl_unit, NULL);
3604 if (error) {
3605 FDLOG(LOG_ERR, &nil_pcb, "Failed to get the control socket unit from the token: %d", error);
3606 goto done;
3607 }
3608
3609 /* A valid kernel control unit is required */
3610 ctl_unit = ntohl(ctl_unit);
3611 if (ctl_unit == 0 || ctl_unit >= GROUP_COUNT_MAX) {
3612 FDLOG(LOG_ERR, &nil_pcb, "Got an invalid control socket unit: %u", ctl_unit);
3613 error = EINVAL;
3614 goto done;
3615 }
3616
3617 socket_unlock(so, 0);
3618 hmac_error = flow_divert_packet_verify_hmac(token, (key_unit != 0 ? key_unit : ctl_unit));
3619 socket_lock(so, 0);
3620
3621 if (hmac_error && hmac_error != ENOENT) {
3622 FDLOG(LOG_ERR, &nil_pcb, "HMAC verfication failed: %d", hmac_error);
3623 error = hmac_error;
3624 goto done;
3625 }
3626
3627 error = flow_divert_packet_get_tlv(token, 0, FLOW_DIVERT_TLV_FLOW_ID, sizeof(flow_id), (void *)&flow_id, NULL);
3628 if (error && error != ENOENT) {
3629 FDLOG(LOG_ERR, &nil_pcb, "Failed to get the flow ID from the token: %d", error);
3630 goto done;
3631 }
3632
3633 if (flow_id == 0) {
3634 error = flow_divert_pcb_init(so, ctl_unit);
3635 if (error == 0) {
3636 struct flow_divert_pcb *fd_cb = so->so_fd_pcb;
3637 int log_level = LOG_NOTICE;
3638
3639 error = flow_divert_packet_get_tlv(token, 0, FLOW_DIVERT_TLV_LOG_LEVEL,
3640 sizeof(log_level), &log_level, NULL);
3641 if (error == 0) {
3642 fd_cb->log_level = log_level;
3643 }
3644 error = 0;
3645
3646 fd_cb->connect_token = token;
3647 token = NULL;
3648 }
3649 } else {
3650 error = flow_divert_attach(so, flow_id, ctl_unit);
3651 }
3652
3653 if (hmac_error == 0) {
3654 struct flow_divert_pcb *fd_cb = so->so_fd_pcb;
3655 if (fd_cb != NULL) {
3656 fd_cb->flags |= FLOW_DIVERT_HAS_HMAC;
3657 }
3658 }
3659
3660 done:
3661 if (token != NULL) {
3662 mbuf_freem(token);
3663 }
3664
3665 return error;
3666 }
3667
3668 errno_t
3669 flow_divert_token_get(struct socket *so, struct sockopt *sopt)
3670 {
3671 uint32_t ctl_unit;
3672 int error = 0;
3673 uint8_t hmac[SHA_DIGEST_LENGTH];
3674 struct flow_divert_pcb *fd_cb = so->so_fd_pcb;
3675 mbuf_t token = NULL;
3676 struct flow_divert_group *control_group = NULL;
3677
3678 if (!(so->so_flags & SOF_FLOW_DIVERT)) {
3679 error = EINVAL;
3680 goto done;
3681 }
3682
3683 VERIFY((so->so_flags & SOF_FLOW_DIVERT) && so->so_fd_pcb != NULL);
3684
3685 if (fd_cb->group == NULL) {
3686 error = EINVAL;
3687 goto done;
3688 }
3689
3690 error = mbuf_gethdr(MBUF_DONTWAIT, MBUF_TYPE_HEADER, &token);
3691 if (error) {
3692 FDLOG(LOG_ERR, fd_cb, "failed to allocate the header mbuf: %d", error);
3693 goto done;
3694 }
3695
3696 ctl_unit = htonl(fd_cb->group->ctl_unit);
3697
3698 error = flow_divert_packet_append_tlv(token, FLOW_DIVERT_TLV_CTL_UNIT, sizeof(ctl_unit), &ctl_unit);
3699 if (error) {
3700 goto done;
3701 }
3702
3703 error = flow_divert_packet_append_tlv(token, FLOW_DIVERT_TLV_FLOW_ID, sizeof(fd_cb->hash), &fd_cb->hash);
3704 if (error) {
3705 goto done;
3706 }
3707
3708 if (fd_cb->app_data != NULL) {
3709 error = flow_divert_packet_append_tlv(token, FLOW_DIVERT_TLV_APP_DATA, fd_cb->app_data_length, fd_cb->app_data);
3710 if (error) {
3711 goto done;
3712 }
3713 }
3714
3715 socket_unlock(so, 0);
3716 lck_rw_lock_shared(&g_flow_divert_group_lck);
3717
3718 if (g_flow_divert_groups != NULL && g_active_group_count > 0 &&
3719 fd_cb->control_group_unit > 0 && fd_cb->control_group_unit < GROUP_COUNT_MAX) {
3720 control_group = g_flow_divert_groups[fd_cb->control_group_unit];
3721 }
3722
3723 if (control_group != NULL) {
3724 lck_rw_lock_shared(&control_group->lck);
3725 ctl_unit = htonl(control_group->ctl_unit);
3726 error = flow_divert_packet_append_tlv(token, FLOW_DIVERT_TLV_KEY_UNIT, sizeof(ctl_unit), &ctl_unit);
3727 if (!error) {
3728 error = flow_divert_packet_compute_hmac(token, control_group, hmac);
3729 }
3730 lck_rw_done(&control_group->lck);
3731 } else {
3732 error = ENOPROTOOPT;
3733 }
3734
3735 lck_rw_done(&g_flow_divert_group_lck);
3736 socket_lock(so, 0);
3737
3738 if (error) {
3739 goto done;
3740 }
3741
3742 error = flow_divert_packet_append_tlv(token, FLOW_DIVERT_TLV_HMAC, sizeof(hmac), hmac);
3743 if (error) {
3744 goto done;
3745 }
3746
3747 if (sopt->sopt_val == USER_ADDR_NULL) {
3748 /* If the caller passed NULL to getsockopt, just set the size of the token and return */
3749 sopt->sopt_valsize = mbuf_pkthdr_len(token);
3750 goto done;
3751 }
3752
3753 error = soopt_mcopyout(sopt, token);
3754 if (error) {
3755 token = NULL; /* For some reason, soopt_mcopyout() frees the mbuf if it fails */
3756 goto done;
3757 }
3758
3759 done:
3760 if (token != NULL) {
3761 mbuf_freem(token);
3762 }
3763
3764 return error;
3765 }
3766
3767 static errno_t
3768 flow_divert_kctl_connect(kern_ctl_ref kctlref __unused, struct sockaddr_ctl *sac, void **unitinfo)
3769 {
3770 struct flow_divert_group *new_group = NULL;
3771 int error = 0;
3772
3773 if (sac->sc_unit >= GROUP_COUNT_MAX) {
3774 error = EINVAL;
3775 goto done;
3776 }
3777
3778 *unitinfo = NULL;
3779
3780 MALLOC_ZONE(new_group, struct flow_divert_group *, sizeof(*new_group), M_FLOW_DIVERT_GROUP, M_WAITOK);
3781 if (new_group == NULL) {
3782 error = ENOBUFS;
3783 goto done;
3784 }
3785
3786 memset(new_group, 0, sizeof(*new_group));
3787
3788 lck_rw_init(&new_group->lck, flow_divert_mtx_grp, flow_divert_mtx_attr);
3789 RB_INIT(&new_group->pcb_tree);
3790 new_group->ctl_unit = sac->sc_unit;
3791 MBUFQ_INIT(&new_group->send_queue);
3792 new_group->signing_id_trie.root = NULL_TRIE_IDX;
3793
3794 lck_rw_lock_exclusive(&g_flow_divert_group_lck);
3795
3796 if (g_flow_divert_groups == NULL) {
3797 MALLOC(g_flow_divert_groups,
3798 struct flow_divert_group **,
3799 GROUP_COUNT_MAX * sizeof(struct flow_divert_group *),
3800 M_TEMP,
3801 M_WAITOK | M_ZERO);
3802 }
3803
3804 if (g_flow_divert_groups == NULL) {
3805 error = ENOBUFS;
3806 } else if (g_flow_divert_groups[sac->sc_unit] != NULL) {
3807 error = EALREADY;
3808 } else {
3809 g_flow_divert_groups[sac->sc_unit] = new_group;
3810 g_active_group_count++;
3811 }
3812
3813 lck_rw_done(&g_flow_divert_group_lck);
3814
3815 *unitinfo = new_group;
3816
3817 done:
3818 if (error != 0 && new_group != NULL) {
3819 FREE_ZONE(new_group, sizeof(*new_group), M_FLOW_DIVERT_GROUP);
3820 }
3821 return error;
3822 }
3823
3824 static errno_t
3825 flow_divert_kctl_disconnect(kern_ctl_ref kctlref __unused, uint32_t unit, void *unitinfo)
3826 {
3827 struct flow_divert_group *group = NULL;
3828 errno_t error = 0;
3829
3830 if (unit >= GROUP_COUNT_MAX) {
3831 return EINVAL;
3832 }
3833
3834 FDLOG(LOG_INFO, &nil_pcb, "disconnecting group %d", unit);
3835
3836 lck_rw_lock_exclusive(&g_flow_divert_group_lck);
3837
3838 if (g_flow_divert_groups == NULL || g_active_group_count == 0) {
3839 panic("flow divert group %u is disconnecting, but no groups are active (groups = %p, active count = %u", unit,
3840 g_flow_divert_groups, g_active_group_count);
3841 }
3842
3843 group = g_flow_divert_groups[unit];
3844
3845 if (group != (struct flow_divert_group *)unitinfo) {
3846 panic("group with unit %d (%p) != unit info (%p)", unit, group, unitinfo);
3847 }
3848
3849 g_flow_divert_groups[unit] = NULL;
3850 g_active_group_count--;
3851
3852 if (g_active_group_count == 0) {
3853 FREE(g_flow_divert_groups, M_TEMP);
3854 g_flow_divert_groups = NULL;
3855 }
3856
3857 lck_rw_done(&g_flow_divert_group_lck);
3858
3859 if (group != NULL) {
3860 flow_divert_close_all(group);
3861
3862 lck_rw_lock_exclusive(&group->lck);
3863
3864 if (group->token_key != NULL) {
3865 memset(group->token_key, 0, group->token_key_size);
3866 FREE(group->token_key, M_TEMP);
3867 group->token_key = NULL;
3868 group->token_key_size = 0;
3869 }
3870
3871 /* Re-set the current trie */
3872 if (group->signing_id_trie.memory != NULL) {
3873 FREE(group->signing_id_trie.memory, M_TEMP);
3874 }
3875 memset(&group->signing_id_trie, 0, sizeof(group->signing_id_trie));
3876 group->signing_id_trie.root = NULL_TRIE_IDX;
3877
3878 lck_rw_done(&group->lck);
3879
3880 FREE_ZONE(group, sizeof(*group), M_FLOW_DIVERT_GROUP);
3881 } else {
3882 error = EINVAL;
3883 }
3884
3885 return error;
3886 }
3887
3888 static errno_t
3889 flow_divert_kctl_send(kern_ctl_ref kctlref __unused, uint32_t unit __unused, void *unitinfo, mbuf_t m, int flags __unused)
3890 {
3891 return flow_divert_input(m, (struct flow_divert_group *)unitinfo);
3892 }
3893
3894 static void
3895 flow_divert_kctl_rcvd(kern_ctl_ref kctlref __unused, uint32_t unit __unused, void *unitinfo, int flags __unused)
3896 {
3897 struct flow_divert_group *group = (struct flow_divert_group *)unitinfo;
3898
3899 if (!OSTestAndClear(GROUP_BIT_CTL_ENQUEUE_BLOCKED, &group->atomic_bits)) {
3900 struct flow_divert_pcb *fd_cb;
3901 SLIST_HEAD(, flow_divert_pcb) tmp_list;
3902
3903 lck_rw_lock_shared(&g_flow_divert_group_lck);
3904 lck_rw_lock_exclusive(&group->lck);
3905
3906 while (!MBUFQ_EMPTY(&group->send_queue)) {
3907 mbuf_t next_packet;
3908 FDLOG0(LOG_DEBUG, &nil_pcb, "trying ctl_enqueuembuf again");
3909 next_packet = MBUFQ_FIRST(&group->send_queue);
3910 int error = ctl_enqueuembuf(g_flow_divert_kctl_ref, group->ctl_unit, next_packet, CTL_DATA_EOR);
3911 if (error) {
3912 FDLOG(LOG_DEBUG, &nil_pcb, "ctl_enqueuembuf returned an error: %d", error);
3913 OSTestAndSet(GROUP_BIT_CTL_ENQUEUE_BLOCKED, &group->atomic_bits);
3914 lck_rw_done(&group->lck);
3915 lck_rw_done(&g_flow_divert_group_lck);
3916 return;
3917 }
3918 MBUFQ_DEQUEUE(&group->send_queue, next_packet);
3919 }
3920
3921 SLIST_INIT(&tmp_list);
3922
3923 RB_FOREACH(fd_cb, fd_pcb_tree, &group->pcb_tree) {
3924 FDRETAIN(fd_cb);
3925 SLIST_INSERT_HEAD(&tmp_list, fd_cb, tmp_list_entry);
3926 }
3927
3928 lck_rw_done(&group->lck);
3929
3930 SLIST_FOREACH(fd_cb, &tmp_list, tmp_list_entry) {
3931 FDLOCK(fd_cb);
3932 if (fd_cb->so != NULL) {
3933 socket_lock(fd_cb->so, 0);
3934 if (fd_cb->group != NULL) {
3935 flow_divert_send_buffered_data(fd_cb, FALSE);
3936 }
3937 socket_unlock(fd_cb->so, 0);
3938 }
3939 FDUNLOCK(fd_cb);
3940 FDRELEASE(fd_cb);
3941 }
3942
3943 lck_rw_done(&g_flow_divert_group_lck);
3944 }
3945 }
3946
3947 static int
3948 flow_divert_kctl_init(void)
3949 {
3950 struct kern_ctl_reg ctl_reg;
3951 int result;
3952
3953 memset(&ctl_reg, 0, sizeof(ctl_reg));
3954
3955 strlcpy(ctl_reg.ctl_name, FLOW_DIVERT_CONTROL_NAME, sizeof(ctl_reg.ctl_name));
3956 ctl_reg.ctl_name[sizeof(ctl_reg.ctl_name) - 1] = '\0';
3957 ctl_reg.ctl_flags = CTL_FLAG_PRIVILEGED | CTL_FLAG_REG_EXTENDED;
3958 ctl_reg.ctl_sendsize = FD_CTL_SENDBUFF_SIZE;
3959 ctl_reg.ctl_recvsize = FD_CTL_RCVBUFF_SIZE;
3960
3961 ctl_reg.ctl_connect = flow_divert_kctl_connect;
3962 ctl_reg.ctl_disconnect = flow_divert_kctl_disconnect;
3963 ctl_reg.ctl_send = flow_divert_kctl_send;
3964 ctl_reg.ctl_rcvd = flow_divert_kctl_rcvd;
3965
3966 result = ctl_register(&ctl_reg, &g_flow_divert_kctl_ref);
3967
3968 if (result) {
3969 FDLOG(LOG_ERR, &nil_pcb, "flow_divert_kctl_init - ctl_register failed: %d\n", result);
3970 return result;
3971 }
3972
3973 return 0;
3974 }
3975
3976 void
3977 flow_divert_init(void)
3978 {
3979 memset(&nil_pcb, 0, sizeof(nil_pcb));
3980 nil_pcb.log_level = LOG_NOTICE;
3981
3982 g_tcp_protosw = pffindproto(AF_INET, IPPROTO_TCP, SOCK_STREAM);
3983
3984 VERIFY(g_tcp_protosw != NULL);
3985
3986 memcpy(&g_flow_divert_in_protosw, g_tcp_protosw, sizeof(g_flow_divert_in_protosw));
3987 memcpy(&g_flow_divert_in_usrreqs, g_tcp_protosw->pr_usrreqs, sizeof(g_flow_divert_in_usrreqs));
3988
3989 g_flow_divert_in_usrreqs.pru_connect = flow_divert_connect_out;
3990 g_flow_divert_in_usrreqs.pru_connectx = flow_divert_connectx_out;
3991 g_flow_divert_in_usrreqs.pru_control = flow_divert_in_control;
3992 g_flow_divert_in_usrreqs.pru_disconnect = flow_divert_close;
3993 g_flow_divert_in_usrreqs.pru_disconnectx = flow_divert_disconnectx;
3994 g_flow_divert_in_usrreqs.pru_peeraddr = flow_divert_getpeername;
3995 g_flow_divert_in_usrreqs.pru_rcvd = flow_divert_rcvd;
3996 g_flow_divert_in_usrreqs.pru_send = flow_divert_data_out;
3997 g_flow_divert_in_usrreqs.pru_shutdown = flow_divert_shutdown;
3998 g_flow_divert_in_usrreqs.pru_sockaddr = flow_divert_getsockaddr;
3999 g_flow_divert_in_usrreqs.pru_preconnect = flow_divert_preconnect;
4000
4001 g_flow_divert_in_protosw.pr_usrreqs = &g_flow_divert_in_usrreqs;
4002 g_flow_divert_in_protosw.pr_ctloutput = flow_divert_ctloutput;
4003
4004 /*
4005 * Socket filters shouldn't attach/detach to/from this protosw
4006 * since pr_protosw is to be used instead, which points to the
4007 * real protocol; if they do, it is a bug and we should panic.
4008 */
4009 g_flow_divert_in_protosw.pr_filter_head.tqh_first =
4010 (struct socket_filter *)(uintptr_t)0xdeadbeefdeadbeef;
4011 g_flow_divert_in_protosw.pr_filter_head.tqh_last =
4012 (struct socket_filter **)(uintptr_t)0xdeadbeefdeadbeef;
4013
4014 /* UDP */
4015 g_udp_protosw = pffindproto(AF_INET, IPPROTO_UDP, SOCK_DGRAM);
4016 VERIFY(g_udp_protosw != NULL);
4017
4018 memcpy(&g_flow_divert_in_udp_protosw, g_udp_protosw, sizeof(g_flow_divert_in_udp_protosw));
4019 memcpy(&g_flow_divert_in_udp_usrreqs, g_udp_protosw->pr_usrreqs, sizeof(g_flow_divert_in_udp_usrreqs));
4020
4021 g_flow_divert_in_udp_usrreqs.pru_connect = flow_divert_connect_out;
4022 g_flow_divert_in_udp_usrreqs.pru_connectx = flow_divert_connectx_out;
4023 g_flow_divert_in_udp_usrreqs.pru_control = flow_divert_in_control;
4024 g_flow_divert_in_udp_usrreqs.pru_disconnect = flow_divert_close;
4025 g_flow_divert_in_udp_usrreqs.pru_disconnectx = flow_divert_disconnectx;
4026 g_flow_divert_in_udp_usrreqs.pru_peeraddr = flow_divert_getpeername;
4027 g_flow_divert_in_udp_usrreqs.pru_rcvd = flow_divert_rcvd;
4028 g_flow_divert_in_udp_usrreqs.pru_send = flow_divert_data_out;
4029 g_flow_divert_in_udp_usrreqs.pru_shutdown = flow_divert_shutdown;
4030 g_flow_divert_in_udp_usrreqs.pru_sockaddr = flow_divert_getsockaddr;
4031 g_flow_divert_in_udp_usrreqs.pru_sosend_list = pru_sosend_list_notsupp;
4032 g_flow_divert_in_udp_usrreqs.pru_soreceive_list = pru_soreceive_list_notsupp;
4033 g_flow_divert_in_udp_usrreqs.pru_preconnect = flow_divert_preconnect;
4034
4035 g_flow_divert_in_udp_protosw.pr_usrreqs = &g_flow_divert_in_usrreqs;
4036 g_flow_divert_in_udp_protosw.pr_ctloutput = flow_divert_ctloutput;
4037
4038 /*
4039 * Socket filters shouldn't attach/detach to/from this protosw
4040 * since pr_protosw is to be used instead, which points to the
4041 * real protocol; if they do, it is a bug and we should panic.
4042 */
4043 g_flow_divert_in_udp_protosw.pr_filter_head.tqh_first =
4044 (struct socket_filter *)(uintptr_t)0xdeadbeefdeadbeef;
4045 g_flow_divert_in_udp_protosw.pr_filter_head.tqh_last =
4046 (struct socket_filter **)(uintptr_t)0xdeadbeefdeadbeef;
4047
4048 #if INET6
4049 g_tcp6_protosw = (struct ip6protosw *)pffindproto(AF_INET6, IPPROTO_TCP, SOCK_STREAM);
4050
4051 VERIFY(g_tcp6_protosw != NULL);
4052
4053 memcpy(&g_flow_divert_in6_protosw, g_tcp6_protosw, sizeof(g_flow_divert_in6_protosw));
4054 memcpy(&g_flow_divert_in6_usrreqs, g_tcp6_protosw->pr_usrreqs, sizeof(g_flow_divert_in6_usrreqs));
4055
4056 g_flow_divert_in6_usrreqs.pru_connect = flow_divert_connect_out;
4057 g_flow_divert_in6_usrreqs.pru_connectx = flow_divert_connectx6_out;
4058 g_flow_divert_in6_usrreqs.pru_control = flow_divert_in6_control;
4059 g_flow_divert_in6_usrreqs.pru_disconnect = flow_divert_close;
4060 g_flow_divert_in6_usrreqs.pru_disconnectx = flow_divert_disconnectx;
4061 g_flow_divert_in6_usrreqs.pru_peeraddr = flow_divert_getpeername;
4062 g_flow_divert_in6_usrreqs.pru_rcvd = flow_divert_rcvd;
4063 g_flow_divert_in6_usrreqs.pru_send = flow_divert_data_out;
4064 g_flow_divert_in6_usrreqs.pru_shutdown = flow_divert_shutdown;
4065 g_flow_divert_in6_usrreqs.pru_sockaddr = flow_divert_getsockaddr;
4066 g_flow_divert_in6_usrreqs.pru_preconnect = flow_divert_preconnect;
4067
4068 g_flow_divert_in6_protosw.pr_usrreqs = &g_flow_divert_in6_usrreqs;
4069 g_flow_divert_in6_protosw.pr_ctloutput = flow_divert_ctloutput;
4070 /*
4071 * Socket filters shouldn't attach/detach to/from this protosw
4072 * since pr_protosw is to be used instead, which points to the
4073 * real protocol; if they do, it is a bug and we should panic.
4074 */
4075 g_flow_divert_in6_protosw.pr_filter_head.tqh_first =
4076 (struct socket_filter *)(uintptr_t)0xdeadbeefdeadbeef;
4077 g_flow_divert_in6_protosw.pr_filter_head.tqh_last =
4078 (struct socket_filter **)(uintptr_t)0xdeadbeefdeadbeef;
4079
4080 /* UDP6 */
4081 g_udp6_protosw = (struct ip6protosw *)pffindproto(AF_INET6, IPPROTO_UDP, SOCK_DGRAM);
4082
4083 VERIFY(g_udp6_protosw != NULL);
4084
4085 memcpy(&g_flow_divert_in6_udp_protosw, g_udp6_protosw, sizeof(g_flow_divert_in6_udp_protosw));
4086 memcpy(&g_flow_divert_in6_udp_usrreqs, g_udp6_protosw->pr_usrreqs, sizeof(g_flow_divert_in6_udp_usrreqs));
4087
4088 g_flow_divert_in6_udp_usrreqs.pru_connect = flow_divert_connect_out;
4089 g_flow_divert_in6_udp_usrreqs.pru_connectx = flow_divert_connectx6_out;
4090 g_flow_divert_in6_udp_usrreqs.pru_control = flow_divert_in6_control;
4091 g_flow_divert_in6_udp_usrreqs.pru_disconnect = flow_divert_close;
4092 g_flow_divert_in6_udp_usrreqs.pru_disconnectx = flow_divert_disconnectx;
4093 g_flow_divert_in6_udp_usrreqs.pru_peeraddr = flow_divert_getpeername;
4094 g_flow_divert_in6_udp_usrreqs.pru_rcvd = flow_divert_rcvd;
4095 g_flow_divert_in6_udp_usrreqs.pru_send = flow_divert_data_out;
4096 g_flow_divert_in6_udp_usrreqs.pru_shutdown = flow_divert_shutdown;
4097 g_flow_divert_in6_udp_usrreqs.pru_sockaddr = flow_divert_getsockaddr;
4098 g_flow_divert_in6_udp_usrreqs.pru_sosend_list = pru_sosend_list_notsupp;
4099 g_flow_divert_in6_udp_usrreqs.pru_soreceive_list = pru_soreceive_list_notsupp;
4100 g_flow_divert_in6_udp_usrreqs.pru_preconnect = flow_divert_preconnect;
4101
4102 g_flow_divert_in6_udp_protosw.pr_usrreqs = &g_flow_divert_in6_udp_usrreqs;
4103 g_flow_divert_in6_udp_protosw.pr_ctloutput = flow_divert_ctloutput;
4104 /*
4105 * Socket filters shouldn't attach/detach to/from this protosw
4106 * since pr_protosw is to be used instead, which points to the
4107 * real protocol; if they do, it is a bug and we should panic.
4108 */
4109 g_flow_divert_in6_udp_protosw.pr_filter_head.tqh_first =
4110 (struct socket_filter *)(uintptr_t)0xdeadbeefdeadbeef;
4111 g_flow_divert_in6_udp_protosw.pr_filter_head.tqh_last =
4112 (struct socket_filter **)(uintptr_t)0xdeadbeefdeadbeef;
4113 #endif /* INET6 */
4114
4115 flow_divert_grp_attr = lck_grp_attr_alloc_init();
4116 if (flow_divert_grp_attr == NULL) {
4117 FDLOG0(LOG_ERR, &nil_pcb, "lck_grp_attr_alloc_init failed");
4118 g_init_result = ENOMEM;
4119 goto done;
4120 }
4121
4122 flow_divert_mtx_grp = lck_grp_alloc_init(FLOW_DIVERT_CONTROL_NAME, flow_divert_grp_attr);
4123 if (flow_divert_mtx_grp == NULL) {
4124 FDLOG0(LOG_ERR, &nil_pcb, "lck_grp_alloc_init failed");
4125 g_init_result = ENOMEM;
4126 goto done;
4127 }
4128
4129 flow_divert_mtx_attr = lck_attr_alloc_init();
4130 if (flow_divert_mtx_attr == NULL) {
4131 FDLOG0(LOG_ERR, &nil_pcb, "lck_attr_alloc_init failed");
4132 g_init_result = ENOMEM;
4133 goto done;
4134 }
4135
4136 g_init_result = flow_divert_kctl_init();
4137 if (g_init_result) {
4138 goto done;
4139 }
4140
4141 lck_rw_init(&g_flow_divert_group_lck, flow_divert_mtx_grp, flow_divert_mtx_attr);
4142
4143 done:
4144 if (g_init_result != 0) {
4145 if (flow_divert_mtx_attr != NULL) {
4146 lck_attr_free(flow_divert_mtx_attr);
4147 flow_divert_mtx_attr = NULL;
4148 }
4149 if (flow_divert_mtx_grp != NULL) {
4150 lck_grp_free(flow_divert_mtx_grp);
4151 flow_divert_mtx_grp = NULL;
4152 }
4153 if (flow_divert_grp_attr != NULL) {
4154 lck_grp_attr_free(flow_divert_grp_attr);
4155 flow_divert_grp_attr = NULL;
4156 }
4157
4158 if (g_flow_divert_kctl_ref != NULL) {
4159 ctl_deregister(g_flow_divert_kctl_ref);
4160 g_flow_divert_kctl_ref = NULL;
4161 }
4162 }
4163 }