]> git.saurik.com Git - apple/xnu.git/blame - bsd/net/necp_client.c
xnu-7195.50.7.100.1.tar.gz
[apple/xnu.git] / bsd / net / necp_client.c
CommitLineData
39037602 1/*
f427ee49 2 * Copyright (c) 2015-2020 Apple Inc. All rights reserved.
39037602
A
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>
5ba3f43e
A
30
31#include <kern/thread_call.h>
32#include <kern/zalloc.h>
33
39037602 34#include <net/if.h>
5ba3f43e
A
35#include <net/if_var.h>
36#include <net/net_api_stats.h>
37#include <net/necp.h>
38#include <net/network_agent.h>
39#include <net/ntstat.h>
40
41#include <netinet/in_pcb.h>
cb323159 42#include <netinet/in_var.h>
39037602
A
43#include <netinet/ip.h>
44#include <netinet/ip6.h>
5ba3f43e 45#include <netinet/mp_pcb.h>
39037602 46#include <netinet/tcp_cc.h>
5ba3f43e
A
47#include <netinet/tcp_fsm.h>
48#include <netinet/tcp_cache.h>
49#include <netinet6/in6_var.h>
50
51#include <sys/domain.h>
39037602 52#include <sys/file_internal.h>
5ba3f43e
A
53#include <sys/kauth.h>
54#include <sys/kernel.h>
55#include <sys/malloc.h>
39037602 56#include <sys/poll.h>
5ba3f43e
A
57#include <sys/priv.h>
58#include <sys/protosw.h>
59#include <sys/queue.h>
60#include <sys/socket.h>
61#include <sys/socketvar.h>
62#include <sys/sysproto.h>
63#include <sys/systm.h>
64#include <sys/types.h>
65#include <sys/codesign.h>
66#include <libkern/section_keywords.h>
67
cb323159
A
68#include <os/refcnt.h>
69
39037602
A
70
71/*
72 * NECP Client Architecture
73 * ------------------------------------------------
74 * See <net/necp.c> for a discussion on NECP database architecture.
75 *
76 * Each client of NECP provides a set of parameters for a connection or network state
77 * evaluation, on which NECP policy evaluation is run. This produces a policy result
78 * which can be accessed by the originating process, along with events for when policies
79 * results have changed.
80 *
81 * ------------------------------------------------
82 * NECP Client FD
83 * ------------------------------------------------
84 * A process opens an NECP file descriptor using necp_open(). This is a very simple
85 * file descriptor, upon which the process may do the following operations:
86 * - necp_client_action(...), to add/remove/query clients
87 * - kqueue, to watch for readable events
88 * - close(), to close the client session and release all clients
89 *
90 * Client objects are allocated structures that hang off of the file descriptor. Each
91 * client contains:
92 * - Client ID, a UUID that references the client across the system
93 * - Parameters, a buffer of TLVs that describe the client's connection parameters,
94 * such as the remote and local endpoints, interface requirements, etc.
95 * - Result, a buffer of TLVs containing the current policy evaluation for the client.
96 * This result will be updated whenever a network change occurs that impacts the
97 * policy result for that client.
98 *
99 * +--------------+
100 * | NECP fd |
101 * +--------------+
102 * ||
103 * ==================================
104 * || || ||
105 * +--------------+ +--------------+ +--------------+
106 * | Client ID | | Client ID | | Client ID |
107 * | ---- | | ---- | | ---- |
108 * | Parameters | | Parameters | | Parameters |
109 * | ---- | | ---- | | ---- |
110 * | Result | | Result | | Result |
111 * +--------------+ +--------------+ +--------------+
112 *
113 * ------------------------------------------------
114 * Client Actions
115 * ------------------------------------------------
116 * - Add. Input parameters as a buffer of TLVs, and output a client ID. Allocates a
117 * new client structure on the file descriptor.
118 * - Remove. Input a client ID. Removes a client structure from the file descriptor.
119 * - Copy Parameters. Input a client ID, and output parameter TLVs.
120 * - Copy Result. Input a client ID, and output result TLVs. Alternatively, input empty
121 * client ID and get next unread client result.
122 * - Copy List. List all client IDs.
123 *
124 * ------------------------------------------------
125 * Client Policy Evaluation
126 * ------------------------------------------------
127 * Policies are evaluated for clients upon client creation, and upon update events,
128 * which are network/agent/policy changes coalesced by a timer.
129 *
130 * The policy evaluation goes through the following steps:
131 * 1. Parse client parameters.
132 * 2. Select a scoped interface if applicable. This involves using require/prohibit
133 * parameters, along with the local address, to select the most appropriate interface
134 * if not explicitly set by the client parameters.
135 * 3. Run NECP application-level policy evalution
136 * 4. Set policy result into client result buffer.
137 *
138 * ------------------------------------------------
139 * Client Observers
140 * ------------------------------------------------
141 * If necp_open() is called with the NECP_OPEN_FLAG_OBSERVER flag, and the process
142 * passes the necessary privilege check, the fd is allowed to use necp_client_action()
143 * to copy client state attached to the file descriptors of other processes, and to
144 * list all client IDs on the system.
145 */
146
147extern u_int32_t necp_debug;
148
39037602
A
149static int necpop_select(struct fileproc *, int, void *, vfs_context_t);
150static int necpop_close(struct fileglob *, vfs_context_t);
cb323159 151static int necpop_kqfilter(struct fileproc *, struct knote *, struct kevent_qos_s *);
39037602
A
152
153// Timer functions
154static int necp_timeout_microseconds = 1000 * 100; // 100ms
155static int necp_timeout_leeway_microseconds = 1000 * 500; // 500ms
5ba3f43e
A
156
157static int necp_client_fd_count = 0;
158static int necp_observer_fd_count = 0;
159static int necp_client_count = 0;
160static int necp_socket_flow_count = 0;
161static int necp_if_flow_count = 0;
162static int necp_observer_message_limit = 256;
163
cb323159
A
164os_refgrp_decl(static, necp_client_refgrp, "NECPClientRefGroup", NULL);
165
5ba3f43e
A
166SYSCTL_INT(_net_necp, NECPCTL_CLIENT_FD_COUNT, client_fd_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_client_fd_count, 0, "");
167SYSCTL_INT(_net_necp, NECPCTL_OBSERVER_FD_COUNT, observer_fd_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_observer_fd_count, 0, "");
168SYSCTL_INT(_net_necp, NECPCTL_CLIENT_COUNT, client_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_client_count, 0, "");
169SYSCTL_INT(_net_necp, NECPCTL_SOCKET_FLOW_COUNT, socket_flow_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_socket_flow_count, 0, "");
170SYSCTL_INT(_net_necp, NECPCTL_IF_FLOW_COUNT, if_flow_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_if_flow_count, 0, "");
171SYSCTL_INT(_net_necp, NECPCTL_OBSERVER_MESSAGE_LIMIT, observer_message_limit, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_observer_message_limit, 256, "");
172
0a7de745
A
173#define NECP_MAX_CLIENT_LIST_SIZE 1024 * 1024 // 1MB
174#define NECP_MAX_AGENT_ACTION_SIZE 256
5ba3f43e 175
39037602 176extern int tvtohz(struct timeval *);
5ba3f43e 177extern unsigned int get_maxmtu(struct rtentry *);
39037602
A
178
179// Parsed parameters
0a7de745
A
180#define NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR 0x00001
181#define NECP_PARSED_PARAMETERS_FIELD_REMOTE_ADDR 0x00002
182#define NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IF 0x00004
183#define NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IF 0x00008
184#define NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE 0x00010
185#define NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IFTYPE 0x00020
186#define NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT 0x00040
187#define NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT 0x00080
188#define NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT 0x00100
189#define NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT 0x00200
190#define NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE 0x00400
191#define NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT_TYPE 0x00800
192#define NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT_TYPE 0x01000
193#define NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT_TYPE 0x02000
194#define NECP_PARSED_PARAMETERS_FIELD_FLAGS 0x04000
195#define NECP_PARSED_PARAMETERS_FIELD_IP_PROTOCOL 0x08000
196#define NECP_PARSED_PARAMETERS_FIELD_EFFECTIVE_PID 0x10000
197#define NECP_PARSED_PARAMETERS_FIELD_EFFECTIVE_UUID 0x20000
198#define NECP_PARSED_PARAMETERS_FIELD_TRAFFIC_CLASS 0x40000
199#define NECP_PARSED_PARAMETERS_FIELD_LOCAL_PORT 0x80000
cb323159
A
200#define NECP_PARSED_PARAMETERS_FIELD_DELEGATED_UPID 0x100000
201#define NECP_PARSED_PARAMETERS_FIELD_ETHERTYPE 0x200000
202#define NECP_PARSED_PARAMETERS_FIELD_TRANSPORT_PROTOCOL 0x400000
203#define NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR_PREFERENCE 0x800000
39037602 204
cb323159
A
205
206#define NECP_MAX_INTERFACE_PARAMETERS 16
207#define NECP_MAX_AGENT_PARAMETERS 4
39037602
A
208struct necp_client_parsed_parameters {
209 u_int32_t valid_fields;
5ba3f43e 210 u_int32_t flags;
cb323159 211 u_int64_t delegated_upid;
39037602
A
212 union necp_sockaddr_union local_addr;
213 union necp_sockaddr_union remote_addr;
214 u_int32_t required_interface_index;
cb323159 215 char prohibited_interfaces[NECP_MAX_INTERFACE_PARAMETERS][IFXNAMSIZ];
5ba3f43e 216 u_int8_t required_interface_type;
cb323159
A
217 u_int8_t local_address_preference;
218 u_int8_t prohibited_interface_types[NECP_MAX_INTERFACE_PARAMETERS];
219 struct necp_client_parameter_netagent_type required_netagent_types[NECP_MAX_AGENT_PARAMETERS];
220 struct necp_client_parameter_netagent_type prohibited_netagent_types[NECP_MAX_AGENT_PARAMETERS];
221 struct necp_client_parameter_netagent_type preferred_netagent_types[NECP_MAX_AGENT_PARAMETERS];
222 struct necp_client_parameter_netagent_type avoided_netagent_types[NECP_MAX_AGENT_PARAMETERS];
223 uuid_t required_netagents[NECP_MAX_AGENT_PARAMETERS];
224 uuid_t prohibited_netagents[NECP_MAX_AGENT_PARAMETERS];
225 uuid_t preferred_netagents[NECP_MAX_AGENT_PARAMETERS];
226 uuid_t avoided_netagents[NECP_MAX_AGENT_PARAMETERS];
227 u_int8_t ip_protocol;
228 u_int8_t transport_protocol;
229 u_int16_t ethertype;
5ba3f43e
A
230 pid_t effective_pid;
231 uuid_t effective_uuid;
232 u_int32_t traffic_class;
39037602
A
233};
234
5ba3f43e
A
235static bool
236necp_find_matching_interface_index(struct necp_client_parsed_parameters *parsed_parameters,
0a7de745 237 u_int *return_ifindex, bool *validate_agents);
5ba3f43e
A
238
239static bool
240necp_ifnet_matches_local_address(struct ifnet *ifp, struct sockaddr *sa);
241
242static bool
243necp_ifnet_matches_parameters(struct ifnet *ifp,
0a7de745 244 struct necp_client_parsed_parameters *parsed_parameters,
cb323159 245 u_int32_t override_flags,
0a7de745 246 u_int32_t *preferred_count,
cb323159
A
247 bool secondary_interface,
248 bool require_scoped_field);
39037602
A
249
250static const struct fileops necp_fd_ops = {
cb323159
A
251 .fo_type = DTYPE_NETPOLICY,
252 .fo_read = fo_no_read,
253 .fo_write = fo_no_write,
254 .fo_ioctl = fo_no_ioctl,
255 .fo_select = necpop_select,
256 .fo_close = necpop_close,
257 .fo_drain = fo_no_drain,
39037602 258 .fo_kqfilter = necpop_kqfilter,
39037602
A
259};
260
261struct necp_client_assertion {
262 LIST_ENTRY(necp_client_assertion) assertion_chain;
263 uuid_t asserted_netagent;
264};
265
5ba3f43e
A
266struct necp_client_flow_header {
267 struct necp_tlv_header outer_header;
d9a64523
A
268 struct necp_tlv_header flow_id_tlv_header;
269 uuid_t flow_id;
5ba3f43e
A
270 struct necp_tlv_header flags_tlv_header;
271 u_int32_t flags_value;
272 struct necp_tlv_header interface_tlv_header;
273 struct necp_client_result_interface interface_value;
274} __attribute__((__packed__));
275
276struct necp_client_flow_protoctl_event_header {
277 struct necp_tlv_header protoctl_tlv_header;
278 struct necp_client_flow_protoctl_event protoctl_event;
279} __attribute__((__packed__));
280
281struct necp_client_nexus_flow_header {
282 struct necp_client_flow_header flow_header;
283 struct necp_tlv_header agent_tlv_header;
284 struct necp_client_result_netagent agent_value;
285 struct necp_tlv_header tfo_cookie_tlv_header;
286 u_int8_t tfo_cookie_value[NECP_TFO_COOKIE_LEN_MAX];
287} __attribute__((__packed__));
288
a39ff7e2 289
d9a64523
A
290struct necp_client_flow {
291 LIST_ENTRY(necp_client_flow) flow_chain;
292 unsigned invalid : 1;
293 unsigned nexus : 1; // If true, flow is a nexus; if false, flow is attached to socket
294 unsigned socket : 1;
295 unsigned viable : 1;
296 unsigned assigned : 1;
297 unsigned has_protoctl_event : 1;
298 unsigned check_tcp_heuristics : 1;
299 unsigned _reserved : 1;
300 union {
301 uuid_t nexus_agent;
302 struct {
303 void *socket_handle;
304 necp_client_flow_cb cb;
305 };
306 } u;
307 uint32_t interface_index;
f427ee49 308 u_short delegated_interface_index;
d9a64523
A
309 uint16_t interface_flags;
310 uint32_t necp_flow_flags;
311 struct necp_client_flow_protoctl_event protoctl_event;
312 union necp_sockaddr_union local_addr;
313 union necp_sockaddr_union remote_addr;
314
315 size_t assigned_results_length;
316 u_int8_t *assigned_results;
317};
318
319struct necp_client_flow_registration {
320 RB_ENTRY(necp_client_flow_registration) fd_link;
321 RB_ENTRY(necp_client_flow_registration) global_link;
322 RB_ENTRY(necp_client_flow_registration) client_link;
323 LIST_ENTRY(necp_client_flow_registration) collect_stats_chain;
324 uuid_t registration_id;
325 u_int32_t flags;
326 unsigned flow_result_read : 1;
327 unsigned defunct : 1;
328 void *interface_handle;
329 necp_client_flow_cb interface_cb;
330 struct necp_client *client;
331 LIST_HEAD(_necp_registration_flow_list, necp_client_flow) flow_list;
332 u_int64_t last_interface_details __attribute__((aligned(sizeof(u_int64_t))));
333};
334
335static int necp_client_flow_id_cmp(struct necp_client_flow_registration *flow0, struct necp_client_flow_registration *flow1);
336
337RB_HEAD(_necp_client_flow_tree, necp_client_flow_registration);
338RB_PROTOTYPE_PREV(_necp_client_flow_tree, necp_client_flow_registration, client_link, necp_client_flow_id_cmp);
339RB_GENERATE_PREV(_necp_client_flow_tree, necp_client_flow_registration, client_link, necp_client_flow_id_cmp);
340
341#define NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT 4
342#define NECP_CLIENT_MAX_INTERFACE_OPTIONS 16
343
344#define NECP_CLIENT_INTERFACE_OPTION_EXTRA_COUNT (NECP_CLIENT_MAX_INTERFACE_OPTIONS - NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT)
345
39037602 346struct necp_client {
5ba3f43e
A
347 RB_ENTRY(necp_client) link;
348 RB_ENTRY(necp_client) global_link;
5ba3f43e
A
349
350 decl_lck_mtx_data(, lock);
351 decl_lck_mtx_data(, route_lock);
cb323159 352 os_refcnt_t reference_count;
39037602
A
353
354 uuid_t client_id;
5ba3f43e 355 unsigned result_read : 1;
5ba3f43e 356 unsigned allow_multiple_flows : 1;
d9a64523 357 unsigned legacy_client_is_flow : 1;
5ba3f43e 358
5ba3f43e 359 unsigned platform_binary : 1;
39037602
A
360
361 size_t result_length;
362 u_int8_t result[NECP_MAX_CLIENT_RESULT_SIZE];
363
5ba3f43e
A
364 necp_policy_id policy_id;
365
cb323159 366 u_int8_t ip_protocol;
5ba3f43e 367 int proc_pid;
39037602 368
cb323159
A
369 u_int64_t delegated_upid;
370
d9a64523 371 struct _necp_client_flow_tree flow_registrations;
39037602
A
372 LIST_HEAD(_necp_client_assertion_list, necp_client_assertion) assertion_list;
373
5ba3f43e
A
374 struct rtentry *current_route;
375
d9a64523
A
376 struct necp_client_interface_option interface_options[NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT];
377 struct necp_client_interface_option *extra_interface_options;
378 u_int8_t interface_option_count; // Number in interface_options + extra_interface_options
379
380 struct necp_client_result_netagent failed_trigger_agent;
381
382 void *agent_handle;
39037602 383
ea3f0419
A
384 uuid_t override_euuid;
385
cb323159 386
39037602
A
387 size_t parameters_length;
388 u_int8_t parameters[0];
389};
390
5ba3f43e
A
391#define NECP_CLIENT_LOCK(_c) lck_mtx_lock(&_c->lock)
392#define NECP_CLIENT_UNLOCK(_c) lck_mtx_unlock(&_c->lock)
393#define NECP_CLIENT_ASSERT_LOCKED(_c) LCK_MTX_ASSERT(&_c->lock, LCK_MTX_ASSERT_OWNED)
394#define NECP_CLIENT_ASSERT_UNLOCKED(_c) LCK_MTX_ASSERT(&_c->lock, LCK_MTX_ASSERT_NOTOWNED)
395
396#define NECP_CLIENT_ROUTE_LOCK(_c) lck_mtx_lock(&_c->route_lock)
397#define NECP_CLIENT_ROUTE_UNLOCK(_c) lck_mtx_unlock(&_c->route_lock)
398
399static void necp_client_retain_locked(struct necp_client *client);
f427ee49 400static void necp_client_retain(struct necp_client *client);
cb323159 401
5ba3f43e 402static bool necp_client_release_locked(struct necp_client *client);
cb323159 403static bool necp_client_release(struct necp_client *client);
5ba3f43e
A
404
405static void
406necp_client_add_assertion(struct necp_client *client, uuid_t netagent_uuid);
407
408static bool
409necp_client_remove_assertion(struct necp_client *client, uuid_t netagent_uuid);
410
d9a64523
A
411LIST_HEAD(_necp_flow_registration_list, necp_client_flow_registration);
412static struct _necp_flow_registration_list necp_collect_stats_flow_list;
5ba3f43e 413
d9a64523
A
414struct necp_flow_defunct {
415 LIST_ENTRY(necp_flow_defunct) chain;
5ba3f43e 416
d9a64523 417 uuid_t flow_id;
5ba3f43e 418 uuid_t nexus_agent;
d9a64523 419 void *agent_handle;
5ba3f43e 420 int proc_pid;
cb323159
A
421 u_int32_t flags;
422 struct necp_client_agent_parameters close_parameters;
423 bool has_close_parameters;
5ba3f43e
A
424};
425
d9a64523 426LIST_HEAD(_necp_flow_defunct_list, necp_flow_defunct);
5ba3f43e
A
427
428static int necp_client_id_cmp(struct necp_client *client0, struct necp_client *client1);
429
430RB_HEAD(_necp_client_tree, necp_client);
431RB_PROTOTYPE_PREV(_necp_client_tree, necp_client, link, necp_client_id_cmp);
432RB_GENERATE_PREV(_necp_client_tree, necp_client, link, necp_client_id_cmp);
433
434RB_HEAD(_necp_client_global_tree, necp_client);
435RB_PROTOTYPE_PREV(_necp_client_global_tree, necp_client, global_link, necp_client_id_cmp);
436RB_GENERATE_PREV(_necp_client_global_tree, necp_client, global_link, necp_client_id_cmp);
437
d9a64523
A
438RB_HEAD(_necp_fd_flow_tree, necp_client_flow_registration);
439RB_PROTOTYPE_PREV(_necp_fd_flow_tree, necp_client_flow_registration, fd_link, necp_client_flow_id_cmp);
440RB_GENERATE_PREV(_necp_fd_flow_tree, necp_client_flow_registration, fd_link, necp_client_flow_id_cmp);
441
442RB_HEAD(_necp_client_flow_global_tree, necp_client_flow_registration);
443RB_PROTOTYPE_PREV(_necp_client_flow_global_tree, necp_client_flow_registration, global_link, necp_client_flow_id_cmp);
444RB_GENERATE_PREV(_necp_client_flow_global_tree, necp_client_flow_registration, global_link, necp_client_flow_id_cmp);
445
5ba3f43e 446static struct _necp_client_global_tree necp_client_global_tree;
d9a64523 447static struct _necp_client_flow_global_tree necp_client_flow_global_tree;
5ba3f43e
A
448
449struct necp_client_update {
450 TAILQ_ENTRY(necp_client_update) chain;
451
452 uuid_t client_id;
453
454 size_t update_length;
455 struct necp_client_observer_update update;
456};
457
a39ff7e2 458
0a7de745
A
459#define NAIF_ATTACHED 0x1 // arena is attached to list
460#define NAIF_REDIRECT 0x2 // arena mmap has been redirected
461#define NAIF_DEFUNCT 0x4 // arena is now defunct
d9a64523 462
39037602 463struct necp_fd_data {
5ba3f43e 464 u_int8_t necp_fd_type;
39037602 465 LIST_ENTRY(necp_fd_data) chain;
5ba3f43e 466 struct _necp_client_tree clients;
d9a64523 467 struct _necp_fd_flow_tree flows;
5ba3f43e
A
468 TAILQ_HEAD(_necp_client_update_list, necp_client_update) update_list;
469 int update_count;
39037602 470 int flags;
cb323159
A
471
472 unsigned background : 1;
473
39037602
A
474 int proc_pid;
475 decl_lck_mtx_data(, fd_lock);
476 struct selinfo si;
477};
478
5ba3f43e
A
479#define NECP_FD_LOCK(_f) lck_mtx_lock(&_f->fd_lock)
480#define NECP_FD_UNLOCK(_f) lck_mtx_unlock(&_f->fd_lock)
481#define NECP_FD_ASSERT_LOCKED(_f) LCK_MTX_ASSERT(&_f->fd_lock, LCK_MTX_ASSERT_OWNED)
482#define NECP_FD_ASSERT_UNLOCKED(_f) LCK_MTX_ASSERT(&_f->fd_lock, LCK_MTX_ASSERT_NOTOWNED)
483
39037602 484static LIST_HEAD(_necp_fd_list, necp_fd_data) necp_fd_list;
5ba3f43e
A
485static LIST_HEAD(_necp_fd_observer_list, necp_fd_data) necp_fd_observer_list;
486
f427ee49
A
487static ZONE_DECLARE(necp_client_fd_zone, "necp.clientfd",
488 sizeof(struct necp_fd_data), ZC_NONE);
5ba3f43e 489
f427ee49 490#define NECP_FLOW_ZONE_NAME "necp.flow"
0a7de745 491#define NECP_FLOW_REGISTRATION_ZONE_NAME "necp.flowregistration"
5ba3f43e 492
0a7de745
A
493static unsigned int necp_flow_size; /* size of necp_client_flow */
494static struct mcache *necp_flow_cache; /* cache for necp_client_flow */
d9a64523 495
0a7de745
A
496static unsigned int necp_flow_registration_size; /* size of necp_client_flow_registration */
497static struct mcache *necp_flow_registration_cache; /* cache for necp_client_flow_registration */
d9a64523 498
39037602 499
0a7de745 500static lck_grp_attr_t *necp_fd_grp_attr = NULL;
f427ee49
A
501static lck_attr_t *necp_fd_mtx_attr = NULL;
502static lck_grp_t *necp_fd_mtx_grp = NULL;
5ba3f43e 503
39037602 504decl_lck_rw_data(static, necp_fd_lock);
5ba3f43e
A
505decl_lck_rw_data(static, necp_observer_lock);
506decl_lck_rw_data(static, necp_client_tree_lock);
d9a64523 507decl_lck_rw_data(static, necp_flow_tree_lock);
5ba3f43e
A
508decl_lck_rw_data(static, necp_collect_stats_list_lock);
509
510#define NECP_STATS_LIST_LOCK_EXCLUSIVE() lck_rw_lock_exclusive(&necp_collect_stats_list_lock)
511#define NECP_STATS_LIST_LOCK_SHARED() lck_rw_lock_shared(&necp_collect_stats_list_lock)
512#define NECP_STATS_LIST_UNLOCK() lck_rw_done(&necp_collect_stats_list_lock)
513
514#define NECP_CLIENT_TREE_LOCK_EXCLUSIVE() lck_rw_lock_exclusive(&necp_client_tree_lock)
515#define NECP_CLIENT_TREE_LOCK_SHARED() lck_rw_lock_shared(&necp_client_tree_lock)
516#define NECP_CLIENT_TREE_UNLOCK() lck_rw_done(&necp_client_tree_lock)
d9a64523
A
517#define NECP_CLIENT_TREE_ASSERT_LOCKED() LCK_RW_ASSERT(&necp_client_tree_lock, LCK_RW_ASSERT_HELD)
518
519#define NECP_FLOW_TREE_LOCK_EXCLUSIVE() lck_rw_lock_exclusive(&necp_flow_tree_lock)
520#define NECP_FLOW_TREE_LOCK_SHARED() lck_rw_lock_shared(&necp_flow_tree_lock)
521#define NECP_FLOW_TREE_UNLOCK() lck_rw_done(&necp_flow_tree_lock)
522#define NECP_FLOW_TREE_ASSERT_LOCKED() LCK_RW_ASSERT(&necp_flow_tree_lock, LCK_RW_ASSERT_HELD)
5ba3f43e
A
523
524#define NECP_FD_LIST_LOCK_EXCLUSIVE() lck_rw_lock_exclusive(&necp_fd_lock)
525#define NECP_FD_LIST_LOCK_SHARED() lck_rw_lock_shared(&necp_fd_lock)
526#define NECP_FD_LIST_UNLOCK() lck_rw_done(&necp_fd_lock)
527
528#define NECP_OBSERVER_LIST_LOCK_EXCLUSIVE() lck_rw_lock_exclusive(&necp_observer_lock)
529#define NECP_OBSERVER_LIST_LOCK_SHARED() lck_rw_lock_shared(&necp_observer_lock)
530#define NECP_OBSERVER_LIST_UNLOCK() lck_rw_done(&necp_observer_lock)
531
532// Locking Notes
533
534// Take NECP_FD_LIST_LOCK when accessing or modifying the necp_fd_list
535// Take NECP_CLIENT_TREE_LOCK when accessing or modifying the necp_client_global_tree
d9a64523
A
536// Take NECP_FLOW_TREE_LOCK when accessing or modifying the necp_client_flow_global_tree
537// Take NECP_STATS_LIST_LOCK when accessing or modifying the necp_collect_stats_flow_list
5ba3f43e
A
538// Take NECP_FD_LOCK when accessing or modifying an necp_fd_data entry
539// Take NECP_CLIENT_LOCK when accessing or modifying a single necp_client
540// Take NECP_CLIENT_ROUTE_LOCK when accessing or modifying a client's route
541
542// Precedence, where 1 is the first lock that must be taken
543// 1. NECP_FD_LIST_LOCK
544// 2. NECP_FD_LOCK (any)
545// 3. NECP_CLIENT_TREE_LOCK
546// 4. NECP_CLIENT_LOCK (any)
d9a64523
A
547// 5. NECP_FLOW_TREE_LOCK
548// 6. NECP_STATS_LIST_LOCK
549// 7. NECP_CLIENT_ROUTE_LOCK (any)
5ba3f43e
A
550
551static thread_call_t necp_client_update_tcall;
39037602 552
39037602
A
553
554/// NECP file descriptor functions
555
39037602
A
556static void
557necp_fd_notify(struct necp_fd_data *fd_data, bool locked)
558{
559 struct selinfo *si = &fd_data->si;
560
561 if (!locked) {
5ba3f43e 562 NECP_FD_LOCK(fd_data);
39037602
A
563 }
564
565 selwakeup(si);
566
567 // use a non-zero hint to tell the notification from the
568 // call done in kqueue_scan() which uses 0
569 KNOTE(&si->si_note, 1); // notification
570
571 if (!locked) {
5ba3f43e 572 NECP_FD_UNLOCK(fd_data);
39037602
A
573 }
574}
575
d9a64523
A
576static inline bool
577necp_client_has_unread_flows(struct necp_client *client)
578{
579 NECP_CLIENT_ASSERT_LOCKED(client);
580 struct necp_client_flow_registration *flow_registration = NULL;
581 RB_FOREACH(flow_registration, _necp_client_flow_tree, &client->flow_registrations) {
582 if (!flow_registration->flow_result_read) {
583 return true;
584 }
585 }
586 return false;
587}
588
39037602
A
589static int
590necp_fd_poll(struct necp_fd_data *fd_data, int events, void *wql, struct proc *p, int is_kevent)
591{
592#pragma unused(wql, p, is_kevent)
593 u_int revents = 0;
39037602
A
594
595 u_int want_rx = events & (POLLIN | POLLRDNORM);
596 if (want_rx) {
5ba3f43e
A
597 if (fd_data->flags & NECP_OPEN_FLAG_PUSH_OBSERVER) {
598 // Push-mode observers are readable when they have a new update
599 if (!TAILQ_EMPTY(&fd_data->update_list)) {
600 revents |= want_rx;
601 }
602 } else {
603 // Standard fds are readable when some client is unread
604 struct necp_client *client = NULL;
605 bool has_unread_clients = FALSE;
606 RB_FOREACH(client, _necp_client_tree, &fd_data->clients) {
607 NECP_CLIENT_LOCK(client);
d9a64523 608 if (!client->result_read || necp_client_has_unread_flows(client)) {
5ba3f43e
A
609 has_unread_clients = TRUE;
610 }
611 NECP_CLIENT_UNLOCK(client);
0a7de745 612 if (has_unread_clients) {
5ba3f43e
A
613 break;
614 }
39037602 615 }
39037602 616
5ba3f43e
A
617 if (has_unread_clients) {
618 revents |= want_rx;
619 }
39037602
A
620 }
621 }
622
0a7de745 623 return revents;
39037602
A
624}
625
d9a64523
A
626static inline void
627necp_generate_client_id(uuid_t client_id, bool is_flow)
628{
629 uuid_generate_random(client_id);
630
631 if (is_flow) {
632 client_id[9] |= 0x01;
633 } else {
634 client_id[9] &= ~0x01;
635 }
636}
637
638static inline bool
639necp_client_id_is_flow(uuid_t client_id)
640{
0a7de745 641 return client_id[9] & 0x01;
d9a64523
A
642}
643
5ba3f43e 644static struct necp_client *
d9a64523
A
645necp_find_client_and_lock(uuid_t client_id)
646{
647 NECP_CLIENT_TREE_ASSERT_LOCKED();
648
649 struct necp_client *client = NULL;
650
651 if (necp_client_id_is_flow(client_id)) {
652 NECP_FLOW_TREE_LOCK_SHARED();
653 struct necp_client_flow_registration find;
654 uuid_copy(find.registration_id, client_id);
655 struct necp_client_flow_registration *flow = RB_FIND(_necp_client_flow_global_tree, &necp_client_flow_global_tree, &find);
656 if (flow != NULL) {
657 client = flow->client;
658 }
659 NECP_FLOW_TREE_UNLOCK();
660 } else {
661 struct necp_client find;
662 uuid_copy(find.client_id, client_id);
663 client = RB_FIND(_necp_client_global_tree, &necp_client_global_tree, &find);
664 }
665
666 if (client != NULL) {
667 NECP_CLIENT_LOCK(client);
668 }
669
0a7de745 670 return client;
d9a64523
A
671}
672
673static struct necp_client_flow_registration *
674necp_client_find_flow(struct necp_client *client, uuid_t flow_id)
675{
676 NECP_CLIENT_ASSERT_LOCKED(client);
677 struct necp_client_flow_registration *flow = NULL;
678
679 if (necp_client_id_is_flow(flow_id)) {
680 struct necp_client_flow_registration find;
681 uuid_copy(find.registration_id, flow_id);
682 flow = RB_FIND(_necp_client_flow_tree, &client->flow_registrations, &find);
683 } else {
684 flow = RB_ROOT(&client->flow_registrations);
685 }
686
0a7de745 687 return flow;
d9a64523
A
688}
689
690static struct necp_client *
691necp_client_fd_find_client_unlocked(struct necp_fd_data *client_fd, uuid_t client_id)
5ba3f43e 692{
5ba3f43e 693 NECP_FD_ASSERT_LOCKED(client_fd);
d9a64523
A
694 struct necp_client *client = NULL;
695
696 if (necp_client_id_is_flow(client_id)) {
697 struct necp_client_flow_registration find;
698 uuid_copy(find.registration_id, client_id);
699 struct necp_client_flow_registration *flow = RB_FIND(_necp_fd_flow_tree, &client_fd->flows, &find);
700 if (flow != NULL) {
701 client = flow->client;
702 }
703 } else {
704 struct necp_client find;
705 uuid_copy(find.client_id, client_id);
706 client = RB_FIND(_necp_client_tree, &client_fd->clients, &find);
707 }
708
0a7de745 709 return client;
d9a64523 710}
5ba3f43e 711
d9a64523
A
712static struct necp_client *
713necp_client_fd_find_client_and_lock(struct necp_fd_data *client_fd, uuid_t client_id)
714{
715 struct necp_client *client = necp_client_fd_find_client_unlocked(client_fd, client_id);
5ba3f43e
A
716 if (client != NULL) {
717 NECP_CLIENT_LOCK(client);
718 }
719
0a7de745 720 return client;
5ba3f43e
A
721}
722
723static inline int
724necp_client_id_cmp(struct necp_client *client0, struct necp_client *client1)
725{
0a7de745 726 return uuid_compare(client0->client_id, client1->client_id);
5ba3f43e
A
727}
728
d9a64523
A
729static inline int
730necp_client_flow_id_cmp(struct necp_client_flow_registration *flow0, struct necp_client_flow_registration *flow1)
731{
0a7de745 732 return uuid_compare(flow0->registration_id, flow1->registration_id);
d9a64523
A
733}
734
39037602
A
735static int
736necpop_select(struct fileproc *fp, int which, void *wql, vfs_context_t ctx)
737{
738#pragma unused(fp, which, wql, ctx)
0a7de745 739 return 0;
39037602
A
740 struct necp_fd_data *fd_data = NULL;
741 int revents = 0;
742 int events = 0;
743 proc_t procp;
744
f427ee49 745 fd_data = (struct necp_fd_data *)fp->fp_glob->fg_data;
39037602 746 if (fd_data == NULL) {
0a7de745 747 return 0;
39037602
A
748 }
749
750 procp = vfs_context_proc(ctx);
751
752 switch (which) {
0a7de745
A
753 case FREAD: {
754 events = POLLIN;
755 break;
756 }
39037602 757
0a7de745
A
758 default: {
759 return 1;
760 }
39037602
A
761 }
762
5ba3f43e 763 NECP_FD_LOCK(fd_data);
39037602 764 revents = necp_fd_poll(fd_data, events, wql, procp, 0);
5ba3f43e 765 NECP_FD_UNLOCK(fd_data);
39037602 766
0a7de745 767 return (events & revents) ? 1 : 0;
39037602
A
768}
769
770static void
771necp_fd_knrdetach(struct knote *kn)
772{
773 struct necp_fd_data *fd_data = (struct necp_fd_data *)kn->kn_hook;
774 struct selinfo *si = &fd_data->si;
775
5ba3f43e 776 NECP_FD_LOCK(fd_data);
39037602 777 KNOTE_DETACH(&si->si_note, kn);
5ba3f43e 778 NECP_FD_UNLOCK(fd_data);
39037602
A
779}
780
781static int
782necp_fd_knread(struct knote *kn, long hint)
783{
784#pragma unused(kn, hint)
785 return 1; /* assume we are ready */
786}
787
788static int
cb323159 789necp_fd_knrprocess(struct knote *kn, struct kevent_qos_s *kev)
39037602 790{
39037602
A
791 struct necp_fd_data *fd_data;
792 int revents;
793 int res;
794
795 fd_data = (struct necp_fd_data *)kn->kn_hook;
796
5ba3f43e 797 NECP_FD_LOCK(fd_data);
39037602
A
798 revents = necp_fd_poll(fd_data, POLLIN, NULL, current_proc(), 1);
799 res = ((revents & POLLIN) != 0);
800 if (res) {
cb323159 801 knote_fill_kevent(kn, kev, 0);
39037602 802 }
5ba3f43e 803 NECP_FD_UNLOCK(fd_data);
0a7de745 804 return res;
39037602
A
805}
806
5ba3f43e 807static int
cb323159 808necp_fd_knrtouch(struct knote *kn, struct kevent_qos_s *kev)
39037602
A
809{
810#pragma unused(kev)
811 struct necp_fd_data *fd_data;
812 int revents;
813
814 fd_data = (struct necp_fd_data *)kn->kn_hook;
815
5ba3f43e 816 NECP_FD_LOCK(fd_data);
39037602 817 revents = necp_fd_poll(fd_data, POLLIN, NULL, current_proc(), 1);
5ba3f43e 818 NECP_FD_UNLOCK(fd_data);
39037602 819
0a7de745 820 return (revents & POLLIN) != 0;
39037602
A
821}
822
5ba3f43e 823SECURITY_READ_ONLY_EARLY(struct filterops) necp_fd_rfiltops = {
39037602
A
824 .f_isfd = 1,
825 .f_detach = necp_fd_knrdetach,
826 .f_event = necp_fd_knread,
827 .f_touch = necp_fd_knrtouch,
828 .f_process = necp_fd_knrprocess,
829};
830
831static int
5ba3f43e 832necpop_kqfilter(struct fileproc *fp, struct knote *kn,
cb323159 833 __unused struct kevent_qos_s *kev)
39037602 834{
39037602
A
835 struct necp_fd_data *fd_data = NULL;
836 int revents;
837
838 if (kn->kn_filter != EVFILT_READ) {
839 NECPLOG(LOG_ERR, "bad filter request %d", kn->kn_filter);
cb323159 840 knote_set_error(kn, EINVAL);
0a7de745 841 return 0;
39037602
A
842 }
843
f427ee49 844 fd_data = (struct necp_fd_data *)fp->fp_glob->fg_data;
39037602
A
845 if (fd_data == NULL) {
846 NECPLOG0(LOG_ERR, "No channel for kqfilter");
cb323159 847 knote_set_error(kn, ENOENT);
0a7de745 848 return 0;
39037602
A
849 }
850
5ba3f43e 851 NECP_FD_LOCK(fd_data);
39037602
A
852 kn->kn_filtid = EVFILTID_NECP_FD;
853 kn->kn_hook = fd_data;
854 KNOTE_ATTACH(&fd_data->si.si_note, kn);
855
856 revents = necp_fd_poll(fd_data, POLLIN, NULL, current_proc(), 1);
857
5ba3f43e 858 NECP_FD_UNLOCK(fd_data);
39037602 859
0a7de745 860 return (revents & POLLIN) != 0;
39037602
A
861}
862
d9a64523
A
863#define INTERFACE_FLAGS_SHIFT 32
864#define INTERFACE_FLAGS_MASK 0xffff
865#define INTERFACE_INDEX_SHIFT 0
866#define INTERFACE_INDEX_MASK 0xffffffff
5ba3f43e 867
d9a64523
A
868static uint64_t
869combine_interface_details(uint32_t interface_index, uint16_t interface_flags)
5ba3f43e 870{
0a7de745
A
871 return ((uint64_t)interface_flags & INTERFACE_FLAGS_MASK) << INTERFACE_FLAGS_SHIFT |
872 ((uint64_t)interface_index & INTERFACE_INDEX_MASK) << INTERFACE_INDEX_SHIFT;
5ba3f43e
A
873}
874
d9a64523 875
39037602 876static void
d9a64523 877necp_defunct_flow_registration(struct necp_client *client,
0a7de745
A
878 struct necp_client_flow_registration *flow_registration,
879 struct _necp_flow_defunct_list *defunct_list)
39037602 880{
a39ff7e2 881 NECP_CLIENT_ASSERT_LOCKED(client);
d9a64523
A
882
883 if (!flow_registration->defunct) {
5ba3f43e
A
884 bool needs_defunct = false;
885 struct necp_client_flow *search_flow = NULL;
d9a64523 886 LIST_FOREACH(search_flow, &flow_registration->flow_list, flow_chain) {
5ba3f43e 887 if (search_flow->nexus &&
0a7de745 888 !uuid_is_null(search_flow->u.nexus_agent)) {
5ba3f43e
A
889 // Save defunct values for the nexus
890 if (defunct_list != NULL) {
891 // Sleeping alloc won't fail; copy only what's necessary
0a7de745
A
892 struct necp_flow_defunct *flow_defunct = _MALLOC(sizeof(struct necp_flow_defunct),
893 M_NECP, M_WAITOK | M_ZERO);
d9a64523
A
894 uuid_copy(flow_defunct->nexus_agent, search_flow->u.nexus_agent);
895 uuid_copy(flow_defunct->flow_id, ((flow_registration->flags & NECP_CLIENT_FLOW_FLAGS_USE_CLIENT_ID) ?
0a7de745
A
896 client->client_id :
897 flow_registration->registration_id));
d9a64523
A
898 flow_defunct->proc_pid = client->proc_pid;
899 flow_defunct->agent_handle = client->agent_handle;
cb323159 900 flow_defunct->flags = flow_registration->flags;
5ba3f43e 901 // Add to the list provided by caller
d9a64523 902 LIST_INSERT_HEAD(defunct_list, flow_defunct, chain);
5ba3f43e
A
903 }
904
905 needs_defunct = true;
906 }
907 }
908
909 if (needs_defunct) {
d9a64523 910
5ba3f43e 911 // Only set defunct if there was some assigned flow
d9a64523 912 flow_registration->defunct = true;
39037602 913 }
39037602
A
914 }
915}
916
d9a64523
A
917static void
918necp_defunct_client_for_policy(struct necp_client *client,
0a7de745 919 struct _necp_flow_defunct_list *defunct_list)
d9a64523
A
920{
921 NECP_CLIENT_ASSERT_LOCKED(client);
922
923 struct necp_client_flow_registration *flow_registration = NULL;
924 RB_FOREACH(flow_registration, _necp_client_flow_tree, &client->flow_registrations) {
925 necp_defunct_flow_registration(client, flow_registration, defunct_list);
926 }
927}
928
39037602 929static void
5ba3f43e
A
930necp_client_free(struct necp_client *client)
931{
932 NECP_CLIENT_ASSERT_LOCKED(client);
933
934 NECP_CLIENT_UNLOCK(client);
935
d9a64523
A
936 FREE(client->extra_interface_options, M_NECP);
937 client->extra_interface_options = NULL;
938
5ba3f43e
A
939 lck_mtx_destroy(&client->route_lock, necp_fd_mtx_grp);
940 lck_mtx_destroy(&client->lock, necp_fd_mtx_grp);
941
942 FREE(client, M_NECP);
943}
944
945static void
946necp_client_retain_locked(struct necp_client *client)
947{
948 NECP_CLIENT_ASSERT_LOCKED(client);
949
cb323159 950 os_ref_retain_locked(&client->reference_count);
5ba3f43e
A
951}
952
f427ee49
A
953static void
954necp_client_retain(struct necp_client *client)
955{
956 NECP_CLIENT_LOCK(client);
957 necp_client_retain_locked(client);
958 NECP_CLIENT_UNLOCK(client);
959}
5ba3f43e
A
960
961static bool
962necp_client_release_locked(struct necp_client *client)
963{
964 NECP_CLIENT_ASSERT_LOCKED(client);
965
cb323159
A
966 os_ref_count_t count = os_ref_release_locked(&client->reference_count);
967 if (count == 0) {
5ba3f43e
A
968 necp_client_free(client);
969 }
970
cb323159 971 return count == 0;
5ba3f43e
A
972}
973
cb323159
A
974static bool
975necp_client_release(struct necp_client *client)
976{
977 bool last_ref;
978
979 NECP_CLIENT_LOCK(client);
980 if (!(last_ref = necp_client_release_locked(client))) {
981 NECP_CLIENT_UNLOCK(client);
982 }
983
984 return last_ref;
985}
5ba3f43e
A
986
987static void
988necp_client_update_observer_add_internal(struct necp_fd_data *observer_fd, struct necp_client *client)
989{
990 NECP_FD_LOCK(observer_fd);
991
992 if (observer_fd->update_count >= necp_observer_message_limit) {
993 NECP_FD_UNLOCK(observer_fd);
994 return;
995 }
996
997 struct necp_client_update *client_update = _MALLOC(sizeof(struct necp_client_update) + client->parameters_length,
0a7de745 998 M_NECP, M_WAITOK | M_ZERO);
5ba3f43e
A
999 if (client_update != NULL) {
1000 client_update->update_length = sizeof(struct necp_client_observer_update) + client->parameters_length;
1001 uuid_copy(client_update->client_id, client->client_id);
1002 client_update->update.update_type = NECP_CLIENT_UPDATE_TYPE_PARAMETERS;
1003 memcpy(client_update->update.tlv_buffer, client->parameters, client->parameters_length);
1004 TAILQ_INSERT_TAIL(&observer_fd->update_list, client_update, chain);
1005 observer_fd->update_count++;
1006
1007 necp_fd_notify(observer_fd, true);
1008 }
1009
1010 NECP_FD_UNLOCK(observer_fd);
1011}
1012
1013static void
1014necp_client_update_observer_update_internal(struct necp_fd_data *observer_fd, struct necp_client *client)
1015{
1016 NECP_FD_LOCK(observer_fd);
1017
1018 if (observer_fd->update_count >= necp_observer_message_limit) {
1019 NECP_FD_UNLOCK(observer_fd);
1020 return;
1021 }
1022
1023 struct necp_client_update *client_update = _MALLOC(sizeof(struct necp_client_update) + client->result_length,
0a7de745 1024 M_NECP, M_WAITOK | M_ZERO);
5ba3f43e
A
1025 if (client_update != NULL) {
1026 client_update->update_length = sizeof(struct necp_client_observer_update) + client->result_length;
1027 uuid_copy(client_update->client_id, client->client_id);
1028 client_update->update.update_type = NECP_CLIENT_UPDATE_TYPE_RESULT;
1029 memcpy(client_update->update.tlv_buffer, client->result, client->result_length);
1030 TAILQ_INSERT_TAIL(&observer_fd->update_list, client_update, chain);
1031 observer_fd->update_count++;
1032
1033 necp_fd_notify(observer_fd, true);
1034 }
1035
1036 NECP_FD_UNLOCK(observer_fd);
1037}
1038
1039static void
1040necp_client_update_observer_remove_internal(struct necp_fd_data *observer_fd, struct necp_client *client)
1041{
1042 NECP_FD_LOCK(observer_fd);
1043
1044 if (observer_fd->update_count >= necp_observer_message_limit) {
1045 NECP_FD_UNLOCK(observer_fd);
1046 return;
1047 }
1048
1049 struct necp_client_update *client_update = _MALLOC(sizeof(struct necp_client_update),
0a7de745 1050 M_NECP, M_WAITOK | M_ZERO);
5ba3f43e
A
1051 if (client_update != NULL) {
1052 client_update->update_length = sizeof(struct necp_client_observer_update);
1053 uuid_copy(client_update->client_id, client->client_id);
1054 client_update->update.update_type = NECP_CLIENT_UPDATE_TYPE_REMOVE;
1055 TAILQ_INSERT_TAIL(&observer_fd->update_list, client_update, chain);
1056 observer_fd->update_count++;
1057
1058 necp_fd_notify(observer_fd, true);
1059 }
1060
1061 NECP_FD_UNLOCK(observer_fd);
1062}
1063
1064static void
1065necp_client_update_observer_add(struct necp_client *client)
1066{
1067 NECP_OBSERVER_LIST_LOCK_SHARED();
1068
1069 if (LIST_EMPTY(&necp_fd_observer_list)) {
1070 // No observers, bail
1071 NECP_OBSERVER_LIST_UNLOCK();
1072 return;
1073 }
1074
1075 struct necp_fd_data *observer_fd = NULL;
1076 LIST_FOREACH(observer_fd, &necp_fd_observer_list, chain) {
1077 necp_client_update_observer_add_internal(observer_fd, client);
1078 }
1079
1080 NECP_OBSERVER_LIST_UNLOCK();
1081}
1082
1083static void
1084necp_client_update_observer_update(struct necp_client *client)
1085{
1086 NECP_OBSERVER_LIST_LOCK_SHARED();
1087
1088 if (LIST_EMPTY(&necp_fd_observer_list)) {
1089 // No observers, bail
1090 NECP_OBSERVER_LIST_UNLOCK();
1091 return;
1092 }
1093
1094 struct necp_fd_data *observer_fd = NULL;
1095 LIST_FOREACH(observer_fd, &necp_fd_observer_list, chain) {
1096 necp_client_update_observer_update_internal(observer_fd, client);
1097 }
1098
1099 NECP_OBSERVER_LIST_UNLOCK();
1100}
1101
1102static void
1103necp_client_update_observer_remove(struct necp_client *client)
39037602 1104{
5ba3f43e
A
1105 NECP_OBSERVER_LIST_LOCK_SHARED();
1106
1107 if (LIST_EMPTY(&necp_fd_observer_list)) {
1108 // No observers, bail
1109 NECP_OBSERVER_LIST_UNLOCK();
1110 return;
1111 }
1112
1113 struct necp_fd_data *observer_fd = NULL;
1114 LIST_FOREACH(observer_fd, &necp_fd_observer_list, chain) {
1115 necp_client_update_observer_remove_internal(observer_fd, client);
1116 }
39037602 1117
5ba3f43e
A
1118 NECP_OBSERVER_LIST_UNLOCK();
1119}
1120
1121static void
d9a64523 1122necp_destroy_client_flow_registration(struct necp_client *client,
0a7de745
A
1123 struct necp_client_flow_registration *flow_registration,
1124 pid_t pid, bool abort)
5ba3f43e 1125{
d9a64523 1126 NECP_CLIENT_ASSERT_LOCKED(client);
5ba3f43e 1127
cb323159
A
1128 bool has_close_parameters = false;
1129 struct necp_client_agent_parameters close_parameters = {};
1130 memset(close_parameters.u.close_token, 0, sizeof(close_parameters.u.close_token));
5ba3f43e 1131
5ba3f43e
A
1132 struct necp_client_flow *search_flow = NULL;
1133 struct necp_client_flow *temp_flow = NULL;
d9a64523 1134 LIST_FOREACH_SAFE(search_flow, &flow_registration->flow_list, flow_chain, temp_flow) {
5ba3f43e 1135 if (search_flow->nexus &&
0a7de745 1136 !uuid_is_null(search_flow->u.nexus_agent)) {
f427ee49
A
1137 // Don't unregister for defunct flows
1138 if (!flow_registration->defunct) {
1139 u_int8_t message_type = (abort ? NETAGENT_MESSAGE_TYPE_ABORT_NEXUS :
1140 NETAGENT_MESSAGE_TYPE_CLOSE_NEXUS);
1141 if (((flow_registration->flags & NECP_CLIENT_FLOW_FLAGS_BROWSE) ||
1142 (flow_registration->flags & NECP_CLIENT_FLOW_FLAGS_RESOLVE)) &&
1143 !(flow_registration->flags & NECP_CLIENT_FLOW_FLAGS_ALLOW_NEXUS)) {
1144 message_type = NETAGENT_MESSAGE_TYPE_CLIENT_UNASSERT;
1145 }
1146 int netagent_error = netagent_client_message_with_params(search_flow->u.nexus_agent,
1147 ((flow_registration->flags & NECP_CLIENT_FLOW_FLAGS_USE_CLIENT_ID) ?
1148 client->client_id :
1149 flow_registration->registration_id),
1150 pid, client->agent_handle,
1151 message_type,
1152 has_close_parameters ? &close_parameters : NULL,
1153 NULL, 0);
1154 if (netagent_error != 0 && netagent_error != ENOENT) {
1155 NECPLOG(LOG_ERR, "necp_client_remove close nexus error (%d) MESSAGE TYPE %u", netagent_error, message_type);
1156 }
39037602 1157 }
5ba3f43e 1158 uuid_clear(search_flow->u.nexus_agent);
39037602 1159 }
5ba3f43e
A
1160 if (search_flow->assigned_results != NULL) {
1161 FREE(search_flow->assigned_results, M_NETAGENT);
1162 search_flow->assigned_results = NULL;
1163 }
1164 LIST_REMOVE(search_flow, flow_chain);
1165 if (search_flow->socket) {
1166 OSDecrementAtomic(&necp_socket_flow_count);
1167 } else {
1168 OSDecrementAtomic(&necp_if_flow_count);
1169 }
a39ff7e2 1170 mcache_free(necp_flow_cache, search_flow);
39037602
A
1171 }
1172
d9a64523
A
1173 RB_REMOVE(_necp_client_flow_tree, &client->flow_registrations, flow_registration);
1174 flow_registration->client = NULL;
1175
1176 mcache_free(necp_flow_registration_cache, flow_registration);
1177}
1178
1179static void
1180necp_destroy_client(struct necp_client *client, pid_t pid, bool abort)
1181{
1182 NECP_CLIENT_ASSERT_UNLOCKED(client);
1183
1184 necp_client_update_observer_remove(client);
1185
1186 NECP_CLIENT_LOCK(client);
1187
1188 // Free route
1189 NECP_CLIENT_ROUTE_LOCK(client);
1190 if (client->current_route != NULL) {
1191 rtfree(client->current_route);
1192 client->current_route = NULL;
1193 }
1194 NECP_CLIENT_ROUTE_UNLOCK(client);
1195
1196 // Remove flow assignments
1197 struct necp_client_flow_registration *flow_registration = NULL;
1198 struct necp_client_flow_registration *temp_flow_registration = NULL;
1199 RB_FOREACH_SAFE(flow_registration, _necp_client_flow_tree, &client->flow_registrations, temp_flow_registration) {
1200 necp_destroy_client_flow_registration(client, flow_registration, pid, abort);
1201 }
1202
cb323159 1203
39037602
A
1204 // Remove agent assertions
1205 struct necp_client_assertion *search_assertion = NULL;
1206 struct necp_client_assertion *temp_assertion = NULL;
1207 LIST_FOREACH_SAFE(search_assertion, &client->assertion_list, assertion_chain, temp_assertion) {
d9a64523 1208 int netagent_error = netagent_client_message(search_assertion->asserted_netagent, client->client_id, pid,
0a7de745 1209 client->agent_handle, NETAGENT_MESSAGE_TYPE_CLIENT_UNASSERT);
39037602 1210 if (netagent_error != 0) {
5ba3f43e 1211 NECPLOG((netagent_error == ENOENT ? LOG_DEBUG : LOG_ERR),
0a7de745 1212 "necp_client_remove unassert agent error (%d)", netagent_error);
39037602
A
1213 }
1214 LIST_REMOVE(search_assertion, assertion_chain);
1215 FREE(search_assertion, M_NECP);
1216 }
39037602 1217
5ba3f43e
A
1218 if (!necp_client_release_locked(client)) {
1219 NECP_CLIENT_UNLOCK(client);
1220 }
1221
1222 OSDecrementAtomic(&necp_client_count);
39037602
A
1223}
1224
f427ee49
A
1225static bool
1226necp_defunct_client_fd_locked_inner(struct necp_fd_data *client_fd, struct _necp_flow_defunct_list *defunct_list, bool destroy_stats);
1227
1228static void
1229necp_process_defunct_list(struct _necp_flow_defunct_list *defunct_list)
1230{
1231 if (!LIST_EMPTY(defunct_list)) {
1232 struct necp_flow_defunct *flow_defunct = NULL;
1233 struct necp_flow_defunct *temp_flow_defunct = NULL;
1234
1235 // For each newly defunct client, send a message to the nexus to remove the flow
1236 LIST_FOREACH_SAFE(flow_defunct, defunct_list, chain, temp_flow_defunct) {
1237 if (!uuid_is_null(flow_defunct->nexus_agent)) {
1238 u_int8_t message_type = NETAGENT_MESSAGE_TYPE_ABORT_NEXUS;
1239 if (((flow_defunct->flags & NECP_CLIENT_FLOW_FLAGS_BROWSE) ||
1240 (flow_defunct->flags & NECP_CLIENT_FLOW_FLAGS_RESOLVE)) &&
1241 !(flow_defunct->flags & NECP_CLIENT_FLOW_FLAGS_ALLOW_NEXUS)) {
1242 message_type = NETAGENT_MESSAGE_TYPE_CLIENT_UNASSERT;
1243 }
1244 int netagent_error = netagent_client_message_with_params(flow_defunct->nexus_agent,
1245 flow_defunct->flow_id,
1246 flow_defunct->proc_pid,
1247 flow_defunct->agent_handle,
1248 message_type,
1249 flow_defunct->has_close_parameters ? &flow_defunct->close_parameters : NULL,
1250 NULL, 0);
1251 if (netagent_error != 0) {
1252 char namebuf[MAXCOMLEN + 1];
1253 (void) strlcpy(namebuf, "unknown", sizeof(namebuf));
1254 proc_name(flow_defunct->proc_pid, namebuf, sizeof(namebuf));
1255 NECPLOG((netagent_error == ENOENT ? LOG_DEBUG : LOG_ERR), "necp_update_client abort nexus error (%d) for pid %d %s", netagent_error, flow_defunct->proc_pid, namebuf);
1256 }
1257 }
1258 LIST_REMOVE(flow_defunct, chain);
1259 FREE(flow_defunct, M_NECP);
1260 }
1261 }
1262 ASSERT(LIST_EMPTY(defunct_list));
1263}
1264
39037602
A
1265static int
1266necpop_close(struct fileglob *fg, vfs_context_t ctx)
1267{
5ba3f43e 1268#pragma unused(ctx)
39037602
A
1269 struct necp_fd_data *fd_data = NULL;
1270 int error = 0;
1271
1272 fd_data = (struct necp_fd_data *)fg->fg_data;
1273 fg->fg_data = NULL;
1274
1275 if (fd_data != NULL) {
5ba3f43e
A
1276 struct _necp_client_tree clients_to_close;
1277 RB_INIT(&clients_to_close);
1278
1279 // Remove from list quickly
1280 if (fd_data->flags & NECP_OPEN_FLAG_PUSH_OBSERVER) {
1281 NECP_OBSERVER_LIST_LOCK_EXCLUSIVE();
1282 LIST_REMOVE(fd_data, chain);
1283 NECP_OBSERVER_LIST_UNLOCK();
1284 } else {
1285 NECP_FD_LIST_LOCK_EXCLUSIVE();
1286 LIST_REMOVE(fd_data, chain);
1287 NECP_FD_LIST_UNLOCK();
1288 }
39037602 1289
5ba3f43e
A
1290 NECP_FD_LOCK(fd_data);
1291 pid_t pid = fd_data->proc_pid;
d9a64523 1292
f427ee49
A
1293 struct _necp_flow_defunct_list defunct_list;
1294 LIST_INIT(&defunct_list);
1295
1296 (void)necp_defunct_client_fd_locked_inner(fd_data, &defunct_list, false);
1297
d9a64523
A
1298 struct necp_client_flow_registration *flow_registration = NULL;
1299 struct necp_client_flow_registration *temp_flow_registration = NULL;
1300 RB_FOREACH_SAFE(flow_registration, _necp_fd_flow_tree, &fd_data->flows, temp_flow_registration) {
1301 NECP_FLOW_TREE_LOCK_EXCLUSIVE();
1302 RB_REMOVE(_necp_client_flow_global_tree, &necp_client_flow_global_tree, flow_registration);
1303 NECP_FLOW_TREE_UNLOCK();
1304 RB_REMOVE(_necp_fd_flow_tree, &fd_data->flows, flow_registration);
1305 }
1306
39037602
A
1307 struct necp_client *client = NULL;
1308 struct necp_client *temp_client = NULL;
5ba3f43e
A
1309 RB_FOREACH_SAFE(client, _necp_client_tree, &fd_data->clients, temp_client) {
1310 NECP_CLIENT_TREE_LOCK_EXCLUSIVE();
1311 RB_REMOVE(_necp_client_global_tree, &necp_client_global_tree, client);
1312 NECP_CLIENT_TREE_UNLOCK();
1313 RB_REMOVE(_necp_client_tree, &fd_data->clients, client);
1314 RB_INSERT(_necp_client_tree, &clients_to_close, client);
39037602 1315 }
5ba3f43e
A
1316
1317 struct necp_client_update *client_update = NULL;
1318 struct necp_client_update *temp_update = NULL;
1319 TAILQ_FOREACH_SAFE(client_update, &fd_data->update_list, chain, temp_update) {
1320 // Flush pending updates
1321 TAILQ_REMOVE(&fd_data->update_list, client_update, chain);
1322 FREE(client_update, M_NECP);
1323 }
1324 fd_data->update_count = 0;
1325
1326
1327 NECP_FD_UNLOCK(fd_data);
39037602
A
1328
1329 selthreadclear(&fd_data->si);
1330
1331 lck_mtx_destroy(&fd_data->fd_lock, necp_fd_mtx_grp);
1332
5ba3f43e
A
1333 if (fd_data->flags & NECP_OPEN_FLAG_PUSH_OBSERVER) {
1334 OSDecrementAtomic(&necp_observer_fd_count);
1335 } else {
1336 OSDecrementAtomic(&necp_client_fd_count);
1337 }
39037602 1338
5ba3f43e 1339 zfree(necp_client_fd_zone, fd_data);
39037602 1340 fd_data = NULL;
5ba3f43e
A
1341
1342 RB_FOREACH_SAFE(client, _necp_client_tree, &clients_to_close, temp_client) {
1343 RB_REMOVE(_necp_client_tree, &clients_to_close, client);
1344 necp_destroy_client(client, pid, true);
1345 }
f427ee49
A
1346
1347 necp_process_defunct_list(&defunct_list);
39037602
A
1348 }
1349
0a7de745 1350 return error;
39037602
A
1351}
1352
1353/// NECP client utilities
1354
5ba3f43e
A
1355static inline bool
1356necp_address_is_wildcard(const union necp_sockaddr_union * const addr)
1357{
0a7de745
A
1358 return (addr->sa.sa_family == AF_INET && addr->sin.sin_addr.s_addr == INADDR_ANY) ||
1359 (addr->sa.sa_family == AF_INET6 && IN6_IS_ADDR_UNSPECIFIED(&addr->sin6.sin6_addr));
5ba3f43e
A
1360}
1361
39037602 1362static int
f427ee49
A
1363necp_find_fd_data(struct proc *p, int fd,
1364 struct fileproc **fpp, struct necp_fd_data **fd_data)
39037602 1365{
f427ee49
A
1366 struct fileproc *fp;
1367 int error = fp_get_ftype(p, fd, DTYPE_NETPOLICY, ENODEV, &fp);
39037602 1368
f427ee49
A
1369 if (error == 0) {
1370 *fd_data = (struct necp_fd_data *)fp->fp_glob->fg_data;
1371 *fpp = fp;
1372
1373 if ((*fd_data)->necp_fd_type != necp_fd_type_client) {
1374 // Not a client fd, ignore
1375 fp_drop(p, fd, fp, 0);
1376 error = EINVAL;
1377 }
39037602 1378 }
f427ee49
A
1379 return error;
1380}
39037602 1381
f427ee49
A
1382static void
1383necp_client_add_nexus_flow(struct necp_client_flow_registration *flow_registration,
1384 uuid_t nexus_agent,
1385 uint32_t interface_index,
1386 uint16_t interface_flags)
1387{
1388 struct necp_client_flow *new_flow = mcache_alloc(necp_flow_cache, MCR_SLEEP);
1389 if (new_flow == NULL) {
1390 NECPLOG0(LOG_ERR, "Failed to allocate nexus flow");
1391 return;
d9a64523
A
1392 }
1393
f427ee49
A
1394 memset(new_flow, 0, sizeof(*new_flow));
1395
1396 new_flow->nexus = TRUE;
1397 uuid_copy(new_flow->u.nexus_agent, nexus_agent);
1398 new_flow->interface_index = interface_index;
1399 new_flow->interface_flags = interface_flags;
1400 new_flow->check_tcp_heuristics = TRUE;
1401
1402
1403 LIST_INSERT_HEAD(&flow_registration->flow_list, new_flow, flow_chain);
1404
39037602
A
1405}
1406
f427ee49
A
1407static void
1408necp_client_add_nexus_flow_if_needed(struct necp_client_flow_registration *flow_registration,
1409 uuid_t nexus_agent,
1410 uint32_t interface_index)
1411{
1412 struct necp_client_flow *flow = NULL;
1413 LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
1414 if (flow->nexus &&
1415 uuid_compare(flow->u.nexus_agent, nexus_agent) == 0) {
1416 return;
1417 }
1418 }
1419
1420 uint16_t interface_flags = 0;
1421 ifnet_t ifp = NULL;
1422 ifnet_head_lock_shared();
1423 if (interface_index != IFSCOPE_NONE && interface_index <= (u_int32_t)if_index) {
1424 ifp = ifindex2ifnet[interface_index];
1425 if (ifp != NULL) {
1426 ifnet_lock_shared(ifp);
1427 interface_flags = nstat_ifnet_to_flags(ifp);
1428 ifnet_lock_done(ifp);
1429 }
1430 }
1431 ifnet_head_done();
1432 necp_client_add_nexus_flow(flow_registration, nexus_agent, interface_index, interface_flags);
1433}
5ba3f43e 1434
d9a64523
A
1435static struct necp_client_flow *
1436necp_client_add_interface_flow(struct necp_client_flow_registration *flow_registration,
0a7de745 1437 uint32_t interface_index)
5ba3f43e 1438{
a39ff7e2 1439 struct necp_client_flow *new_flow = mcache_alloc(necp_flow_cache, MCR_SLEEP);
5ba3f43e
A
1440 if (new_flow == NULL) {
1441 NECPLOG0(LOG_ERR, "Failed to allocate interface flow");
d9a64523 1442 return NULL;
5ba3f43e
A
1443 }
1444
1445 memset(new_flow, 0, sizeof(*new_flow));
1446
1447 // Neither nexus nor socket
1448 new_flow->interface_index = interface_index;
d9a64523
A
1449 new_flow->u.socket_handle = flow_registration->interface_handle;
1450 new_flow->u.cb = flow_registration->interface_cb;
5ba3f43e
A
1451
1452 OSIncrementAtomic(&necp_if_flow_count);
1453
d9a64523
A
1454 LIST_INSERT_HEAD(&flow_registration->flow_list, new_flow, flow_chain);
1455
1456 return new_flow;
5ba3f43e
A
1457}
1458
d9a64523
A
1459static struct necp_client_flow *
1460necp_client_add_interface_flow_if_needed(struct necp_client *client,
0a7de745
A
1461 struct necp_client_flow_registration *flow_registration,
1462 uint32_t interface_index)
5ba3f43e
A
1463{
1464 if (!client->allow_multiple_flows ||
0a7de745 1465 interface_index == IFSCOPE_NONE) {
5ba3f43e 1466 // Interface not set, or client not allowed to use this mode
d9a64523 1467 return NULL;
5ba3f43e
A
1468 }
1469
1470 struct necp_client_flow *flow = NULL;
d9a64523 1471 LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
5ba3f43e
A
1472 if (!flow->nexus && !flow->socket && flow->interface_index == interface_index) {
1473 // Already have the flow
1474 flow->invalid = FALSE;
d9a64523
A
1475 flow->u.socket_handle = flow_registration->interface_handle;
1476 flow->u.cb = flow_registration->interface_cb;
1477 return NULL;
1478 }
1479 }
1480 return necp_client_add_interface_flow(flow_registration, interface_index);
1481}
1482
1483static void
1484necp_client_add_interface_option_if_needed(struct necp_client *client,
0a7de745
A
1485 uint32_t interface_index,
1486 uint32_t interface_generation,
1487 uuid_t *nexus_agent)
d9a64523
A
1488{
1489 if (interface_index == IFSCOPE_NONE ||
0a7de745 1490 (client->interface_option_count != 0 && !client->allow_multiple_flows)) {
d9a64523
A
1491 // Interface not set, or client not allowed to use this mode
1492 return;
1493 }
1494
1495 if (client->interface_option_count >= NECP_CLIENT_MAX_INTERFACE_OPTIONS) {
1496 // Cannot take any more interface options
1497 return;
1498 }
5ba3f43e 1499
d9a64523
A
1500 // Check if already present
1501 for (u_int32_t option_i = 0; option_i < client->interface_option_count; option_i++) {
1502 if (option_i < NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT) {
1503 struct necp_client_interface_option *option = &client->interface_options[option_i];
1504 if (option->interface_index == interface_index) {
1505 if (nexus_agent == NULL) {
1506 return;
1507 }
1508 if (uuid_compare(option->nexus_agent, *nexus_agent) == 0) {
1509 return;
1510 }
1511 if (uuid_is_null(option->nexus_agent)) {
1512 uuid_copy(option->nexus_agent, *nexus_agent);
1513 return;
1514 }
1515 // If we get to this point, this is a new nexus flow
1516 }
1517 } else {
1518 struct necp_client_interface_option *option = &client->extra_interface_options[option_i - NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT];
1519 if (option->interface_index == interface_index) {
1520 if (nexus_agent == NULL) {
1521 return;
1522 }
1523 if (uuid_compare(option->nexus_agent, *nexus_agent) == 0) {
1524 return;
1525 }
1526 if (uuid_is_null(option->nexus_agent)) {
1527 uuid_copy(option->nexus_agent, *nexus_agent);
1528 return;
1529 }
1530 // If we get to this point, this is a new nexus flow
1531 }
5ba3f43e
A
1532 }
1533 }
1534
d9a64523
A
1535 // Add a new entry
1536 if (client->interface_option_count < NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT) {
1537 // Add to static
1538 struct necp_client_interface_option *option = &client->interface_options[client->interface_option_count];
1539 option->interface_index = interface_index;
1540 option->interface_generation = interface_generation;
1541 if (nexus_agent != NULL) {
1542 uuid_copy(option->nexus_agent, *nexus_agent);
cb323159
A
1543 } else {
1544 uuid_clear(option->nexus_agent);
d9a64523
A
1545 }
1546 client->interface_option_count++;
1547 } else {
1548 // Add to extra
1549 if (client->extra_interface_options == NULL) {
1550 client->extra_interface_options = _MALLOC(sizeof(struct necp_client_interface_option) * NECP_CLIENT_INTERFACE_OPTION_EXTRA_COUNT, M_NECP, M_WAITOK | M_ZERO);
1551 }
1552 if (client->extra_interface_options != NULL) {
1553 struct necp_client_interface_option *option = &client->extra_interface_options[client->interface_option_count - NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT];
1554 option->interface_index = interface_index;
1555 option->interface_generation = interface_generation;
1556 if (nexus_agent != NULL) {
1557 uuid_copy(option->nexus_agent, *nexus_agent);
cb323159
A
1558 } else {
1559 uuid_clear(option->nexus_agent);
d9a64523
A
1560 }
1561 client->interface_option_count++;
1562 }
1563 }
5ba3f43e
A
1564}
1565
1566static bool
1567necp_client_flow_is_viable(proc_t proc, struct necp_client *client,
0a7de745 1568 struct necp_client_flow *flow)
5ba3f43e
A
1569{
1570 struct necp_aggregate_result result;
1571 bool ignore_address = (client->allow_multiple_flows && !flow->nexus && !flow->socket);
1572
1573 flow->necp_flow_flags = 0;
1574 int error = necp_application_find_policy_match_internal(proc, client->parameters,
0a7de745 1575 (u_int32_t)client->parameters_length,
cb323159 1576 &result, &flow->necp_flow_flags, NULL,
0a7de745 1577 flow->interface_index,
cb323159 1578 &flow->local_addr, &flow->remote_addr, NULL, NULL,
ea3f0419 1579 NULL, ignore_address, true, NULL);
0a7de745 1580
94ff46dc
A
1581 // Check for blocking agents
1582 for (int i = 0; i < NECP_MAX_NETAGENTS; i++) {
1583 if (uuid_is_null(result.netagents[i])) {
1584 // Passed end of valid agents
1585 break;
1586 }
1587
1588 u_int32_t flags = netagent_get_flags(result.netagents[i]);
1589 if ((flags & NETAGENT_FLAG_REGISTERED) &&
1590 !(flags & NETAGENT_FLAG_VOLUNTARY) &&
1591 !(flags & NETAGENT_FLAG_ACTIVE) &&
1592 !(flags & NETAGENT_FLAG_SPECIFIC_USE_ONLY)) {
1593 // A required agent is not active, cause the flow to be marked non-viable
1594 return false;
1595 }
1596 }
1597
f427ee49
A
1598 if (flow->interface_index != IFSCOPE_NONE) {
1599 ifnet_head_lock_shared();
1600
1601 struct ifnet *ifp = ifindex2ifnet[flow->interface_index];
1602 if (ifp && ifp->if_delegated.ifp != IFSCOPE_NONE) {
1603 flow->delegated_interface_index = ifp->if_delegated.ifp->if_index;
1604 }
1605
1606 ifnet_head_done();
1607 }
1608
0a7de745
A
1609 return error == 0 &&
1610 result.routed_interface_index != IFSCOPE_NONE &&
1611 result.routing_result != NECP_KERNEL_POLICY_RESULT_DROP;
5ba3f43e
A
1612}
1613
d9a64523
A
1614static void
1615necp_flow_add_interface_flows(proc_t proc,
0a7de745
A
1616 struct necp_client *client,
1617 struct necp_client_flow_registration *flow_registration,
1618 bool send_initial)
d9a64523
A
1619{
1620 // Traverse all interfaces and add a tracking flow if needed
1621 for (u_int32_t option_i = 0; option_i < client->interface_option_count; option_i++) {
1622 if (option_i < NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT) {
1623 struct necp_client_interface_option *option = &client->interface_options[option_i];
1624 struct necp_client_flow *flow = necp_client_add_interface_flow_if_needed(client, flow_registration, option->interface_index);
1625 if (flow != NULL && send_initial) {
1626 flow->viable = necp_client_flow_is_viable(proc, client, flow);
1627 if (flow->viable && flow->u.cb) {
1628 bool viable = flow->viable;
1629 flow->u.cb(flow_registration->interface_handle, NECP_CLIENT_CBACTION_INITIAL, flow->interface_index, flow->necp_flow_flags, &viable);
1630 flow->viable = viable;
1631 }
1632 }
1633 } else {
1634 struct necp_client_interface_option *option = &client->extra_interface_options[option_i - NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT];
1635 struct necp_client_flow *flow = necp_client_add_interface_flow_if_needed(client, flow_registration, option->interface_index);
1636 if (flow != NULL && send_initial) {
1637 flow->viable = necp_client_flow_is_viable(proc, client, flow);
1638 if (flow->viable && flow->u.cb) {
1639 bool viable = flow->viable;
1640 flow->u.cb(flow_registration->interface_handle, NECP_CLIENT_CBACTION_INITIAL, flow->interface_index, flow->necp_flow_flags, &viable);
1641 flow->viable = viable;
1642 }
1643 }
1644 }
1645 }
1646}
1647
5ba3f43e 1648static bool
a39ff7e2 1649necp_client_update_flows(proc_t proc,
0a7de745
A
1650 struct necp_client *client,
1651 struct _necp_flow_defunct_list *defunct_list)
5ba3f43e 1652{
a39ff7e2
A
1653 NECP_CLIENT_ASSERT_LOCKED(client);
1654
f427ee49 1655 bool any_client_updated = FALSE;
5ba3f43e
A
1656 struct necp_client_flow *flow = NULL;
1657 struct necp_client_flow *temp_flow = NULL;
d9a64523
A
1658 struct necp_client_flow_registration *flow_registration = NULL;
1659 RB_FOREACH(flow_registration, _necp_client_flow_tree, &client->flow_registrations) {
1660 if (flow_registration->interface_cb != NULL) {
1661 // Add any interface flows that are not already tracked
1662 necp_flow_add_interface_flows(proc, client, flow_registration, false);
5ba3f43e
A
1663 }
1664
d9a64523 1665 LIST_FOREACH_SAFE(flow, &flow_registration->flow_list, flow_chain, temp_flow) {
f427ee49
A
1666 bool client_updated = FALSE;
1667
d9a64523 1668 // Check policy result for flow
f427ee49
A
1669 u_short old_delegated_ifindex = flow->delegated_interface_index;
1670
d9a64523
A
1671 int old_flags = flow->necp_flow_flags;
1672 bool viable = necp_client_flow_is_viable(proc, client, flow);
5ba3f43e 1673
d9a64523 1674 // TODO: Defunct nexus flows that are blocked by policy
5ba3f43e 1675
d9a64523
A
1676 if (flow->viable != viable) {
1677 flow->viable = viable;
1678 client_updated = TRUE;
1679 }
1680
1681 if ((old_flags & NECP_CLIENT_RESULT_FLAG_FORCE_UPDATE) !=
0a7de745 1682 (flow->necp_flow_flags & NECP_CLIENT_RESULT_FLAG_FORCE_UPDATE)) {
d9a64523 1683 client_updated = TRUE;
5ba3f43e 1684 }
5ba3f43e 1685
f427ee49
A
1686 if (flow->delegated_interface_index != old_delegated_ifindex) {
1687 client_updated = TRUE;
1688 }
1689
d9a64523
A
1690 if (flow->viable && client_updated && (flow->socket || (!flow->socket && !flow->nexus)) && flow->u.cb) {
1691 bool flow_viable = flow->viable;
cb323159 1692 flow->u.cb(flow->u.socket_handle, NECP_CLIENT_CBACTION_VIABLE, flow->interface_index, flow->necp_flow_flags, &flow_viable);
d9a64523
A
1693 flow->viable = flow_viable;
1694 }
5ba3f43e 1695
d9a64523
A
1696 if (!flow->viable || flow->invalid) {
1697 if (client_updated && (flow->socket || (!flow->socket && !flow->nexus)) && flow->u.cb) {
1698 bool flow_viable = flow->viable;
cb323159 1699 flow->u.cb(flow->u.socket_handle, NECP_CLIENT_CBACTION_NONVIABLE, flow->interface_index, flow->necp_flow_flags, &flow_viable);
d9a64523 1700 flow->viable = flow_viable;
5ba3f43e 1701 }
d9a64523
A
1702 // The callback might change the viable-flag of the
1703 // flow depending on its policy. Thus, we need to
1704 // check the flags again after the callback.
1705 }
1706
1707 (void)defunct_list;
1708
1709 // Handle flows that no longer match
1710 if (!flow->viable || flow->invalid) {
1711 // Drop them as long as they aren't assigned data
1712 if (!flow->nexus && !flow->assigned) {
1713 if (flow->assigned_results != NULL) {
1714 FREE(flow->assigned_results, M_NETAGENT);
1715 flow->assigned_results = NULL;
1716 client_updated = TRUE;
1717 }
1718 LIST_REMOVE(flow, flow_chain);
1719 if (flow->socket) {
1720 OSDecrementAtomic(&necp_socket_flow_count);
1721 } else {
1722 OSDecrementAtomic(&necp_if_flow_count);
1723 }
1724 mcache_free(necp_flow_cache, flow);
5ba3f43e 1725 }
5ba3f43e 1726 }
f427ee49
A
1727
1728 any_client_updated |= client_updated;
5ba3f43e
A
1729 }
1730 }
1731
f427ee49 1732 return any_client_updated;
5ba3f43e
A
1733}
1734
1735static void
1736necp_client_mark_all_nonsocket_flows_as_invalid(struct necp_client *client)
1737{
d9a64523 1738 struct necp_client_flow_registration *flow_registration = NULL;
5ba3f43e 1739 struct necp_client_flow *flow = NULL;
d9a64523
A
1740 RB_FOREACH(flow_registration, _necp_client_flow_tree, &client->flow_registrations) {
1741 LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
1742 if (!flow->socket) { // Socket flows are not marked as invalid
1743 flow->invalid = TRUE;
1744 }
5ba3f43e
A
1745 }
1746 }
d9a64523
A
1747
1748 // Reset option count every update
1749 client->interface_option_count = 0;
5ba3f43e
A
1750}
1751
ea3f0419
A
1752static inline bool
1753necp_netagent_is_required(const struct necp_client_parsed_parameters *parameters,
1754 uuid_t *netagent_uuid)
1755{
1756 // Specific use agents only apply when required
1757 bool required = false;
1758 if (parameters != NULL) {
1759 // Check required agent UUIDs
1760 for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
1761 if (uuid_is_null(parameters->required_netagents[i])) {
1762 break;
1763 }
1764 if (uuid_compare(parameters->required_netagents[i], *netagent_uuid) == 0) {
1765 required = true;
1766 break;
1767 }
1768 }
1769
1770 if (!required) {
1771 // Check required agent types
1772 bool fetched_type = false;
1773 char netagent_domain[NETAGENT_DOMAINSIZE];
1774 char netagent_type[NETAGENT_TYPESIZE];
1775 memset(&netagent_domain, 0, NETAGENT_DOMAINSIZE);
1776 memset(&netagent_type, 0, NETAGENT_TYPESIZE);
1777
1778 for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
1779 if (strlen(parameters->required_netagent_types[i].netagent_domain) == 0 ||
1780 strlen(parameters->required_netagent_types[i].netagent_type) == 0) {
1781 break;
1782 }
1783
1784 if (!fetched_type) {
1785 if (netagent_get_agent_domain_and_type(*netagent_uuid, netagent_domain, netagent_type)) {
1786 fetched_type = TRUE;
1787 } else {
1788 break;
1789 }
1790 }
1791
1792 if ((strlen(parameters->required_netagent_types[i].netagent_domain) == 0 ||
1793 strncmp(netagent_domain, parameters->required_netagent_types[i].netagent_domain, NETAGENT_DOMAINSIZE) == 0) &&
1794 (strlen(parameters->required_netagent_types[i].netagent_type) == 0 ||
1795 strncmp(netagent_type, parameters->required_netagent_types[i].netagent_type, NETAGENT_TYPESIZE) == 0)) {
1796 required = true;
1797 break;
1798 }
1799 }
1800 }
1801 }
1802
1803 return required;
1804}
1805
5ba3f43e 1806static bool
d9a64523 1807necp_netagent_applies_to_client(struct necp_client *client,
0a7de745
A
1808 const struct necp_client_parsed_parameters *parameters,
1809 uuid_t *netagent_uuid, bool allow_nexus,
1810 uint32_t interface_index, uint32_t interface_generation)
5ba3f43e 1811{
d9a64523 1812#pragma unused(interface_index, interface_generation)
5ba3f43e 1813 bool applies = FALSE;
d9a64523 1814 u_int32_t flags = netagent_get_flags(*netagent_uuid);
5ba3f43e
A
1815 if (!(flags & NETAGENT_FLAG_REGISTERED)) {
1816 // Unregistered agents never apply
0a7de745 1817 return applies;
5ba3f43e
A
1818 }
1819
cb323159
A
1820 const bool is_nexus_agent = ((flags & NETAGENT_FLAG_NEXUS_PROVIDER) ||
1821 (flags & NETAGENT_FLAG_NEXUS_LISTENER) ||
1822 (flags & NETAGENT_FLAG_CUSTOM_ETHER_NEXUS) ||
1823 (flags & NETAGENT_FLAG_CUSTOM_IP_NEXUS) ||
1824 (flags & NETAGENT_FLAG_INTERPOSE_NEXUS));
1825 if (is_nexus_agent) {
1826 if (!allow_nexus) {
1827 // Hide nexus providers unless allowed
1828 // Direct interfaces and direct policies are allowed to use a nexus
1829 // Delegate interfaces or re-scoped interfaces are not allowed
1830 return applies;
1831 }
1832
1833 if ((parameters->flags & NECP_CLIENT_PARAMETER_FLAG_CUSTOM_ETHER) &&
1834 !(flags & NETAGENT_FLAG_CUSTOM_ETHER_NEXUS)) {
1835 // Client requested a custom ether nexus, but this nexus isn't one
1836 return applies;
1837 }
1838
1839 if ((parameters->flags & NECP_CLIENT_PARAMETER_FLAG_CUSTOM_IP) &&
1840 !(flags & NETAGENT_FLAG_CUSTOM_IP_NEXUS)) {
1841 // Client requested a custom IP nexus, but this nexus isn't one
1842 return applies;
1843 }
1844
1845 if ((parameters->flags & NECP_CLIENT_PARAMETER_FLAG_INTERPOSE) &&
1846 !(flags & NETAGENT_FLAG_INTERPOSE_NEXUS)) {
1847 // Client requested an interpose nexus, but this nexus isn't one
1848 return applies;
1849 }
1850
1851 if (!(parameters->flags & NECP_CLIENT_PARAMETER_FLAG_CUSTOM_ETHER) &&
1852 !(parameters->flags & NECP_CLIENT_PARAMETER_FLAG_CUSTOM_IP) &&
1853 !(parameters->flags & NECP_CLIENT_PARAMETER_FLAG_INTERPOSE) &&
1854 !(flags & NETAGENT_FLAG_NEXUS_PROVIDER)) {
1855 // Client requested default parameters, but this nexus isn't generic
1856 return applies;
1857 }
5ba3f43e 1858 }
39037602 1859
d9a64523
A
1860 if (uuid_compare(client->failed_trigger_agent.netagent_uuid, *netagent_uuid) == 0) {
1861 if (client->failed_trigger_agent.generation == netagent_get_generation(*netagent_uuid)) {
1862 // If this agent was triggered, and failed, and hasn't changed, keep hiding it
0a7de745 1863 return applies;
d9a64523
A
1864 } else {
1865 // Mismatch generation, clear out old trigger
1866 uuid_clear(client->failed_trigger_agent.netagent_uuid);
1867 client->failed_trigger_agent.generation = 0;
1868 }
1869 }
1870
39037602
A
1871 if (flags & NETAGENT_FLAG_SPECIFIC_USE_ONLY) {
1872 // Specific use agents only apply when required
ea3f0419 1873 applies = necp_netagent_is_required(parameters, netagent_uuid);
39037602
A
1874 } else {
1875 applies = TRUE;
1876 }
1877
39037602 1878
0a7de745 1879 return applies;
39037602
A
1880}
1881
5ba3f43e 1882static void
d9a64523 1883necp_client_add_agent_interface_options(struct necp_client *client,
0a7de745
A
1884 const struct necp_client_parsed_parameters *parsed_parameters,
1885 ifnet_t ifp)
5ba3f43e
A
1886{
1887 if (ifp != NULL && ifp->if_agentids != NULL) {
1888 for (u_int32_t i = 0; i < ifp->if_agentcount; i++) {
1889 if (uuid_is_null(ifp->if_agentids[i])) {
1890 continue;
1891 }
5ba3f43e 1892 // Relies on the side effect that nexus agents that apply will create flows
d9a64523 1893 (void)necp_netagent_applies_to_client(client, parsed_parameters, &ifp->if_agentids[i], TRUE,
0a7de745 1894 ifp->if_index, ifnet_get_generation(ifp));
5ba3f43e
A
1895 }
1896 }
1897}
1898
ea3f0419
A
1899static void
1900necp_client_add_browse_interface_options(struct necp_client *client,
1901 const struct necp_client_parsed_parameters *parsed_parameters,
1902 ifnet_t ifp)
1903{
1904 if (ifp != NULL && ifp->if_agentids != NULL) {
1905 for (u_int32_t i = 0; i < ifp->if_agentcount; i++) {
1906 if (uuid_is_null(ifp->if_agentids[i])) {
1907 continue;
1908 }
1909
1910 u_int32_t flags = netagent_get_flags(ifp->if_agentids[i]);
1911 if ((flags & NETAGENT_FLAG_REGISTERED) &&
1912 (flags & NETAGENT_FLAG_ACTIVE) &&
1913 (flags & NETAGENT_FLAG_SUPPORTS_BROWSE) &&
1914 (!(flags & NETAGENT_FLAG_SPECIFIC_USE_ONLY) ||
1915 necp_netagent_is_required(parsed_parameters, &ifp->if_agentids[i]))) {
1916 necp_client_add_interface_option_if_needed(client, ifp->if_index, ifnet_get_generation(ifp), &ifp->if_agentids[i]);
1917
1918 // Finding one is enough
1919 break;
1920 }
1921 }
1922 }
1923}
1924
5ba3f43e
A
1925static inline bool
1926necp_client_address_is_valid(struct sockaddr *address)
1927{
1928 if (address->sa_family == AF_INET) {
0a7de745 1929 return address->sa_len == sizeof(struct sockaddr_in);
5ba3f43e 1930 } else if (address->sa_family == AF_INET6) {
0a7de745 1931 return address->sa_len == sizeof(struct sockaddr_in6);
5ba3f43e 1932 } else {
0a7de745 1933 return FALSE;
5ba3f43e
A
1934 }
1935}
1936
cb323159
A
1937static inline bool
1938necp_client_endpoint_is_unspecified(struct necp_client_endpoint *endpoint)
1939{
1940 if (necp_client_address_is_valid(&endpoint->u.sa)) {
1941 if (endpoint->u.sa.sa_family == AF_INET) {
1942 return endpoint->u.sin.sin_addr.s_addr == INADDR_ANY;
1943 } else if (endpoint->u.sa.sa_family == AF_INET6) {
1944 return IN6_IS_ADDR_UNSPECIFIED(&endpoint->u.sin6.sin6_addr);
1945 } else {
1946 return TRUE;
1947 }
1948 } else {
1949 return TRUE;
1950 }
1951}
1952
1953
39037602
A
1954static int
1955necp_client_parse_parameters(u_int8_t *parameters,
0a7de745
A
1956 u_int32_t parameters_size,
1957 struct necp_client_parsed_parameters *parsed_parameters)
39037602
A
1958{
1959 int error = 0;
1960 size_t offset = 0;
1961
1962 u_int32_t num_prohibited_interfaces = 0;
39037602
A
1963 u_int32_t num_prohibited_interface_types = 0;
1964 u_int32_t num_required_agents = 0;
1965 u_int32_t num_prohibited_agents = 0;
1966 u_int32_t num_preferred_agents = 0;
d9a64523 1967 u_int32_t num_avoided_agents = 0;
39037602
A
1968 u_int32_t num_required_agent_types = 0;
1969 u_int32_t num_prohibited_agent_types = 0;
1970 u_int32_t num_preferred_agent_types = 0;
d9a64523 1971 u_int32_t num_avoided_agent_types = 0;
cb323159
A
1972 u_int8_t *resolver_tag = NULL;
1973 u_int32_t resolver_tag_length = 0;
1974 u_int8_t *client_hostname = NULL;
1975 u_int32_t hostname_length = 0;
1976 uuid_t parent_id = {};
39037602
A
1977
1978 if (parsed_parameters == NULL) {
0a7de745 1979 return EINVAL;
39037602
A
1980 }
1981
1982 memset(parsed_parameters, 0, sizeof(struct necp_client_parsed_parameters));
1983
5ba3f43e 1984 while ((offset + sizeof(struct necp_tlv_header)) <= parameters_size) {
39037602
A
1985 u_int8_t type = necp_buffer_get_tlv_type(parameters, offset);
1986 u_int32_t length = necp_buffer_get_tlv_length(parameters, offset);
1987
5ba3f43e 1988 if (length > (parameters_size - (offset + sizeof(struct necp_tlv_header)))) {
813fb2f6
A
1989 // If the length is larger than what can fit in the remaining parameters size, bail
1990 NECPLOG(LOG_ERR, "Invalid TLV length (%u)", length);
1991 break;
1992 }
1993
1994 if (length > 0) {
39037602
A
1995 u_int8_t *value = necp_buffer_get_tlv_value(parameters, offset, NULL);
1996 if (value != NULL) {
1997 switch (type) {
0a7de745
A
1998 case NECP_CLIENT_PARAMETER_BOUND_INTERFACE: {
1999 if (length <= IFXNAMSIZ && length > 0) {
2000 ifnet_t bound_interface = NULL;
2001 char interface_name[IFXNAMSIZ];
2002 memcpy(interface_name, value, length);
2003 interface_name[length - 1] = 0; // Make sure the string is NULL terminated
2004 if (ifnet_find_by_name(interface_name, &bound_interface) == 0) {
2005 parsed_parameters->required_interface_index = bound_interface->if_index;
2006 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IF;
2007 ifnet_release(bound_interface);
39037602 2008 }
39037602 2009 }
0a7de745
A
2010 break;
2011 }
2012 case NECP_CLIENT_PARAMETER_LOCAL_ADDRESS: {
2013 if (length >= sizeof(struct necp_policy_condition_addr)) {
2014 struct necp_policy_condition_addr *address_struct = (struct necp_policy_condition_addr *)(void *)value;
2015 if (necp_client_address_is_valid(&address_struct->address.sa)) {
2016 memcpy(&parsed_parameters->local_addr, &address_struct->address, sizeof(address_struct->address));
2017 if (!necp_address_is_wildcard(&parsed_parameters->local_addr)) {
2018 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR;
39037602 2019 }
0a7de745
A
2020 if ((parsed_parameters->local_addr.sa.sa_family == AF_INET && parsed_parameters->local_addr.sin.sin_port) ||
2021 (parsed_parameters->local_addr.sa.sa_family == AF_INET6 && parsed_parameters->local_addr.sin6.sin6_port)) {
2022 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_LOCAL_PORT;
39037602
A
2023 }
2024 }
39037602 2025 }
0a7de745
A
2026 break;
2027 }
2028 case NECP_CLIENT_PARAMETER_LOCAL_ENDPOINT: {
2029 if (length >= sizeof(struct necp_client_endpoint)) {
2030 struct necp_client_endpoint *endpoint = (struct necp_client_endpoint *)(void *)value;
2031 if (necp_client_address_is_valid(&endpoint->u.sa)) {
2032 memcpy(&parsed_parameters->local_addr, &endpoint->u.sa, sizeof(union necp_sockaddr_union));
2033 if (!necp_address_is_wildcard(&parsed_parameters->local_addr)) {
2034 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR;
39037602 2035 }
0a7de745
A
2036 if ((parsed_parameters->local_addr.sa.sa_family == AF_INET && parsed_parameters->local_addr.sin.sin_port) ||
2037 (parsed_parameters->local_addr.sa.sa_family == AF_INET6 && parsed_parameters->local_addr.sin6.sin6_port)) {
2038 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_LOCAL_PORT;
39037602
A
2039 }
2040 }
39037602 2041 }
0a7de745
A
2042 break;
2043 }
2044 case NECP_CLIENT_PARAMETER_REMOTE_ADDRESS: {
2045 if (length >= sizeof(struct necp_policy_condition_addr)) {
2046 struct necp_policy_condition_addr *address_struct = (struct necp_policy_condition_addr *)(void *)value;
2047 if (necp_client_address_is_valid(&address_struct->address.sa)) {
2048 memcpy(&parsed_parameters->remote_addr, &address_struct->address, sizeof(address_struct->address));
2049 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REMOTE_ADDR;
39037602 2050 }
39037602 2051 }
0a7de745
A
2052 break;
2053 }
2054 case NECP_CLIENT_PARAMETER_REMOTE_ENDPOINT: {
2055 if (length >= sizeof(struct necp_client_endpoint)) {
2056 struct necp_client_endpoint *endpoint = (struct necp_client_endpoint *)(void *)value;
2057 if (necp_client_address_is_valid(&endpoint->u.sa)) {
2058 memcpy(&parsed_parameters->remote_addr, &endpoint->u.sa, sizeof(union necp_sockaddr_union));
2059 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REMOTE_ADDR;
39037602 2060 }
39037602 2061 }
0a7de745
A
2062 break;
2063 }
2064 case NECP_CLIENT_PARAMETER_PROHIBIT_INTERFACE: {
cb323159 2065 if (num_prohibited_interfaces >= NECP_MAX_INTERFACE_PARAMETERS) {
39037602
A
2066 break;
2067 }
0a7de745
A
2068 if (length <= IFXNAMSIZ && length > 0) {
2069 memcpy(parsed_parameters->prohibited_interfaces[num_prohibited_interfaces], value, length);
2070 parsed_parameters->prohibited_interfaces[num_prohibited_interfaces][length - 1] = 0; // Make sure the string is NULL terminated
2071 num_prohibited_interfaces++;
2072 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IF;
39037602 2073 }
0a7de745
A
2074 break;
2075 }
2076 case NECP_CLIENT_PARAMETER_REQUIRE_IF_TYPE: {
2077 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE) {
39037602
A
2078 break;
2079 }
0a7de745
A
2080 if (length >= sizeof(u_int8_t)) {
2081 memcpy(&parsed_parameters->required_interface_type, value, sizeof(u_int8_t));
2082 if (parsed_parameters->required_interface_type) {
2083 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE;
39037602 2084 }
39037602 2085 }
0a7de745
A
2086 break;
2087 }
2088 case NECP_CLIENT_PARAMETER_PROHIBIT_IF_TYPE: {
cb323159 2089 if (num_prohibited_interface_types >= NECP_MAX_INTERFACE_PARAMETERS) {
d9a64523
A
2090 break;
2091 }
0a7de745
A
2092 if (length >= sizeof(u_int8_t)) {
2093 memcpy(&parsed_parameters->prohibited_interface_types[num_prohibited_interface_types], value, sizeof(u_int8_t));
2094 num_prohibited_interface_types++;
2095 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IFTYPE;
39037602 2096 }
0a7de745
A
2097 break;
2098 }
2099 case NECP_CLIENT_PARAMETER_REQUIRE_AGENT: {
cb323159 2100 if (num_required_agents >= NECP_MAX_AGENT_PARAMETERS) {
39037602
A
2101 break;
2102 }
0a7de745
A
2103 if (length >= sizeof(uuid_t)) {
2104 memcpy(&parsed_parameters->required_netagents[num_required_agents], value, sizeof(uuid_t));
2105 num_required_agents++;
2106 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT;
39037602 2107 }
0a7de745
A
2108 break;
2109 }
2110 case NECP_CLIENT_PARAMETER_PROHIBIT_AGENT: {
cb323159 2111 if (num_prohibited_agents >= NECP_MAX_AGENT_PARAMETERS) {
d9a64523
A
2112 break;
2113 }
0a7de745
A
2114 if (length >= sizeof(uuid_t)) {
2115 memcpy(&parsed_parameters->prohibited_netagents[num_prohibited_agents], value, sizeof(uuid_t));
2116 num_prohibited_agents++;
2117 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT;
2118 }
2119 break;
2120 }
2121 case NECP_CLIENT_PARAMETER_PREFER_AGENT: {
cb323159 2122 if (num_preferred_agents >= NECP_MAX_AGENT_PARAMETERS) {
5ba3f43e
A
2123 break;
2124 }
0a7de745
A
2125 if (length >= sizeof(uuid_t)) {
2126 memcpy(&parsed_parameters->preferred_netagents[num_preferred_agents], value, sizeof(uuid_t));
2127 num_preferred_agents++;
2128 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT;
2129 }
2130 break;
2131 }
2132 case NECP_CLIENT_PARAMETER_AVOID_AGENT: {
cb323159 2133 if (num_avoided_agents >= NECP_MAX_AGENT_PARAMETERS) {
5ba3f43e
A
2134 break;
2135 }
0a7de745
A
2136 if (length >= sizeof(uuid_t)) {
2137 memcpy(&parsed_parameters->avoided_netagents[num_avoided_agents], value, sizeof(uuid_t));
2138 num_avoided_agents++;
2139 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT;
2140 }
2141 break;
2142 }
2143 case NECP_CLIENT_PARAMETER_REQUIRE_AGENT_TYPE: {
cb323159 2144 if (num_required_agent_types >= NECP_MAX_AGENT_PARAMETERS) {
5ba3f43e
A
2145 break;
2146 }
0a7de745
A
2147 if (length >= sizeof(struct necp_client_parameter_netagent_type)) {
2148 memcpy(&parsed_parameters->required_netagent_types[num_required_agent_types], value, sizeof(struct necp_client_parameter_netagent_type));
2149 num_required_agent_types++;
2150 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE;
2151 }
2152 break;
2153 }
2154 case NECP_CLIENT_PARAMETER_PROHIBIT_AGENT_TYPE: {
cb323159 2155 if (num_prohibited_agent_types >= NECP_MAX_AGENT_PARAMETERS) {
5ba3f43e
A
2156 break;
2157 }
0a7de745
A
2158 if (length >= sizeof(struct necp_client_parameter_netagent_type)) {
2159 memcpy(&parsed_parameters->prohibited_netagent_types[num_prohibited_agent_types], value, sizeof(struct necp_client_parameter_netagent_type));
2160 num_prohibited_agent_types++;
2161 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT_TYPE;
2162 }
2163 break;
2164 }
2165 case NECP_CLIENT_PARAMETER_PREFER_AGENT_TYPE: {
cb323159 2166 if (num_preferred_agent_types >= NECP_MAX_AGENT_PARAMETERS) {
5ba3f43e
A
2167 break;
2168 }
0a7de745
A
2169 if (length >= sizeof(struct necp_client_parameter_netagent_type)) {
2170 memcpy(&parsed_parameters->preferred_netagent_types[num_preferred_agent_types], value, sizeof(struct necp_client_parameter_netagent_type));
2171 num_preferred_agent_types++;
2172 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT_TYPE;
2173 }
2174 break;
2175 }
2176 case NECP_CLIENT_PARAMETER_AVOID_AGENT_TYPE: {
cb323159 2177 if (num_avoided_agent_types >= NECP_MAX_AGENT_PARAMETERS) {
5ba3f43e
A
2178 break;
2179 }
0a7de745
A
2180 if (length >= sizeof(struct necp_client_parameter_netagent_type)) {
2181 memcpy(&parsed_parameters->avoided_netagent_types[num_avoided_agent_types], value, sizeof(struct necp_client_parameter_netagent_type));
2182 num_avoided_agent_types++;
2183 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT_TYPE;
2184 }
2185 break;
2186 }
2187 case NECP_CLIENT_PARAMETER_FLAGS: {
2188 if (length >= sizeof(u_int32_t)) {
2189 memcpy(&parsed_parameters->flags, value, sizeof(parsed_parameters->flags));
2190 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_FLAGS;
2191 }
2192 break;
2193 }
2194 case NECP_CLIENT_PARAMETER_IP_PROTOCOL: {
cb323159
A
2195 if (length == sizeof(u_int16_t)) {
2196 u_int16_t large_ip_protocol = 0;
2197 memcpy(&large_ip_protocol, value, sizeof(large_ip_protocol));
2198 parsed_parameters->ip_protocol = (u_int8_t)large_ip_protocol;
2199 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_IP_PROTOCOL;
2200 } else if (length >= sizeof(parsed_parameters->ip_protocol)) {
0a7de745
A
2201 memcpy(&parsed_parameters->ip_protocol, value, sizeof(parsed_parameters->ip_protocol));
2202 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_IP_PROTOCOL;
2203 }
2204 break;
2205 }
cb323159
A
2206 case NECP_CLIENT_PARAMETER_TRANSPORT_PROTOCOL: {
2207 if (length >= sizeof(parsed_parameters->transport_protocol)) {
2208 memcpy(&parsed_parameters->transport_protocol, value, sizeof(parsed_parameters->transport_protocol));
2209 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_TRANSPORT_PROTOCOL;
2210 }
2211 break;
2212 }
0a7de745
A
2213 case NECP_CLIENT_PARAMETER_PID: {
2214 if (length >= sizeof(parsed_parameters->effective_pid)) {
2215 memcpy(&parsed_parameters->effective_pid, value, sizeof(parsed_parameters->effective_pid));
2216 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_EFFECTIVE_PID;
2217 }
2218 break;
2219 }
cb323159
A
2220 case NECP_CLIENT_PARAMETER_DELEGATED_UPID: {
2221 if (length >= sizeof(parsed_parameters->delegated_upid)) {
2222 memcpy(&parsed_parameters->delegated_upid, value, sizeof(parsed_parameters->delegated_upid));
2223 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_DELEGATED_UPID;
2224 }
2225 break;
2226 }
2227 case NECP_CLIENT_PARAMETER_ETHERTYPE: {
2228 if (length >= sizeof(parsed_parameters->ethertype)) {
2229 memcpy(&parsed_parameters->ethertype, value, sizeof(parsed_parameters->ethertype));
2230 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_ETHERTYPE;
2231 }
2232 break;
2233 }
0a7de745
A
2234 case NECP_CLIENT_PARAMETER_APPLICATION: {
2235 if (length >= sizeof(parsed_parameters->effective_uuid)) {
2236 memcpy(&parsed_parameters->effective_uuid, value, sizeof(parsed_parameters->effective_uuid));
2237 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_EFFECTIVE_UUID;
2238 }
2239 break;
2240 }
2241 case NECP_CLIENT_PARAMETER_TRAFFIC_CLASS: {
2242 if (length >= sizeof(parsed_parameters->traffic_class)) {
2243 memcpy(&parsed_parameters->traffic_class, value, sizeof(parsed_parameters->traffic_class));
2244 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_TRAFFIC_CLASS;
2245 }
2246 break;
2247 }
cb323159
A
2248 case NECP_CLIENT_PARAMETER_RESOLVER_TAG: {
2249 if (length > 0) {
2250 resolver_tag = (u_int8_t *)value;
2251 resolver_tag_length = length;
2252 }
2253 break;
2254 }
2255 case NECP_CLIENT_PARAMETER_DOMAIN: {
2256 if (length > 0) {
2257 client_hostname = (u_int8_t *)value;
2258 hostname_length = length;
2259 }
2260 break;
2261 }
2262 case NECP_CLIENT_PARAMETER_PARENT_ID: {
2263 if (length == sizeof(parent_id)) {
2264 uuid_copy(parent_id, value);
2265 }
2266 break;
2267 }
2268 case NECP_CLIENT_PARAMETER_LOCAL_ADDRESS_PREFERENCE: {
2269 if (length >= sizeof(parsed_parameters->local_address_preference)) {
2270 memcpy(&parsed_parameters->local_address_preference, value, sizeof(parsed_parameters->local_address_preference));
2271 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR_PREFERENCE;
2272 }
2273 break;
2274 }
0a7de745
A
2275 default: {
2276 break;
2277 }
5ba3f43e
A
2278 }
2279 }
2280 }
2281
2282 offset += sizeof(struct necp_tlv_header) + length;
2283 }
2284
cb323159
A
2285 if (resolver_tag != NULL) {
2286 union necp_sockaddr_union remote_addr;
2287 memcpy(&remote_addr, &parsed_parameters->remote_addr, sizeof(remote_addr));
2288 remote_addr.sin.sin_port = 0;
2289 const bool validated = necp_validate_resolver_answer(parent_id,
2290 client_hostname, hostname_length,
2291 (u_int8_t *)&remote_addr, sizeof(remote_addr),
2292 resolver_tag, resolver_tag_length);
2293 if (!validated) {
2294 error = EAUTH;
2295 NECPLOG(LOG_ERR, "Failed to validate answer for hostname %s", client_hostname);
2296 }
2297 }
2298
0a7de745 2299 return error;
5ba3f43e
A
2300}
2301
2302static int
2303necp_client_parse_result(u_int8_t *result,
0a7de745
A
2304 u_int32_t result_size,
2305 union necp_sockaddr_union *local_address,
2306 union necp_sockaddr_union *remote_address,
2307 void **flow_stats)
5ba3f43e 2308{
d9a64523 2309#pragma unused(flow_stats)
5ba3f43e
A
2310 int error = 0;
2311 size_t offset = 0;
2312
2313 while ((offset + sizeof(struct necp_tlv_header)) <= result_size) {
2314 u_int8_t type = necp_buffer_get_tlv_type(result, offset);
2315 u_int32_t length = necp_buffer_get_tlv_length(result, offset);
2316
2317 if (length > 0 && (offset + sizeof(struct necp_tlv_header) + length) <= result_size) {
2318 u_int8_t *value = necp_buffer_get_tlv_value(result, offset, NULL);
2319 if (value != NULL) {
2320 switch (type) {
0a7de745
A
2321 case NECP_CLIENT_RESULT_LOCAL_ENDPOINT: {
2322 if (length >= sizeof(struct necp_client_endpoint)) {
2323 struct necp_client_endpoint *endpoint = (struct necp_client_endpoint *)(void *)value;
2324 if (local_address != NULL && necp_client_address_is_valid(&endpoint->u.sa)) {
2325 memcpy(local_address, &endpoint->u.sa, endpoint->u.sa.sa_len);
5ba3f43e 2326 }
5ba3f43e 2327 }
0a7de745
A
2328 break;
2329 }
2330 case NECP_CLIENT_RESULT_REMOTE_ENDPOINT: {
2331 if (length >= sizeof(struct necp_client_endpoint)) {
2332 struct necp_client_endpoint *endpoint = (struct necp_client_endpoint *)(void *)value;
2333 if (remote_address != NULL && necp_client_address_is_valid(&endpoint->u.sa)) {
2334 memcpy(remote_address, &endpoint->u.sa, endpoint->u.sa.sa_len);
5ba3f43e 2335 }
39037602 2336 }
0a7de745
A
2337 break;
2338 }
2339 default: {
2340 break;
2341 }
39037602
A
2342 }
2343 }
2344 }
2345
5ba3f43e 2346 offset += sizeof(struct necp_tlv_header) + length;
39037602
A
2347 }
2348
0a7de745 2349 return error;
39037602
A
2350}
2351
d9a64523
A
2352static struct necp_client_flow_registration *
2353necp_client_create_flow_registration(struct necp_fd_data *fd_data, struct necp_client *client)
2354{
2355 NECP_FD_ASSERT_LOCKED(fd_data);
2356 NECP_CLIENT_ASSERT_LOCKED(client);
2357
2358 struct necp_client_flow_registration *new_registration = mcache_alloc(necp_flow_registration_cache, MCR_SLEEP);
2359 if (new_registration == NULL) {
2360 return NULL;
2361 }
2362
2363 memset(new_registration, 0, sizeof(*new_registration));
2364
2365 new_registration->last_interface_details = combine_interface_details(IFSCOPE_NONE, NSTAT_IFNET_IS_UNKNOWN_TYPE);
2366
2367 necp_generate_client_id(new_registration->registration_id, true);
2368 LIST_INIT(&new_registration->flow_list);
2369
2370 // Add registration to client list
2371 RB_INSERT(_necp_client_flow_tree, &client->flow_registrations, new_registration);
2372
2373 // Add registration to fd list
2374 RB_INSERT(_necp_fd_flow_tree, &fd_data->flows, new_registration);
2375
2376 // Add registration to global tree for lookup
2377 NECP_FLOW_TREE_LOCK_EXCLUSIVE();
2378 RB_INSERT(_necp_client_flow_global_tree, &necp_client_flow_global_tree, new_registration);
2379 NECP_FLOW_TREE_UNLOCK();
2380
2381 new_registration->client = client;
2382
2383 // Start out assuming there is nothing to read from the flow
2384 new_registration->flow_result_read = true;
2385
2386 return new_registration;
2387}
2388
2389static void
2390necp_client_add_socket_flow(struct necp_client_flow_registration *flow_registration,
0a7de745 2391 struct inpcb *inp)
d9a64523
A
2392{
2393 struct necp_client_flow *new_flow = mcache_alloc(necp_flow_cache, MCR_SLEEP);
2394 if (new_flow == NULL) {
2395 NECPLOG0(LOG_ERR, "Failed to allocate socket flow");
2396 return;
2397 }
2398
2399 memset(new_flow, 0, sizeof(*new_flow));
2400
2401 new_flow->socket = TRUE;
2402 new_flow->u.socket_handle = inp;
2403 new_flow->u.cb = inp->necp_cb;
2404
2405 OSIncrementAtomic(&necp_socket_flow_count);
2406
2407 LIST_INSERT_HEAD(&flow_registration->flow_list, new_flow, flow_chain);
2408}
2409
cb323159
A
2410static int
2411necp_client_register_socket_inner(pid_t pid, uuid_t client_id, struct inpcb *inp, bool is_listener)
5ba3f43e
A
2412{
2413 int error = 0;
d9a64523 2414 struct necp_fd_data *client_fd = NULL;
5ba3f43e
A
2415 bool found_client = FALSE;
2416
d9a64523
A
2417 NECP_FD_LIST_LOCK_SHARED();
2418 LIST_FOREACH(client_fd, &necp_fd_list, chain) {
2419 NECP_FD_LOCK(client_fd);
2420 struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
2421 if (client != NULL) {
2422 if (!pid || client->proc_pid == pid) {
cb323159 2423 if (is_listener) {
d9a64523 2424 found_client = TRUE;
cb323159
A
2425 } else {
2426 // Find client flow and assign from socket
2427 struct necp_client_flow_registration *flow_registration = necp_client_find_flow(client, client_id);
2428 if (flow_registration != NULL) {
2429 // Found the right client and flow registration, add a new flow
d9a64523
A
2430 found_client = TRUE;
2431 necp_client_add_socket_flow(flow_registration, inp);
cb323159
A
2432 } else if (RB_EMPTY(&client->flow_registrations) && !necp_client_id_is_flow(client_id)) {
2433 // No flows yet on this client, add a new registration
2434 flow_registration = necp_client_create_flow_registration(client_fd, client);
2435 if (flow_registration == NULL) {
2436 error = ENOMEM;
2437 } else {
2438 // Add a new flow
2439 found_client = TRUE;
2440 necp_client_add_socket_flow(flow_registration, inp);
2441 }
d9a64523
A
2442 }
2443 }
2444 }
5ba3f43e 2445
d9a64523 2446 NECP_CLIENT_UNLOCK(client);
5ba3f43e 2447 }
d9a64523 2448 NECP_FD_UNLOCK(client_fd);
5ba3f43e 2449
d9a64523
A
2450 if (found_client) {
2451 break;
2452 }
5ba3f43e 2453 }
d9a64523 2454 NECP_FD_LIST_UNLOCK();
5ba3f43e
A
2455
2456 if (!found_client) {
2457 error = ENOENT;
2458 } else {
d9a64523 2459 // Count the sockets that have the NECP client UUID set
5ba3f43e
A
2460 struct socket *so = inp->inp_socket;
2461 if (!(so->so_flags1 & SOF1_HAS_NECP_CLIENT_UUID)) {
2462 so->so_flags1 |= SOF1_HAS_NECP_CLIENT_UUID;
2463 INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_necp_clientuuid_total);
2464 }
2465 }
2466
0a7de745 2467 return error;
5ba3f43e
A
2468}
2469
cb323159
A
2470int
2471necp_client_register_socket_flow(pid_t pid, uuid_t client_id, struct inpcb *inp)
2472{
2473 return necp_client_register_socket_inner(pid, client_id, inp, false);
2474}
2475
2476int
2477necp_client_register_socket_listener(pid_t pid, uuid_t client_id, struct inpcb *inp)
2478{
2479 return necp_client_register_socket_inner(pid, client_id, inp, true);
2480}
2481
2482
5ba3f43e 2483static void
d9a64523 2484necp_client_add_multipath_interface_flows(struct necp_client_flow_registration *flow_registration,
0a7de745
A
2485 struct necp_client *client,
2486 struct mppcb *mpp)
5ba3f43e 2487{
d9a64523
A
2488 flow_registration->interface_handle = mpp;
2489 flow_registration->interface_cb = mpp->necp_cb;
5ba3f43e 2490
d9a64523
A
2491 proc_t proc = proc_find(client->proc_pid);
2492 if (proc == PROC_NULL) {
2493 return;
2494 }
5ba3f43e 2495
d9a64523
A
2496 // Traverse all interfaces and add a tracking flow if needed
2497 necp_flow_add_interface_flows(proc, client, flow_registration, true);
2498
2499 proc_rele(proc);
2500 proc = PROC_NULL;
2501}
2502
2503int
2504necp_client_register_multipath_cb(pid_t pid, uuid_t client_id, struct mppcb *mpp)
2505{
2506 int error = 0;
2507 struct necp_fd_data *client_fd = NULL;
2508 bool found_client = FALSE;
2509
2510 NECP_FD_LIST_LOCK_SHARED();
2511 LIST_FOREACH(client_fd, &necp_fd_list, chain) {
2512 NECP_FD_LOCK(client_fd);
2513 struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
2514 if (client != NULL) {
2515 if (!pid || client->proc_pid == pid) {
2516 struct necp_client_flow_registration *flow_registration = necp_client_find_flow(client, client_id);
2517 if (flow_registration != NULL) {
2518 // Found the right client and flow registration, add a new flow
2519 found_client = TRUE;
2520 necp_client_add_multipath_interface_flows(flow_registration, client, mpp);
2521 } else if (RB_EMPTY(&client->flow_registrations) && !necp_client_id_is_flow(client_id)) {
2522 // No flows yet on this client, add a new registration
2523 flow_registration = necp_client_create_flow_registration(client_fd, client);
2524 if (flow_registration == NULL) {
2525 error = ENOMEM;
2526 } else {
2527 // Add a new flow
2528 found_client = TRUE;
2529 necp_client_add_multipath_interface_flows(flow_registration, client, mpp);
2530 }
2531 }
2532 }
2533
2534 NECP_CLIENT_UNLOCK(client);
2535 }
2536 NECP_FD_UNLOCK(client_fd);
2537
2538 if (found_client) {
2539 break;
2540 }
2541 }
2542 NECP_FD_LIST_UNLOCK();
2543
2544 if (!found_client && error == 0) {
2545 error = ENOENT;
2546 }
2547
0a7de745 2548 return error;
d9a64523
A
2549}
2550
0a7de745
A
2551#define NETAGENT_DOMAIN_RADIO_MANAGER "WirelessRadioManager"
2552#define NETAGENT_TYPE_RADIO_MANAGER "WirelessRadioManager:BB Manager"
d9a64523
A
2553
2554static int
2555necp_client_lookup_bb_radio_manager(struct necp_client *client,
0a7de745 2556 uuid_t netagent_uuid)
d9a64523
A
2557{
2558 char netagent_domain[NETAGENT_DOMAINSIZE];
2559 char netagent_type[NETAGENT_TYPESIZE];
2560 struct necp_aggregate_result result;
2561 proc_t proc;
2562 int error;
2563
2564 proc = proc_find(client->proc_pid);
2565 if (proc == PROC_NULL) {
2566 return ESRCH;
2567 }
2568
2569 error = necp_application_find_policy_match_internal(proc, client->parameters, (u_int32_t)client->parameters_length,
ea3f0419 2570 &result, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, true, true, NULL);
d9a64523
A
2571
2572 proc_rele(proc);
2573 proc = PROC_NULL;
2574
2575 if (error) {
2576 return error;
2577 }
2578
2579 for (int i = 0; i < NECP_MAX_NETAGENTS; i++) {
2580 if (uuid_is_null(result.netagents[i])) {
2581 // Passed end of valid agents
2582 break;
2583 }
2584
2585 memset(&netagent_domain, 0, NETAGENT_DOMAINSIZE);
2586 memset(&netagent_type, 0, NETAGENT_TYPESIZE);
2587 if (netagent_get_agent_domain_and_type(result.netagents[i], netagent_domain, netagent_type) == FALSE) {
2588 continue;
2589 }
2590
2591 if (strncmp(netagent_domain, NETAGENT_DOMAIN_RADIO_MANAGER, NETAGENT_DOMAINSIZE) != 0) {
5ba3f43e
A
2592 continue;
2593 }
2594
d9a64523
A
2595 if (strncmp(netagent_type, NETAGENT_TYPE_RADIO_MANAGER, NETAGENT_TYPESIZE) != 0) {
2596 continue;
2597 }
2598
2599 uuid_copy(netagent_uuid, result.netagents[i]);
5ba3f43e 2600
d9a64523
A
2601 break;
2602 }
2603
2604 return 0;
2605}
2606
2607static int
2608necp_client_assert_bb_radio_manager_common(struct necp_client *client, bool assert)
2609{
2610 uuid_t netagent_uuid;
2611 uint8_t assert_type;
2612 int error;
2613
2614 error = necp_client_lookup_bb_radio_manager(client, netagent_uuid);
2615 if (error) {
2616 NECPLOG0(LOG_ERR, "BB radio manager agent not found");
2617 return error;
2618 }
2619
2620 // Before unasserting, verify that the assertion was already taken
2621 if (assert == FALSE) {
2622 assert_type = NETAGENT_MESSAGE_TYPE_CLIENT_UNASSERT;
2623
2624 if (!necp_client_remove_assertion(client, netagent_uuid)) {
2625 return EINVAL;
5ba3f43e 2626 }
d9a64523
A
2627 } else {
2628 assert_type = NETAGENT_MESSAGE_TYPE_CLIENT_ASSERT;
2629 }
2630
2631 error = netagent_client_message(netagent_uuid, client->client_id, client->proc_pid, client->agent_handle, assert_type);
2632 if (error) {
2633 NECPLOG0(LOG_ERR, "netagent_client_message failed");
2634 return error;
5ba3f43e 2635 }
d9a64523
A
2636
2637 // Only save the assertion if the action succeeded
2638 if (assert == TRUE) {
2639 necp_client_add_assertion(client, netagent_uuid);
2640 }
2641
2642 return 0;
5ba3f43e
A
2643}
2644
2645int
d9a64523 2646necp_client_assert_bb_radio_manager(uuid_t client_id, bool assert)
5ba3f43e 2647{
d9a64523 2648 struct necp_client *client;
5ba3f43e 2649 int error = 0;
5ba3f43e
A
2650
2651 NECP_CLIENT_TREE_LOCK_SHARED();
2652
d9a64523 2653 client = necp_find_client_and_lock(client_id);
5ba3f43e 2654
d9a64523
A
2655 if (client) {
2656 // Found the right client!
2657 error = necp_client_assert_bb_radio_manager_common(client, assert);
5ba3f43e
A
2658
2659 NECP_CLIENT_UNLOCK(client);
d9a64523
A
2660 } else {
2661 NECPLOG0(LOG_ERR, "Couldn't find client");
2662 error = ENOENT;
5ba3f43e
A
2663 }
2664
2665 NECP_CLIENT_TREE_UNLOCK();
2666
0a7de745 2667 return error;
5ba3f43e
A
2668}
2669
5ba3f43e
A
2670static int
2671necp_client_unregister_socket_flow(uuid_t client_id, void *handle)
39037602
A
2672{
2673 int error = 0;
2674 struct necp_fd_data *client_fd = NULL;
2675 bool found_client = FALSE;
2676 bool client_updated = FALSE;
2677
5ba3f43e
A
2678 NECP_FD_LIST_LOCK_SHARED();
2679 LIST_FOREACH(client_fd, &necp_fd_list, chain) {
2680 NECP_FD_LOCK(client_fd);
2681
2682 struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
2683 if (client != NULL) {
d9a64523
A
2684 struct necp_client_flow_registration *flow_registration = necp_client_find_flow(client, client_id);
2685 if (flow_registration != NULL) {
2686 // Found the right client and flow!
2687 found_client = TRUE;
5ba3f43e 2688
d9a64523
A
2689 // Remove flow assignment
2690 struct necp_client_flow *search_flow = NULL;
2691 struct necp_client_flow *temp_flow = NULL;
2692 LIST_FOREACH_SAFE(search_flow, &flow_registration->flow_list, flow_chain, temp_flow) {
2693 if (search_flow->socket && search_flow->u.socket_handle == handle) {
2694 if (search_flow->assigned_results != NULL) {
2695 FREE(search_flow->assigned_results, M_NETAGENT);
2696 search_flow->assigned_results = NULL;
2697 }
2698 client_updated = TRUE;
2699 flow_registration->flow_result_read = FALSE;
2700 LIST_REMOVE(search_flow, flow_chain);
2701 OSDecrementAtomic(&necp_socket_flow_count);
2702 mcache_free(necp_flow_cache, search_flow);
5ba3f43e 2703 }
5ba3f43e
A
2704 }
2705 }
2706
2707 NECP_CLIENT_UNLOCK(client);
2708 }
2709
2710 if (client_updated) {
5ba3f43e
A
2711 necp_fd_notify(client_fd, true);
2712 }
2713 NECP_FD_UNLOCK(client_fd);
2714
2715 if (found_client) {
2716 break;
2717 }
2718 }
2719 NECP_FD_LIST_UNLOCK();
2720
2721 if (!found_client) {
2722 error = ENOENT;
2723 }
2724
0a7de745 2725 return error;
5ba3f43e
A
2726}
2727
2728static int
2729necp_client_unregister_multipath_cb(uuid_t client_id, void *handle)
2730{
2731 int error = 0;
2732 bool found_client = FALSE;
2733
2734 NECP_CLIENT_TREE_LOCK_SHARED();
2735
d9a64523 2736 struct necp_client *client = necp_find_client_and_lock(client_id);
5ba3f43e 2737 if (client != NULL) {
d9a64523
A
2738 struct necp_client_flow_registration *flow_registration = necp_client_find_flow(client, client_id);
2739 if (flow_registration != NULL) {
2740 // Found the right client and flow!
2741 found_client = TRUE;
5ba3f43e 2742
d9a64523
A
2743 // Remove flow assignment
2744 struct necp_client_flow *search_flow = NULL;
2745 struct necp_client_flow *temp_flow = NULL;
2746 LIST_FOREACH_SAFE(search_flow, &flow_registration->flow_list, flow_chain, temp_flow) {
2747 if (!search_flow->socket && !search_flow->nexus &&
0a7de745 2748 search_flow->u.socket_handle == handle) {
d9a64523
A
2749 search_flow->u.socket_handle = NULL;
2750 search_flow->u.cb = NULL;
2751 }
5ba3f43e 2752 }
39037602 2753
d9a64523
A
2754 flow_registration->interface_handle = NULL;
2755 flow_registration->interface_cb = NULL;
2756 }
5ba3f43e
A
2757
2758 NECP_CLIENT_UNLOCK(client);
2759 }
2760
2761 NECP_CLIENT_TREE_UNLOCK();
2762
2763 if (!found_client) {
2764 error = ENOENT;
2765 }
2766
0a7de745 2767 return error;
5ba3f43e
A
2768}
2769
2770int
2771necp_client_assign_from_socket(pid_t pid, uuid_t client_id, struct inpcb *inp)
2772{
2773 int error = 0;
2774 struct necp_fd_data *client_fd = NULL;
2775 bool found_client = FALSE;
2776 bool client_updated = FALSE;
2777
2778 NECP_FD_LIST_LOCK_SHARED();
39037602 2779 LIST_FOREACH(client_fd, &necp_fd_list, chain) {
5ba3f43e
A
2780 if (pid && client_fd->proc_pid != pid) {
2781 continue;
2782 }
39037602 2783
5ba3f43e
A
2784 proc_t proc = proc_find(client_fd->proc_pid);
2785 if (proc == PROC_NULL) {
2786 continue;
2787 }
2788
2789 NECP_FD_LOCK(client_fd);
2790
2791 struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
2792 if (client != NULL) {
d9a64523
A
2793 struct necp_client_flow_registration *flow_registration = necp_client_find_flow(client, client_id);
2794 if (flow_registration == NULL && RB_EMPTY(&client->flow_registrations) && !necp_client_id_is_flow(client_id)) {
2795 // No flows yet on this client, add a new registration
2796 flow_registration = necp_client_create_flow_registration(client_fd, client);
2797 if (flow_registration == NULL) {
2798 error = ENOMEM;
2799 }
2800 }
2801 if (flow_registration != NULL) {
2802 // Found the right client and flow!
2803 found_client = TRUE;
5ba3f43e 2804
d9a64523
A
2805 struct necp_client_flow *flow = NULL;
2806 LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
2807 if (flow->socket && flow->u.socket_handle == inp) {
2808 // Release prior results and route
2809 if (flow->assigned_results != NULL) {
2810 FREE(flow->assigned_results, M_NETAGENT);
2811 flow->assigned_results = NULL;
2812 }
5ba3f43e 2813
d9a64523
A
2814 ifnet_t ifp = NULL;
2815 if ((inp->inp_flags & INP_BOUND_IF) && inp->inp_boundifp) {
2816 ifp = inp->inp_boundifp;
2817 } else {
2818 ifp = inp->inp_last_outifp;
2819 }
5ba3f43e 2820
d9a64523
A
2821 if (ifp != NULL) {
2822 flow->interface_index = ifp->if_index;
2823 } else {
2824 flow->interface_index = IFSCOPE_NONE;
2825 }
5ba3f43e 2826
d9a64523
A
2827 if (inp->inp_vflag & INP_IPV4) {
2828 flow->local_addr.sin.sin_family = AF_INET;
2829 flow->local_addr.sin.sin_len = sizeof(struct sockaddr_in);
2830 flow->local_addr.sin.sin_port = inp->inp_lport;
2831 memcpy(&flow->local_addr.sin.sin_addr, &inp->inp_laddr, sizeof(struct in_addr));
2832
2833 flow->remote_addr.sin.sin_family = AF_INET;
2834 flow->remote_addr.sin.sin_len = sizeof(struct sockaddr_in);
2835 flow->remote_addr.sin.sin_port = inp->inp_fport;
2836 memcpy(&flow->remote_addr.sin.sin_addr, &inp->inp_faddr, sizeof(struct in_addr));
2837 } else if (inp->inp_vflag & INP_IPV6) {
2838 in6_ip6_to_sockaddr(&inp->in6p_laddr, inp->inp_lport, &flow->local_addr.sin6, sizeof(flow->local_addr));
2839 in6_ip6_to_sockaddr(&inp->in6p_faddr, inp->inp_fport, &flow->remote_addr.sin6, sizeof(flow->remote_addr));
2840 }
5ba3f43e 2841
d9a64523
A
2842 flow->viable = necp_client_flow_is_viable(proc, client, flow);
2843
2844 uuid_t empty_uuid;
2845 uuid_clear(empty_uuid);
2846 flow->assigned = TRUE;
2847 flow->assigned_results = necp_create_nexus_assign_message(empty_uuid, 0, NULL, 0,
0a7de745
A
2848 (struct necp_client_endpoint *)&flow->local_addr,
2849 (struct necp_client_endpoint *)&flow->remote_addr,
cb323159 2850 NULL, 0, NULL, &flow->assigned_results_length);
d9a64523
A
2851 flow_registration->flow_result_read = FALSE;
2852 client_updated = TRUE;
2853 break;
2854 }
39037602
A
2855 }
2856 }
5ba3f43e
A
2857
2858 NECP_CLIENT_UNLOCK(client);
39037602
A
2859 }
2860 if (client_updated) {
2861 necp_fd_notify(client_fd, true);
2862 }
5ba3f43e
A
2863 NECP_FD_UNLOCK(client_fd);
2864
2865 proc_rele(proc);
2866 proc = PROC_NULL;
39037602
A
2867
2868 if (found_client) {
2869 break;
2870 }
2871 }
5ba3f43e 2872 NECP_FD_LIST_UNLOCK();
39037602 2873
d9a64523
A
2874 if (error == 0) {
2875 if (!found_client) {
2876 error = ENOENT;
2877 } else if (!client_updated) {
2878 error = EINVAL;
2879 }
5ba3f43e
A
2880 }
2881
0a7de745 2882 return error;
5ba3f43e
A
2883}
2884
cb323159
A
2885bool
2886necp_socket_is_allowed_to_recv_on_interface(struct inpcb *inp, ifnet_t interface)
2887{
2888 if (interface == NULL ||
2889 inp == NULL ||
2890 !(inp->inp_flags2 & INP2_EXTERNAL_PORT) ||
2891 uuid_is_null(inp->necp_client_uuid)) {
2892 // If there's no interface or client ID to check,
2893 // or if this is not a listener, pass.
2894 // Outbound connections will have already been
2895 // validated for policy.
2896 return TRUE;
2897 }
2898
2899 // Only filter out listener sockets (no remote address specified)
2900 if ((inp->inp_vflag & INP_IPV4) &&
2901 inp->inp_faddr.s_addr != INADDR_ANY) {
2902 return TRUE;
2903 }
2904 if ((inp->inp_vflag & INP_IPV6) &&
2905 !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
2906 return TRUE;
2907 }
2908
2909 bool allowed = TRUE;
2910
2911 NECP_CLIENT_TREE_LOCK_SHARED();
2912
2913 struct necp_client *client = necp_find_client_and_lock(inp->necp_client_uuid);
2914 if (client != NULL) {
2915 struct necp_client_parsed_parameters *parsed_parameters = NULL;
2916
2917 MALLOC(parsed_parameters, struct necp_client_parsed_parameters *, sizeof(*parsed_parameters), M_NECP, (M_WAITOK | M_ZERO));
2918 if (parsed_parameters != NULL) {
2919 int error = necp_client_parse_parameters(client->parameters, (u_int32_t)client->parameters_length, parsed_parameters);
2920 if (error == 0) {
2921 if (!necp_ifnet_matches_parameters(interface, parsed_parameters, 0, NULL, true, false)) {
2922 allowed = FALSE;
2923 }
2924 }
2925 FREE(parsed_parameters, M_NECP);
2926 }
2927
2928 NECP_CLIENT_UNLOCK(client);
2929 }
2930
2931 NECP_CLIENT_TREE_UNLOCK();
2932
2933 return allowed;
2934}
2935
5ba3f43e
A
2936int
2937necp_update_flow_protoctl_event(uuid_t netagent_uuid, uuid_t client_id,
2938 uint32_t protoctl_event_code, uint32_t protoctl_event_val,
2939 uint32_t protoctl_event_tcp_seq_number)
2940{
2941 int error = 0;
2942 struct necp_fd_data *client_fd = NULL;
2943 bool found_client = FALSE;
2944 bool client_updated = FALSE;
2945
2946 NECP_FD_LIST_LOCK_SHARED();
2947 LIST_FOREACH(client_fd, &necp_fd_list, chain) {
2948 proc_t proc = proc_find(client_fd->proc_pid);
2949 if (proc == PROC_NULL) {
2950 continue;
2951 }
2952
2953 NECP_FD_LOCK(client_fd);
2954
2955 struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
2956 if (client != NULL) {
d9a64523
A
2957 struct necp_client_flow_registration *flow_registration = necp_client_find_flow(client, client_id);
2958 if (flow_registration != NULL) {
2959 // Found the right client and flow!
2960 found_client = TRUE;
5ba3f43e 2961
d9a64523
A
2962 struct necp_client_flow *flow = NULL;
2963 LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
2964 // Verify that the client nexus agent matches
f427ee49
A
2965 if ((flow->nexus && uuid_compare(flow->u.nexus_agent, netagent_uuid) == 0) ||
2966 flow->socket) {
d9a64523
A
2967 flow->has_protoctl_event = TRUE;
2968 flow->protoctl_event.protoctl_event_code = protoctl_event_code;
2969 flow->protoctl_event.protoctl_event_val = protoctl_event_val;
2970 flow->protoctl_event.protoctl_event_tcp_seq_num = protoctl_event_tcp_seq_number;
2971 flow_registration->flow_result_read = FALSE;
2972 client_updated = TRUE;
2973 break;
2974 }
5ba3f43e
A
2975 }
2976 }
2977
2978 NECP_CLIENT_UNLOCK(client);
2979 }
2980
2981 if (client_updated) {
2982 necp_fd_notify(client_fd, true);
2983 }
2984
2985 NECP_FD_UNLOCK(client_fd);
2986 proc_rele(proc);
2987 proc = PROC_NULL;
2988
2989 if (found_client) {
2990 break;
2991 }
2992 }
2993 NECP_FD_LIST_UNLOCK();
39037602 2994
5ba3f43e
A
2995 if (!found_client) {
2996 error = ENOENT;
2997 } else if (!client_updated) {
2998 error = EINVAL;
2999 }
0a7de745 3000 return error;
5ba3f43e
A
3001}
3002
3003static bool
a39ff7e2 3004necp_assign_client_result_locked(struct proc *proc,
0a7de745
A
3005 struct necp_fd_data *client_fd,
3006 struct necp_client *client,
3007 struct necp_client_flow_registration *flow_registration,
3008 uuid_t netagent_uuid,
3009 u_int8_t *assigned_results,
3010 size_t assigned_results_length,
3011 bool notify_fd)
5ba3f43e
A
3012{
3013 bool client_updated = FALSE;
3014
3015 NECP_FD_ASSERT_LOCKED(client_fd);
3016 NECP_CLIENT_ASSERT_LOCKED(client);
3017
3018 struct necp_client_flow *flow = NULL;
d9a64523 3019 LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
5ba3f43e
A
3020 // Verify that the client nexus agent matches
3021 if (flow->nexus &&
0a7de745 3022 uuid_compare(flow->u.nexus_agent, netagent_uuid) == 0) {
5ba3f43e
A
3023 // Release prior results and route
3024 if (flow->assigned_results != NULL) {
3025 FREE(flow->assigned_results, M_NETAGENT);
3026 flow->assigned_results = NULL;
3027 }
3028
d9a64523 3029 void *nexus_stats = NULL;
5ba3f43e
A
3030 if (assigned_results != NULL && assigned_results_length > 0) {
3031 int error = necp_client_parse_result(assigned_results, (u_int32_t)assigned_results_length,
0a7de745 3032 &flow->local_addr, &flow->remote_addr, &nexus_stats);
5ba3f43e
A
3033 VERIFY(error == 0);
3034 }
3035
3036 flow->viable = necp_client_flow_is_viable(proc, client, flow);
3037
3038 flow->assigned = TRUE;
3039 flow->assigned_results = assigned_results;
3040 flow->assigned_results_length = assigned_results_length;
d9a64523 3041 flow_registration->flow_result_read = FALSE;
5ba3f43e
A
3042 client_updated = TRUE;
3043 break;
3044 }
3045 }
3046
a39ff7e2 3047 if (client_updated && notify_fd) {
5ba3f43e
A
3048 necp_fd_notify(client_fd, true);
3049 }
3050
3051 // if not updated, client must free assigned_results
0a7de745 3052 return client_updated;
5ba3f43e
A
3053}
3054
3055int
3056necp_assign_client_result(uuid_t netagent_uuid, uuid_t client_id,
0a7de745 3057 u_int8_t *assigned_results, size_t assigned_results_length)
5ba3f43e
A
3058{
3059 int error = 0;
3060 struct necp_fd_data *client_fd = NULL;
3061 bool found_client = FALSE;
3062 bool client_updated = FALSE;
3063
3064 NECP_FD_LIST_LOCK_SHARED();
3065
3066 LIST_FOREACH(client_fd, &necp_fd_list, chain) {
3067 proc_t proc = proc_find(client_fd->proc_pid);
3068 if (proc == PROC_NULL) {
3069 continue;
3070 }
3071
3072 NECP_FD_LOCK(client_fd);
3073 struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
3074 if (client != NULL) {
d9a64523
A
3075 struct necp_client_flow_registration *flow_registration = necp_client_find_flow(client, client_id);
3076 if (flow_registration != NULL) {
3077 // Found the right client and flow!
3078 found_client = TRUE;
3079 if (necp_assign_client_result_locked(proc, client_fd, client, flow_registration, netagent_uuid,
0a7de745 3080 assigned_results, assigned_results_length, true)) {
d9a64523
A
3081 client_updated = TRUE;
3082 }
5ba3f43e
A
3083 }
3084
3085 NECP_CLIENT_UNLOCK(client);
3086 }
3087 NECP_FD_UNLOCK(client_fd);
3088
3089 proc_rele(proc);
3090 proc = PROC_NULL;
3091
d9a64523
A
3092 if (found_client) {
3093 break;
3094 }
3095 }
3096
3097 NECP_FD_LIST_UNLOCK();
3098
3099 // upon error, client must free assigned_results
3100 if (!found_client) {
3101 error = ENOENT;
3102 } else if (!client_updated) {
3103 error = EINVAL;
3104 }
3105
0a7de745 3106 return error;
d9a64523
A
3107}
3108
3109/// Client updating
3110
3111static bool
3112necp_update_parsed_parameters(struct necp_client_parsed_parameters *parsed_parameters,
0a7de745 3113 struct necp_aggregate_result *result)
d9a64523
A
3114{
3115 if (parsed_parameters == NULL ||
0a7de745
A
3116 result == NULL) {
3117 return false;
d9a64523
A
3118 }
3119
3120 bool updated = false;
3121 for (int i = 0; i < NECP_MAX_NETAGENTS; i++) {
3122 if (uuid_is_null(result->netagents[i])) {
3123 // Passed end of valid agents
3124 break;
3125 }
3126
3127 if (!(result->netagent_use_flags[i] & NECP_AGENT_USE_FLAG_SCOPE)) {
3128 // Not a scoped agent, ignore
3129 continue;
3130 }
3131
3132 // This is a scoped agent. Add it to the required agents.
3133 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT) {
3134 // Already some required agents, add this at the end
cb323159 3135 for (int j = 0; j < NECP_MAX_AGENT_PARAMETERS; j++) {
d9a64523
A
3136 if (uuid_compare(parsed_parameters->required_netagents[j], result->netagents[i]) == 0) {
3137 // Already required, break
3138 break;
3139 }
3140 if (uuid_is_null(parsed_parameters->required_netagents[j])) {
3141 // Add here
3142 memcpy(&parsed_parameters->required_netagents[j], result->netagents[i], sizeof(uuid_t));
3143 updated = true;
3144 break;
3145 }
3146 }
3147 } else {
3148 // No required agents yet, add this one
3149 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT;
3150 memcpy(&parsed_parameters->required_netagents[0], result->netagents[i], sizeof(uuid_t));
3151 updated = true;
3152 }
3153
3154 // Remove requirements for agents of the same type
3155 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE) {
3156 char remove_agent_domain[NETAGENT_DOMAINSIZE] = { 0 };
3157 char remove_agent_type[NETAGENT_TYPESIZE] = { 0 };
3158 if (netagent_get_agent_domain_and_type(result->netagents[i], remove_agent_domain, remove_agent_type)) {
cb323159 3159 for (int j = 0; j < NECP_MAX_AGENT_PARAMETERS; j++) {
d9a64523 3160 if (strlen(parsed_parameters->required_netagent_types[j].netagent_domain) == 0 &&
0a7de745 3161 strlen(parsed_parameters->required_netagent_types[j].netagent_type) == 0) {
d9a64523
A
3162 break;
3163 }
3164
3165 if (strncmp(parsed_parameters->required_netagent_types[j].netagent_domain, remove_agent_domain, NETAGENT_DOMAINSIZE) == 0 &&
0a7de745 3166 strncmp(parsed_parameters->required_netagent_types[j].netagent_type, remove_agent_type, NETAGENT_TYPESIZE) == 0) {
d9a64523
A
3167 updated = true;
3168
cb323159 3169 if (j == NECP_MAX_AGENT_PARAMETERS - 1) {
d9a64523 3170 // Last field, just clear and break
cb323159 3171 memset(&parsed_parameters->required_netagent_types[NECP_MAX_AGENT_PARAMETERS - 1], 0, sizeof(struct necp_client_parameter_netagent_type));
d9a64523
A
3172 break;
3173 } else {
3174 // Move the parameters down, clear the last entry
3175 memmove(&parsed_parameters->required_netagent_types[j],
0a7de745 3176 &parsed_parameters->required_netagent_types[j + 1],
cb323159
A
3177 sizeof(struct necp_client_parameter_netagent_type) * (NECP_MAX_AGENT_PARAMETERS - (j + 1)));
3178 memset(&parsed_parameters->required_netagent_types[NECP_MAX_AGENT_PARAMETERS - 1], 0, sizeof(struct necp_client_parameter_netagent_type));
d9a64523
A
3179 // Continue, don't increment but look at the new shifted item instead
3180 continue;
3181 }
3182 }
3183
3184 // Increment j to look at the next agent type parameter
3185 j++;
3186 }
3187 }
3188 }
3189 }
3190
3191 if (updated &&
0a7de745
A
3192 parsed_parameters->required_interface_index != IFSCOPE_NONE &&
3193 (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IF) == 0) {
d9a64523
A
3194 // A required interface index was added after the fact. Clear it.
3195 parsed_parameters->required_interface_index = IFSCOPE_NONE;
3196 }
3197
3198
0a7de745 3199 return updated;
d9a64523
A
3200}
3201
3202static inline bool
3203necp_agent_types_match(const char *agent_domain1, const char *agent_type1,
0a7de745 3204 const char *agent_domain2, const char *agent_type2)
d9a64523 3205{
0a7de745
A
3206 return (strlen(agent_domain1) == 0 ||
3207 strncmp(agent_domain2, agent_domain1, NETAGENT_DOMAINSIZE) == 0) &&
3208 (strlen(agent_type1) == 0 ||
3209 strncmp(agent_type2, agent_type1, NETAGENT_TYPESIZE) == 0);
d9a64523
A
3210}
3211
3212static inline bool
3213necp_calculate_client_result(proc_t proc,
0a7de745
A
3214 struct necp_client *client,
3215 struct necp_client_parsed_parameters *parsed_parameters,
3216 struct necp_aggregate_result *result,
cb323159
A
3217 u_int32_t *flags,
3218 u_int32_t *reason,
3219 struct necp_client_endpoint *v4_gateway,
ea3f0419
A
3220 struct necp_client_endpoint *v6_gateway,
3221 uuid_t *override_euuid)
d9a64523
A
3222{
3223 struct rtentry *route = NULL;
3224
3225 // Check parameters to find best interface
3226 bool validate_agents = false;
3227 u_int matching_if_index = 0;
3228 if (necp_find_matching_interface_index(parsed_parameters, &matching_if_index, &validate_agents)) {
3229 if (matching_if_index != 0) {
3230 parsed_parameters->required_interface_index = matching_if_index;
3231 }
3232 // Interface found or not needed, match policy.
3233 memset(result, 0, sizeof(*result));
3234 int error = necp_application_find_policy_match_internal(proc, client->parameters,
0a7de745 3235 (u_int32_t)client->parameters_length,
cb323159
A
3236 result, flags, reason, matching_if_index,
3237 NULL, NULL,
3238 v4_gateway, v6_gateway,
ea3f0419
A
3239 &route, false, true,
3240 override_euuid);
d9a64523
A
3241 if (error != 0) {
3242 if (route != NULL) {
3243 rtfree(route);
3244 }
0a7de745 3245 return FALSE;
d9a64523
A
3246 }
3247
3248 if (validate_agents) {
3249 bool requirement_failed = FALSE;
3250 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT) {
cb323159 3251 for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
d9a64523
A
3252 if (uuid_is_null(parsed_parameters->required_netagents[i])) {
3253 break;
3254 }
3255
3256 bool requirement_found = FALSE;
3257 for (int j = 0; j < NECP_MAX_NETAGENTS; j++) {
3258 if (uuid_is_null(result->netagents[j])) {
3259 break;
3260 }
3261
3262 if (uuid_compare(parsed_parameters->required_netagents[i], result->netagents[j]) == 0) {
3263 requirement_found = TRUE;
3264 break;
3265 }
3266 }
3267
3268 if (!requirement_found) {
3269 requirement_failed = TRUE;
3270 break;
3271 }
3272 }
3273 }
3274
3275 if (!requirement_failed && parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE) {
cb323159 3276 for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
d9a64523 3277 if (strlen(parsed_parameters->required_netagent_types[i].netagent_domain) == 0 &&
0a7de745 3278 strlen(parsed_parameters->required_netagent_types[i].netagent_type) == 0) {
d9a64523
A
3279 break;
3280 }
3281
3282 bool requirement_found = FALSE;
3283 for (int j = 0; j < NECP_MAX_NETAGENTS; j++) {
3284 if (uuid_is_null(result->netagents[j])) {
3285 break;
3286 }
3287
3288 char policy_agent_domain[NETAGENT_DOMAINSIZE] = { 0 };
3289 char policy_agent_type[NETAGENT_TYPESIZE] = { 0 };
3290
3291 if (netagent_get_agent_domain_and_type(result->netagents[j], policy_agent_domain, policy_agent_type)) {
3292 if (necp_agent_types_match(parsed_parameters->required_netagent_types[i].netagent_domain,
0a7de745
A
3293 parsed_parameters->required_netagent_types[i].netagent_type,
3294 policy_agent_domain, policy_agent_type)) {
d9a64523
A
3295 requirement_found = TRUE;
3296 break;
3297 }
3298 }
3299 }
3300
3301 if (!requirement_found) {
3302 requirement_failed = TRUE;
3303 break;
3304 }
3305 }
3306 }
3307
3308 if (requirement_failed) {
3309 // Agent requirement failed. Clear out the whole result, make everything fail.
3310 memset(result, 0, sizeof(*result));
3311 if (route != NULL) {
3312 rtfree(route);
3313 }
0a7de745 3314 return TRUE;
d9a64523 3315 }
5ba3f43e 3316 }
5ba3f43e 3317
d9a64523
A
3318 // Reset current route
3319 NECP_CLIENT_ROUTE_LOCK(client);
3320 if (client->current_route != NULL) {
3321 rtfree(client->current_route);
3322 }
3323 client->current_route = route;
3324 NECP_CLIENT_ROUTE_UNLOCK(client);
3325 } else {
3326 // Interface not found. Clear out the whole result, make everything fail.
3327 memset(result, 0, sizeof(*result));
39037602
A
3328 }
3329
0a7de745 3330 return TRUE;
39037602
A
3331}
3332
cb323159
A
3333#define NECP_PARSED_PARAMETERS_REQUIRED_FIELDS (NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IF | \
3334 NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE | \
3335 NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT | \
3336 NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE)
3337
39037602
A
3338static bool
3339necp_update_client_result(proc_t proc,
0a7de745
A
3340 struct necp_fd_data *client_fd,
3341 struct necp_client *client,
3342 struct _necp_flow_defunct_list *defunct_list)
39037602
A
3343{
3344 struct necp_client_result_netagent netagent;
3345 struct necp_aggregate_result result;
5ba3f43e 3346 struct necp_client_parsed_parameters *parsed_parameters = NULL;
39037602 3347 u_int32_t flags = 0;
cb323159 3348 u_int32_t reason = 0;
39037602 3349
5ba3f43e 3350 NECP_CLIENT_ASSERT_LOCKED(client);
39037602 3351
5ba3f43e
A
3352 MALLOC(parsed_parameters, struct necp_client_parsed_parameters *, sizeof(*parsed_parameters), M_NECP, (M_WAITOK | M_ZERO));
3353 if (parsed_parameters == NULL) {
0a7de745
A
3354 NECPLOG0(LOG_ERR, "Failed to allocate parsed parameters");
3355 return FALSE;
5ba3f43e
A
3356 }
3357
3358 // Nexus flows will be brought back if they are still valid
3359 necp_client_mark_all_nonsocket_flows_as_invalid(client);
3360
3361 int error = necp_client_parse_parameters(client->parameters, (u_int32_t)client->parameters_length, parsed_parameters);
39037602 3362 if (error != 0) {
5ba3f43e 3363 FREE(parsed_parameters, M_NECP);
0a7de745 3364 return FALSE;
39037602
A
3365 }
3366
5ba3f43e
A
3367 // Update saved IP protocol
3368 client->ip_protocol = parsed_parameters->ip_protocol;
3369
d9a64523 3370 // Calculate the policy result
cb323159
A
3371 struct necp_client_endpoint v4_gateway = {};
3372 struct necp_client_endpoint v6_gateway = {};
ea3f0419
A
3373 uuid_t override_euuid;
3374 uuid_clear(override_euuid);
3375 if (!necp_calculate_client_result(proc, client, parsed_parameters, &result, &flags, &reason, &v4_gateway, &v6_gateway, &override_euuid)) {
d9a64523 3376 FREE(parsed_parameters, M_NECP);
0a7de745 3377 return FALSE;
d9a64523
A
3378 }
3379
3380 if (necp_update_parsed_parameters(parsed_parameters, &result)) {
3381 // Changed the parameters based on result, try again (only once)
ea3f0419 3382 if (!necp_calculate_client_result(proc, client, parsed_parameters, &result, &flags, &reason, &v4_gateway, &v6_gateway, &override_euuid)) {
5ba3f43e 3383 FREE(parsed_parameters, M_NECP);
0a7de745 3384 return FALSE;
39037602 3385 }
39037602
A
3386 }
3387
cb323159
A
3388 if ((parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) &&
3389 parsed_parameters->required_interface_index != IFSCOPE_NONE &&
3390 (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IF) == 0) {
3391 // Listener should not apply required interface index if
3392 parsed_parameters->required_interface_index = IFSCOPE_NONE;
3393 }
3394
5ba3f43e
A
3395 // Save the last policy id on the client
3396 client->policy_id = result.policy_id;
ea3f0419 3397 uuid_copy(client->override_euuid, override_euuid);
5ba3f43e
A
3398
3399 if ((parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_MULTIPATH) ||
ea3f0419 3400 (parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_BROWSE) ||
0a7de745
A
3401 ((parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) &&
3402 result.routing_result != NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED)) {
5ba3f43e
A
3403 client->allow_multiple_flows = TRUE;
3404 } else {
3405 client->allow_multiple_flows = FALSE;
3406 }
3407
39037602
A
3408 // If the original request was scoped, and the policy result matches, make sure the result is scoped
3409 if ((result.routing_result == NECP_KERNEL_POLICY_RESULT_NONE ||
0a7de745
A
3410 result.routing_result == NECP_KERNEL_POLICY_RESULT_PASS) &&
3411 result.routed_interface_index != IFSCOPE_NONE &&
3412 parsed_parameters->required_interface_index == result.routed_interface_index) {
39037602
A
3413 result.routing_result = NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED;
3414 result.routing_result_parameter.scoped_interface_index = result.routed_interface_index;
3415 }
3416
5ba3f43e 3417 if (defunct_list != NULL &&
0a7de745 3418 result.routing_result == NECP_KERNEL_POLICY_RESULT_DROP) {
5ba3f43e
A
3419 // If we are forced to drop the client, defunct it if it has flows
3420 necp_defunct_client_for_policy(client, defunct_list);
3421 }
3422
3423 // Recalculate flags
5ba3f43e
A
3424 if (parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) {
3425 // Listeners are valid as long as they aren't dropped
3426 if (result.routing_result != NECP_KERNEL_POLICY_RESULT_DROP) {
3427 flags |= NECP_CLIENT_RESULT_FLAG_SATISFIED;
3428 }
3429 } else if (result.routed_interface_index != 0) {
3430 // Clients without flows determine viability based on having some routable interface
3431 flags |= NECP_CLIENT_RESULT_FLAG_SATISFIED;
3432 }
3433
39037602
A
3434 bool updated = FALSE;
3435 u_int8_t *cursor = client->result;
5ba3f43e 3436 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_FLAGS, sizeof(flags), &flags, &updated, client->result, sizeof(client->result));
cb323159
A
3437 if (reason != 0) {
3438 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_REASON, sizeof(reason), &reason, &updated, client->result, sizeof(client->result));
3439 }
5ba3f43e 3440 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_CLIENT_ID, sizeof(uuid_t), client->client_id, &updated,
0a7de745 3441 client->result, sizeof(client->result));
5ba3f43e 3442 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_POLICY_RESULT, sizeof(result.routing_result), &result.routing_result, &updated,
0a7de745 3443 client->result, sizeof(client->result));
39037602 3444 if (result.routing_result_parameter.tunnel_interface_index != 0) {
5ba3f43e 3445 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_POLICY_RESULT_PARAMETER,
0a7de745
A
3446 sizeof(result.routing_result_parameter), &result.routing_result_parameter, &updated,
3447 client->result, sizeof(client->result));
39037602
A
3448 }
3449 if (result.filter_control_unit != 0) {
5ba3f43e 3450 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_FILTER_CONTROL_UNIT,
0a7de745
A
3451 sizeof(result.filter_control_unit), &result.filter_control_unit, &updated,
3452 client->result, sizeof(client->result));
39037602 3453 }
f427ee49
A
3454 if (result.flow_divert_aggregate_unit != 0) {
3455 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_FLOW_DIVERT_AGGREGATE_UNIT,
3456 sizeof(result.flow_divert_aggregate_unit), &result.flow_divert_aggregate_unit, &updated,
3457 client->result, sizeof(client->result));
3458 }
39037602
A
3459 if (result.routed_interface_index != 0) {
3460 u_int routed_interface_index = result.routed_interface_index;
3461 if (result.routing_result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL &&
cb323159 3462 (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_REQUIRED_FIELDS) &&
0a7de745
A
3463 parsed_parameters->required_interface_index != IFSCOPE_NONE &&
3464 parsed_parameters->required_interface_index != result.routed_interface_index) {
5ba3f43e 3465 routed_interface_index = parsed_parameters->required_interface_index;
39037602
A
3466 }
3467
5ba3f43e 3468 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_INTERFACE_INDEX,
0a7de745
A
3469 sizeof(routed_interface_index), &routed_interface_index, &updated,
3470 client->result, sizeof(client->result));
5ba3f43e
A
3471 }
3472 if (client_fd && client_fd->flags & NECP_OPEN_FLAG_BACKGROUND) {
3473 u_int32_t effective_traffic_class = SO_TC_BK_SYS;
3474 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_EFFECTIVE_TRAFFIC_CLASS,
0a7de745
A
3475 sizeof(effective_traffic_class), &effective_traffic_class, &updated,
3476 client->result, sizeof(client->result));
5ba3f43e 3477 }
cb323159
A
3478
3479 if (client_fd->background) {
3480 bool has_assigned_flow = FALSE;
3481 struct necp_client_flow_registration *flow_registration = NULL;
3482 struct necp_client_flow *search_flow = NULL;
3483 RB_FOREACH(flow_registration, _necp_client_flow_tree, &client->flow_registrations) {
3484 LIST_FOREACH(search_flow, &flow_registration->flow_list, flow_chain) {
3485 if (search_flow->assigned) {
3486 has_assigned_flow = TRUE;
3487 break;
3488 }
3489 }
3490 }
3491
3492 if (has_assigned_flow) {
3493 u_int32_t background = client_fd->background;
3494 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_TRAFFIC_MGMT_BG,
3495 sizeof(background), &background, &updated,
3496 client->result, sizeof(client->result));
5ba3f43e 3497 }
39037602 3498 }
cb323159
A
3499
3500 bool write_v4_gateway = !necp_client_endpoint_is_unspecified(&v4_gateway);
3501 bool write_v6_gateway = !necp_client_endpoint_is_unspecified(&v6_gateway);
3502
5ba3f43e
A
3503 NECP_CLIENT_ROUTE_LOCK(client);
3504 if (client->current_route != NULL) {
3505 const u_int32_t route_mtu = get_maxmtu(client->current_route);
3506 if (route_mtu != 0) {
3507 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_EFFECTIVE_MTU,
0a7de745
A
3508 sizeof(route_mtu), &route_mtu, &updated,
3509 client->result, sizeof(client->result));
5ba3f43e 3510 }
cb323159
A
3511 bool has_remote_addr = parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REMOTE_ADDR;
3512 if (has_remote_addr && client->current_route->rt_gateway != NULL) {
3513 if (client->current_route->rt_gateway->sa_family == AF_INET) {
3514 write_v6_gateway = false;
3515 } else if (client->current_route->rt_gateway->sa_family == AF_INET6) {
3516 write_v4_gateway = false;
3517 }
3518 }
39037602 3519 }
5ba3f43e
A
3520 NECP_CLIENT_ROUTE_UNLOCK(client);
3521
cb323159
A
3522 if (write_v4_gateway) {
3523 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_GATEWAY,
3524 sizeof(struct necp_client_endpoint), &v4_gateway, &updated,
3525 client->result, sizeof(client->result));
3526 }
3527
3528 if (write_v6_gateway) {
3529 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_GATEWAY,
3530 sizeof(struct necp_client_endpoint), &v6_gateway, &updated,
3531 client->result, sizeof(client->result));
3532 }
3533
5ba3f43e
A
3534 if (result.mss_recommended != 0) {
3535 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_RECOMMENDED_MSS,
0a7de745
A
3536 sizeof(result.mss_recommended), &result.mss_recommended, &updated,
3537 client->result, sizeof(client->result));
5ba3f43e
A
3538 }
3539
39037602
A
3540 for (int i = 0; i < NECP_MAX_NETAGENTS; i++) {
3541 if (uuid_is_null(result.netagents[i])) {
3542 break;
3543 }
3544 uuid_copy(netagent.netagent_uuid, result.netagents[i]);
3545 netagent.generation = netagent_get_generation(netagent.netagent_uuid);
d9a64523 3546 if (necp_netagent_applies_to_client(client, parsed_parameters, &netagent.netagent_uuid, TRUE, 0, 0)) {
5ba3f43e 3547 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_NETAGENT, sizeof(netagent), &netagent, &updated,
0a7de745 3548 client->result, sizeof(client->result));
39037602
A
3549 }
3550 }
3551
3552 ifnet_head_lock_shared();
3553 ifnet_t direct_interface = NULL;
3554 ifnet_t delegate_interface = NULL;
3555 ifnet_t original_scoped_interface = NULL;
3556
813fb2f6 3557 if (result.routed_interface_index != IFSCOPE_NONE && result.routed_interface_index <= (u_int32_t)if_index) {
39037602 3558 direct_interface = ifindex2ifnet[result.routed_interface_index];
5ba3f43e 3559 } else if (parsed_parameters->required_interface_index != IFSCOPE_NONE &&
0a7de745 3560 parsed_parameters->required_interface_index <= (u_int32_t)if_index) {
39037602 3561 // If the request was scoped, but the route didn't match, still grab the agents
5ba3f43e 3562 direct_interface = ifindex2ifnet[parsed_parameters->required_interface_index];
39037602 3563 } else if (result.routed_interface_index == IFSCOPE_NONE &&
0a7de745
A
3564 result.routing_result == NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED &&
3565 result.routing_result_parameter.scoped_interface_index != IFSCOPE_NONE) {
39037602
A
3566 direct_interface = ifindex2ifnet[result.routing_result_parameter.scoped_interface_index];
3567 }
3568 if (direct_interface != NULL) {
3569 delegate_interface = direct_interface->if_delegated.ifp;
3570 }
3571 if (result.routing_result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL &&
cb323159 3572 (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_REQUIRED_FIELDS) &&
0a7de745
A
3573 parsed_parameters->required_interface_index != IFSCOPE_NONE &&
3574 parsed_parameters->required_interface_index != result.routing_result_parameter.tunnel_interface_index &&
3575 parsed_parameters->required_interface_index <= (u_int32_t)if_index) {
5ba3f43e 3576 original_scoped_interface = ifindex2ifnet[parsed_parameters->required_interface_index];
39037602
A
3577 }
3578 // Add interfaces
3579 if (original_scoped_interface != NULL) {
3580 struct necp_client_result_interface interface_struct;
3581 interface_struct.index = original_scoped_interface->if_index;
3582 interface_struct.generation = ifnet_get_generation(original_scoped_interface);
5ba3f43e 3583 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_INTERFACE, sizeof(interface_struct), &interface_struct, &updated,
0a7de745 3584 client->result, sizeof(client->result));
39037602
A
3585 }
3586 if (direct_interface != NULL) {
3587 struct necp_client_result_interface interface_struct;
3588 interface_struct.index = direct_interface->if_index;
3589 interface_struct.generation = ifnet_get_generation(direct_interface);
5ba3f43e 3590 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_INTERFACE, sizeof(interface_struct), &interface_struct, &updated,
0a7de745 3591 client->result, sizeof(client->result));
9d749ea3
A
3592
3593 // Set the delta time since interface up/down
3594 struct timeval updown_delta = {};
3595 if (ifnet_updown_delta(direct_interface, &updown_delta) == 0) {
3596 u_int32_t delta = updown_delta.tv_sec;
3597 bool ignore_updated = FALSE;
3598 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_INTERFACE_TIME_DELTA,
0a7de745
A
3599 sizeof(delta), &delta, &ignore_updated,
3600 client->result, sizeof(client->result));
9d749ea3 3601 }
39037602
A
3602 }
3603 if (delegate_interface != NULL) {
3604 struct necp_client_result_interface interface_struct;
3605 interface_struct.index = delegate_interface->if_index;
3606 interface_struct.generation = ifnet_get_generation(delegate_interface);
5ba3f43e 3607 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_INTERFACE, sizeof(interface_struct), &interface_struct, &updated,
0a7de745 3608 client->result, sizeof(client->result));
5ba3f43e
A
3609 }
3610
3611 // Update multipath/listener interface flows
3612 if (parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_MULTIPATH) {
3613 // Get multipath interface options from ordered list
3614 struct ifnet *multi_interface = NULL;
3615 TAILQ_FOREACH(multi_interface, &ifnet_ordered_head, if_ordered_link) {
cb323159 3616 if (necp_ifnet_matches_parameters(multi_interface, parsed_parameters, 0, NULL, true, false)) {
5ba3f43e 3617 // Add multipath interface flows for kernel MPTCP
d9a64523 3618 necp_client_add_interface_option_if_needed(client, multi_interface->if_index,
0a7de745 3619 ifnet_get_generation(multi_interface), NULL);
5ba3f43e
A
3620
3621 // Add nexus agents for multipath
d9a64523 3622 necp_client_add_agent_interface_options(client, parsed_parameters, multi_interface);
5ba3f43e
A
3623 }
3624 }
cb323159
A
3625 } else if (parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) {
3626 if (result.routing_result == NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED) {
3627 if (direct_interface != NULL) {
3628 // If scoped, only listen on that interface
5ba3f43e 3629 // Add nexus agents for listeners
cb323159
A
3630 necp_client_add_agent_interface_options(client, parsed_parameters, direct_interface);
3631
3632 // Add interface option in case it is not a nexus
3633 necp_client_add_interface_option_if_needed(client, direct_interface->if_index,
3634 ifnet_get_generation(direct_interface), NULL);
3635 }
3636 } else {
3637 // Get listener interface options from global list
3638 struct ifnet *listen_interface = NULL;
3639 TAILQ_FOREACH(listen_interface, &ifnet_head, if_link) {
3640 if ((listen_interface->if_flags & (IFF_UP | IFF_RUNNING)) &&
3641 necp_ifnet_matches_parameters(listen_interface, parsed_parameters, 0, NULL, true, false)) {
3642 // Add nexus agents for listeners
3643 necp_client_add_agent_interface_options(client, parsed_parameters, listen_interface);
3644 }
5ba3f43e
A
3645 }
3646 }
ea3f0419
A
3647 } else if (parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_BROWSE) {
3648 if (result.routing_result == NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED) {
3649 if (direct_interface != NULL) {
3650 // Add browse option if it has an agent
3651 necp_client_add_browse_interface_options(client, parsed_parameters, direct_interface);
3652 }
3653 } else {
3654 // Get browse interface options from global list
3655 struct ifnet *browse_interface = NULL;
3656 TAILQ_FOREACH(browse_interface, &ifnet_head, if_link) {
3657 if (necp_ifnet_matches_parameters(browse_interface, parsed_parameters, 0, NULL, true, false)) {
3658 necp_client_add_browse_interface_options(client, parsed_parameters, browse_interface);
3659 }
3660 }
3661 }
39037602 3662 }
5ba3f43e 3663
39037602
A
3664 // Add agents
3665 if (original_scoped_interface != NULL) {
3666 ifnet_lock_shared(original_scoped_interface);
3667 if (original_scoped_interface->if_agentids != NULL) {
3668 for (u_int32_t i = 0; i < original_scoped_interface->if_agentcount; i++) {
3669 if (uuid_is_null(original_scoped_interface->if_agentids[i])) {
3670 continue;
3671 }
3672 uuid_copy(netagent.netagent_uuid, original_scoped_interface->if_agentids[i]);
3673 netagent.generation = netagent_get_generation(netagent.netagent_uuid);
d9a64523 3674 if (necp_netagent_applies_to_client(client, parsed_parameters, &netagent.netagent_uuid, FALSE,
0a7de745 3675 original_scoped_interface->if_index, ifnet_get_generation(original_scoped_interface))) {
5ba3f43e 3676 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_NETAGENT, sizeof(netagent), &netagent, &updated,
0a7de745 3677 client->result, sizeof(client->result));
39037602
A
3678 }
3679 }
3680 }
3681 ifnet_lock_done(original_scoped_interface);
3682 }
3683 if (direct_interface != NULL) {
3684 ifnet_lock_shared(direct_interface);
3685 if (direct_interface->if_agentids != NULL) {
3686 for (u_int32_t i = 0; i < direct_interface->if_agentcount; i++) {
3687 if (uuid_is_null(direct_interface->if_agentids[i])) {
3688 continue;
3689 }
3690 uuid_copy(netagent.netagent_uuid, direct_interface->if_agentids[i]);
3691 netagent.generation = netagent_get_generation(netagent.netagent_uuid);
d9a64523 3692 if (necp_netagent_applies_to_client(client, parsed_parameters, &netagent.netagent_uuid, TRUE,
0a7de745 3693 direct_interface->if_index, ifnet_get_generation(direct_interface))) {
5ba3f43e 3694 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_NETAGENT, sizeof(netagent), &netagent, &updated,
0a7de745 3695 client->result, sizeof(client->result));
39037602
A
3696 }
3697 }
3698 }
3699 ifnet_lock_done(direct_interface);
3700 }
3701 if (delegate_interface != NULL) {
3702 ifnet_lock_shared(delegate_interface);
3703 if (delegate_interface->if_agentids != NULL) {
3704 for (u_int32_t i = 0; i < delegate_interface->if_agentcount; i++) {
3705 if (uuid_is_null(delegate_interface->if_agentids[i])) {
3706 continue;
3707 }
3708 uuid_copy(netagent.netagent_uuid, delegate_interface->if_agentids[i]);
3709 netagent.generation = netagent_get_generation(netagent.netagent_uuid);
d9a64523 3710 if (necp_netagent_applies_to_client(client, parsed_parameters, &netagent.netagent_uuid, FALSE,
0a7de745 3711 delegate_interface->if_index, ifnet_get_generation(delegate_interface))) {
5ba3f43e 3712 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_NETAGENT, sizeof(netagent), &netagent, &updated,
0a7de745 3713 client->result, sizeof(client->result));
39037602
A
3714 }
3715 }
3716 }
3717 ifnet_lock_done(delegate_interface);
3718 }
3719 ifnet_head_done();
3720
d9a64523
A
3721 // Add interface options
3722 for (u_int32_t option_i = 0; option_i < client->interface_option_count; option_i++) {
3723 if (option_i < NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT) {
3724 struct necp_client_interface_option *option = &client->interface_options[option_i];
3725 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_INTERFACE_OPTION, sizeof(*option), option, &updated,
0a7de745 3726 client->result, sizeof(client->result));
d9a64523
A
3727 } else {
3728 struct necp_client_interface_option *option = &client->extra_interface_options[option_i - NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT];
3729 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_INTERFACE_OPTION, sizeof(*option), option, &updated,
0a7de745 3730 client->result, sizeof(client->result));
d9a64523
A
3731 }
3732 }
3733
39037602
A
3734 size_t new_result_length = (cursor - client->result);
3735 if (new_result_length != client->result_length) {
3736 client->result_length = new_result_length;
3737 updated = TRUE;
3738 }
5ba3f43e
A
3739
3740 // Update flow viability/flags
d9a64523 3741 if (necp_client_update_flows(proc, client, defunct_list)) {
5ba3f43e
A
3742 updated = TRUE;
3743 }
3744
39037602
A
3745 if (updated) {
3746 client->result_read = FALSE;
5ba3f43e 3747 necp_client_update_observer_update(client);
39037602
A
3748 }
3749
5ba3f43e 3750 FREE(parsed_parameters, M_NECP);
0a7de745 3751 return updated;
39037602
A
3752}
3753
f427ee49
A
3754static bool
3755necp_defunct_client_fd_locked_inner(struct necp_fd_data *client_fd, struct _necp_flow_defunct_list *defunct_list, bool destroy_stats)
5ba3f43e
A
3756{
3757 bool updated_result = FALSE;
3758 struct necp_client *client = NULL;
3759
3760 NECP_FD_ASSERT_LOCKED(client_fd);
a39ff7e2 3761
5ba3f43e 3762 RB_FOREACH(client, _necp_client_tree, &client_fd->clients) {
d9a64523
A
3763 struct necp_client_flow_registration *flow_registration = NULL;
3764
5ba3f43e 3765 NECP_CLIENT_LOCK(client);
5ba3f43e 3766
d9a64523
A
3767 // Prepare close events to be sent to the nexus to effectively remove the flows
3768 struct necp_client_flow *search_flow = NULL;
3769 RB_FOREACH(flow_registration, _necp_client_flow_tree, &client->flow_registrations) {
3770 LIST_FOREACH(search_flow, &flow_registration->flow_list, flow_chain) {
5ba3f43e 3771 if (search_flow->nexus &&
0a7de745 3772 !uuid_is_null(search_flow->u.nexus_agent)) {
5ba3f43e 3773 // Sleeping alloc won't fail; copy only what's necessary
cb323159 3774 struct necp_flow_defunct *flow_defunct = _MALLOC(sizeof(struct necp_flow_defunct), M_NECP, M_WAITOK | M_ZERO);
d9a64523
A
3775 uuid_copy(flow_defunct->nexus_agent, search_flow->u.nexus_agent);
3776 uuid_copy(flow_defunct->flow_id, ((flow_registration->flags & NECP_CLIENT_FLOW_FLAGS_USE_CLIENT_ID) ?
0a7de745
A
3777 client->client_id :
3778 flow_registration->registration_id));
d9a64523
A
3779 flow_defunct->proc_pid = client->proc_pid;
3780 flow_defunct->agent_handle = client->agent_handle;
cb323159 3781 flow_defunct->flags = flow_registration->flags;
5ba3f43e 3782 // Add to the list provided by caller
d9a64523
A
3783 LIST_INSERT_HEAD(defunct_list, flow_defunct, chain);
3784
3785 flow_registration->defunct = true;
3786 flow_registration->flow_result_read = false;
3787 updated_result = true;
5ba3f43e
A
3788 }
3789 }
3790 }
f427ee49
A
3791 if (destroy_stats) {
3792 }
5ba3f43e
A
3793 NECP_CLIENT_UNLOCK(client);
3794 }
a39ff7e2 3795
f427ee49
A
3796 return updated_result;
3797}
3798
3799static inline void
3800necp_defunct_client_fd_locked(struct necp_fd_data *client_fd, struct _necp_flow_defunct_list *defunct_list, struct proc *proc)
3801{
3802#pragma unused(proc)
3803 bool updated_result = FALSE;
3804
3805 NECP_FD_ASSERT_LOCKED(client_fd);
3806
3807 updated_result = necp_defunct_client_fd_locked_inner(client_fd, defunct_list, true);
3808
a39ff7e2 3809
5ba3f43e
A
3810 if (updated_result) {
3811 necp_fd_notify(client_fd, true);
3812 }
3813}
3814
3815static inline void
3816necp_update_client_fd_locked(struct necp_fd_data *client_fd,
0a7de745
A
3817 proc_t proc,
3818 struct _necp_flow_defunct_list *defunct_list)
5ba3f43e
A
3819{
3820 struct necp_client *client = NULL;
3821 bool updated_result = FALSE;
3822 NECP_FD_ASSERT_LOCKED(client_fd);
3823 RB_FOREACH(client, _necp_client_tree, &client_fd->clients) {
3824 NECP_CLIENT_LOCK(client);
3825 if (necp_update_client_result(proc, client_fd, client, defunct_list)) {
3826 updated_result = TRUE;
3827 }
3828 NECP_CLIENT_UNLOCK(client);
3829 }
3830 if (updated_result) {
3831 necp_fd_notify(client_fd, true);
3832 }
3833}
3834
3835
39037602
A
3836static void
3837necp_update_all_clients_callout(__unused thread_call_param_t dummy,
0a7de745 3838 __unused thread_call_param_t arg)
39037602 3839{
39037602
A
3840 struct necp_fd_data *client_fd = NULL;
3841
d9a64523 3842 struct _necp_flow_defunct_list defunct_list;
5ba3f43e
A
3843 LIST_INIT(&defunct_list);
3844
3845 NECP_FD_LIST_LOCK_SHARED();
39037602
A
3846
3847 LIST_FOREACH(client_fd, &necp_fd_list, chain) {
39037602 3848 proc_t proc = proc_find(client_fd->proc_pid);
5ba3f43e 3849 if (proc == PROC_NULL) {
39037602
A
3850 continue;
3851 }
3852
5ba3f43e
A
3853 // Update all clients on one fd
3854 NECP_FD_LOCK(client_fd);
3855 necp_update_client_fd_locked(client_fd, proc, &defunct_list);
3856 NECP_FD_UNLOCK(client_fd);
3857
3858 proc_rele(proc);
3859 proc = PROC_NULL;
3860 }
3861
3862 NECP_FD_LIST_UNLOCK();
3863
3864 // Handle the case in which some clients became newly defunct
f427ee49 3865 necp_process_defunct_list(&defunct_list);
5ba3f43e
A
3866}
3867
3868void
3869necp_update_all_clients(void)
cb323159
A
3870{
3871 necp_update_all_clients_immediately_if_needed(false);
3872}
3873
3874void
3875necp_update_all_clients_immediately_if_needed(bool should_update_immediately)
5ba3f43e
A
3876{
3877 if (necp_client_update_tcall == NULL) {
3878 // Don't try to update clients if the module is not initialized
3879 return;
3880 }
3881
3882 uint64_t deadline = 0;
3883 uint64_t leeway = 0;
cb323159
A
3884
3885 uint32_t timeout_to_use = necp_timeout_microseconds;
3886 uint32_t leeway_to_use = necp_timeout_leeway_microseconds;
3887 if (should_update_immediately) {
3888 timeout_to_use = 1000 * 10; // 10ms
3889 leeway_to_use = 1000 * 10; // 10ms;
3890 }
3891
3892 clock_interval_to_deadline(timeout_to_use, NSEC_PER_USEC, &deadline);
3893 clock_interval_to_absolutetime_interval(leeway_to_use, NSEC_PER_USEC, &leeway);
5ba3f43e
A
3894
3895 thread_call_enter_delayed_with_leeway(necp_client_update_tcall, NULL,
0a7de745 3896 deadline, leeway, THREAD_CALL_DELAY_LEEWAY);
5ba3f43e
A
3897}
3898
cb323159 3899bool
5ba3f43e 3900necp_set_client_as_background(proc_t proc,
0a7de745
A
3901 struct fileproc *fp,
3902 bool background)
5ba3f43e 3903{
5ba3f43e
A
3904 if (proc == PROC_NULL) {
3905 NECPLOG0(LOG_ERR, "NULL proc");
cb323159 3906 return FALSE;
5ba3f43e
A
3907 }
3908
3909 if (fp == NULL) {
3910 NECPLOG0(LOG_ERR, "NULL fp");
cb323159 3911 return FALSE;
5ba3f43e
A
3912 }
3913
f427ee49 3914 struct necp_fd_data *client_fd = (struct necp_fd_data *)fp->fp_glob->fg_data;
5ba3f43e
A
3915 if (client_fd == NULL) {
3916 NECPLOG0(LOG_ERR, "Could not find client structure for backgrounded client");
cb323159 3917 return FALSE;
5ba3f43e
A
3918 }
3919
3920 if (client_fd->necp_fd_type != necp_fd_type_client) {
3921 // Not a client fd, ignore
3922 NECPLOG0(LOG_ERR, "Not a client fd, ignore");
cb323159 3923 return FALSE;
5ba3f43e
A
3924 }
3925
cb323159 3926 client_fd->background = background;
5ba3f43e 3927
cb323159 3928 return TRUE;
5ba3f43e
A
3929}
3930
3931void
a39ff7e2
A
3932necp_fd_memstatus(proc_t proc, uint32_t status,
3933 struct necp_fd_data *client_fd)
5ba3f43e 3934{
a39ff7e2
A
3935#pragma unused(proc, status, client_fd)
3936 ASSERT(proc != PROC_NULL);
3937 ASSERT(client_fd != NULL);
5ba3f43e 3938
a39ff7e2
A
3939 // Nothing to reap for the process or client for now,
3940 // but this is where we would trigger that in future.
3941}
5ba3f43e 3942
a39ff7e2
A
3943void
3944necp_fd_defunct(proc_t proc, struct necp_fd_data *client_fd)
3945{
d9a64523 3946 struct _necp_flow_defunct_list defunct_list;
39037602 3947
a39ff7e2
A
3948 ASSERT(proc != PROC_NULL);
3949 ASSERT(client_fd != NULL);
39037602 3950
5ba3f43e
A
3951 if (client_fd->necp_fd_type != necp_fd_type_client) {
3952 // Not a client fd, ignore
39037602
A
3953 return;
3954 }
3955
5ba3f43e
A
3956 // Our local temporary list
3957 LIST_INIT(&defunct_list);
39037602 3958
5ba3f43e
A
3959 // Need to hold lock so ntstats defunct the same set of clients
3960 NECP_FD_LOCK(client_fd);
a39ff7e2 3961 necp_defunct_client_fd_locked(client_fd, &defunct_list, proc);
5ba3f43e
A
3962 NECP_FD_UNLOCK(client_fd);
3963
f427ee49 3964 necp_process_defunct_list(&defunct_list);
39037602
A
3965}
3966
3967static void
3968necp_client_remove_agent_from_result(struct necp_client *client, uuid_t netagent_uuid)
3969{
3970 size_t offset = 0;
3971
3972 u_int8_t *result_buffer = client->result;
5ba3f43e 3973 while ((offset + sizeof(struct necp_tlv_header)) <= client->result_length) {
39037602
A
3974 u_int8_t type = necp_buffer_get_tlv_type(result_buffer, offset);
3975 u_int32_t length = necp_buffer_get_tlv_length(result_buffer, offset);
3976
5ba3f43e 3977 size_t tlv_total_length = (sizeof(struct necp_tlv_header) + length);
39037602 3978 if (type == NECP_CLIENT_RESULT_NETAGENT &&
0a7de745
A
3979 length == sizeof(struct necp_client_result_netagent) &&
3980 (offset + tlv_total_length) <= client->result_length) {
39037602 3981 struct necp_client_result_netagent *value = ((struct necp_client_result_netagent *)(void *)
0a7de745 3982 necp_buffer_get_tlv_value(result_buffer, offset, NULL));
39037602
A
3983 if (uuid_compare(value->netagent_uuid, netagent_uuid) == 0) {
3984 // Found a netagent to remove
3985 // Shift bytes down to remove the tlv, and adjust total length
3986 // Don't adjust the current offset
3987 memmove(result_buffer + offset,
0a7de745
A
3988 result_buffer + offset + tlv_total_length,
3989 client->result_length - (offset + tlv_total_length));
39037602 3990 client->result_length -= tlv_total_length;
5ba3f43e 3991 memset(result_buffer + client->result_length, 0, sizeof(client->result) - client->result_length);
39037602
A
3992 continue;
3993 }
3994 }
3995
3996 offset += tlv_total_length;
3997 }
3998}
3999
4000void
d9a64523 4001necp_force_update_client(uuid_t client_id, uuid_t remove_netagent_uuid, u_int32_t agent_generation)
39037602
A
4002{
4003 struct necp_fd_data *client_fd = NULL;
4004
5ba3f43e 4005 NECP_FD_LIST_LOCK_SHARED();
39037602
A
4006
4007 LIST_FOREACH(client_fd, &necp_fd_list, chain) {
4008 bool updated_result = FALSE;
5ba3f43e
A
4009 NECP_FD_LOCK(client_fd);
4010 struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
4011 if (client != NULL) {
d9a64523
A
4012 client->failed_trigger_agent.generation = agent_generation;
4013 uuid_copy(client->failed_trigger_agent.netagent_uuid, remove_netagent_uuid);
5ba3f43e
A
4014 if (!uuid_is_null(remove_netagent_uuid)) {
4015 necp_client_remove_agent_from_result(client, remove_netagent_uuid);
39037602 4016 }
d9a64523 4017 client->result_read = FALSE;
5ba3f43e
A
4018 // Found the client, break
4019 updated_result = TRUE;
4020 NECP_CLIENT_UNLOCK(client);
39037602
A
4021 }
4022 if (updated_result) {
4023 necp_fd_notify(client_fd, true);
4024 }
5ba3f43e 4025 NECP_FD_UNLOCK(client_fd);
39037602
A
4026 if (updated_result) {
4027 // Found the client, break
4028 break;
4029 }
4030 }
4031
5ba3f43e 4032 NECP_FD_LIST_UNLOCK();
39037602
A
4033}
4034
5ba3f43e 4035
39037602
A
4036/// Interface matching
4037
0a7de745
A
4038#define NECP_PARSED_PARAMETERS_INTERESTING_IFNET_FIELDS (NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR | \
4039 NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IF | \
4040 NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE | \
4041 NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IFTYPE | \
4042 NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT | \
4043 NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT | \
4044 NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT | \
4045 NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT | \
4046 NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE | \
4047 NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT_TYPE | \
4048 NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT_TYPE | \
4049 NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT_TYPE)
4050
4051#define NECP_PARSED_PARAMETERS_SCOPED_FIELDS (NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR | \
4052 NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE | \
4053 NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT | \
4054 NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT | \
0a7de745 4055 NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE | \
cb323159 4056 NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT_TYPE)
0a7de745
A
4057
4058#define NECP_PARSED_PARAMETERS_SCOPED_IFNET_FIELDS (NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR | \
4059 NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE)
4060
4061#define NECP_PARSED_PARAMETERS_PREFERRED_FIELDS (NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT | \
4062 NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT | \
4063 NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT_TYPE | \
4064 NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT_TYPE)
39037602
A
4065
4066static bool
4067necp_ifnet_matches_type(struct ifnet *ifp, u_int8_t interface_type, bool check_delegates)
4068{
4069 struct ifnet *check_ifp = ifp;
4070 while (check_ifp) {
4071 if (if_functional_type(check_ifp, TRUE) == interface_type) {
0a7de745 4072 return TRUE;
39037602
A
4073 }
4074 if (!check_delegates) {
4075 break;
4076 }
4077 check_ifp = check_ifp->if_delegated.ifp;
39037602 4078 }
0a7de745 4079 return FALSE;
39037602
A
4080}
4081
4082static bool
4083necp_ifnet_matches_name(struct ifnet *ifp, const char *interface_name, bool check_delegates)
4084{
4085 struct ifnet *check_ifp = ifp;
4086 while (check_ifp) {
4087 if (strncmp(check_ifp->if_xname, interface_name, IFXNAMSIZ) == 0) {
0a7de745 4088 return TRUE;
39037602
A
4089 }
4090 if (!check_delegates) {
4091 break;
4092 }
4093 check_ifp = check_ifp->if_delegated.ifp;
4094 }
0a7de745 4095 return FALSE;
39037602
A
4096}
4097
4098static bool
4099necp_ifnet_matches_agent(struct ifnet *ifp, uuid_t *agent_uuid, bool check_delegates)
4100{
4101 struct ifnet *check_ifp = ifp;
4102
4103 while (check_ifp != NULL) {
4104 ifnet_lock_shared(check_ifp);
4105 if (check_ifp->if_agentids != NULL) {
4106 for (u_int32_t index = 0; index < check_ifp->if_agentcount; index++) {
4107 if (uuid_compare(check_ifp->if_agentids[index], *agent_uuid) == 0) {
4108 ifnet_lock_done(check_ifp);
0a7de745 4109 return TRUE;
39037602
A
4110 }
4111 }
4112 }
4113 ifnet_lock_done(check_ifp);
4114
4115 if (!check_delegates) {
4116 break;
4117 }
4118 check_ifp = check_ifp->if_delegated.ifp;
4119 }
0a7de745 4120 return FALSE;
39037602
A
4121}
4122
4123static bool
d9a64523 4124necp_ifnet_matches_agent_type(struct ifnet *ifp, const char *agent_domain, const char *agent_type, bool check_delegates)
39037602
A
4125{
4126 struct ifnet *check_ifp = ifp;
4127
4128 while (check_ifp != NULL) {
4129 ifnet_lock_shared(check_ifp);
4130 if (check_ifp->if_agentids != NULL) {
4131 for (u_int32_t index = 0; index < check_ifp->if_agentcount; index++) {
4132 if (uuid_is_null(check_ifp->if_agentids[index])) {
4133 continue;
4134 }
4135
4136 char if_agent_domain[NETAGENT_DOMAINSIZE] = { 0 };
4137 char if_agent_type[NETAGENT_TYPESIZE] = { 0 };
4138
4139 if (netagent_get_agent_domain_and_type(check_ifp->if_agentids[index], if_agent_domain, if_agent_type)) {
d9a64523
A
4140 if (necp_agent_types_match(agent_domain, agent_type, if_agent_domain, if_agent_type)) {
4141 ifnet_lock_done(check_ifp);
0a7de745 4142 return TRUE;
d9a64523 4143 }
39037602
A
4144 }
4145 }
4146 }
4147 ifnet_lock_done(check_ifp);
4148
4149 if (!check_delegates) {
4150 break;
4151 }
4152 check_ifp = check_ifp->if_delegated.ifp;
4153 }
0a7de745 4154 return FALSE;
39037602
A
4155}
4156
4157static bool
4158necp_ifnet_matches_local_address(struct ifnet *ifp, struct sockaddr *sa)
4159{
4160 struct ifaddr *ifa = NULL;
4161 bool matched_local_address = FALSE;
4162
4163 // Transform sa into the ifaddr form
4164 // IPv6 Scope IDs are always embedded in the ifaddr list
4165 struct sockaddr_storage address;
4166 u_int ifscope = IFSCOPE_NONE;
4167 (void)sa_copy(sa, &address, &ifscope);
4168 SIN(&address)->sin_port = 0;
4169 if (address.ss_family == AF_INET6) {
4170 SIN6(&address)->sin6_scope_id = 0;
4171 }
4172
4173 ifa = ifa_ifwithaddr_scoped_locked((struct sockaddr *)&address, ifp->if_index);
4174 matched_local_address = (ifa != NULL);
4175
4176 if (ifa) {
4177 ifaddr_release(ifa);
4178 }
4179
0a7de745 4180 return matched_local_address;
39037602
A
4181}
4182
5ba3f43e
A
4183static bool
4184necp_interface_type_is_primary_eligible(u_int8_t interface_type)
4185{
4186 switch (interface_type) {
0a7de745
A
4187 // These types can never be primary, so a client requesting these types is allowed
4188 // to match an interface that isn't currently eligible to be primary (has default
4189 // route, dns, etc)
4190 case IFRTYPE_FUNCTIONAL_WIFI_AWDL:
4191 case IFRTYPE_FUNCTIONAL_INTCOPROC:
4192 return false;
4193 default:
4194 break;
5ba3f43e
A
4195 }
4196 return true;
4197}
4198
4199#define NECP_IFP_IS_ON_ORDERED_LIST(_ifp) ((_ifp)->if_ordered_link.tqe_next != NULL || (_ifp)->if_ordered_link.tqe_prev != NULL)
4200
d9a64523
A
4201// Secondary interface flag indicates that the interface is being
4202// used for multipath or a listener as an extra path
39037602
A
4203static bool
4204necp_ifnet_matches_parameters(struct ifnet *ifp,
0a7de745 4205 struct necp_client_parsed_parameters *parsed_parameters,
cb323159 4206 u_int32_t override_flags,
0a7de745 4207 u_int32_t *preferred_count,
cb323159
A
4208 bool secondary_interface,
4209 bool require_scoped_field)
39037602 4210{
cb323159
A
4211 bool matched_some_scoped_field = FALSE;
4212
39037602
A
4213 if (preferred_count) {
4214 *preferred_count = 0;
4215 }
4216
cb323159
A
4217 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IF) {
4218 if (parsed_parameters->required_interface_index != ifp->if_index) {
4219 return FALSE;
4220 }
4221 }
4222
39037602
A
4223 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR) {
4224 if (!necp_ifnet_matches_local_address(ifp, &parsed_parameters->local_addr.sa)) {
0a7de745 4225 return FALSE;
39037602 4226 }
cb323159
A
4227 if (require_scoped_field) {
4228 matched_some_scoped_field = TRUE;
4229 }
39037602
A
4230 }
4231
5ba3f43e 4232 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_FLAGS) {
cb323159
A
4233 if (override_flags != 0) {
4234 if ((override_flags & NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_EXPENSIVE) &&
4235 IFNET_IS_EXPENSIVE(ifp)) {
4236 return FALSE;
4237 }
4238 if ((override_flags & NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_CONSTRAINED) &&
4239 IFNET_IS_CONSTRAINED(ifp)) {
4240 return FALSE;
4241 }
4242 } else {
4243 if ((parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_EXPENSIVE) &&
4244 IFNET_IS_EXPENSIVE(ifp)) {
4245 return FALSE;
4246 }
4247 if ((parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_CONSTRAINED) &&
4248 IFNET_IS_CONSTRAINED(ifp)) {
4249 return FALSE;
4250 }
39037602
A
4251 }
4252 }
4253
d9a64523 4254 if ((!secondary_interface || // Enforce interface type if this is the primary interface
0a7de745
A
4255 !(parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_FLAGS) || // or if there are no flags
4256 !(parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_ONLY_PRIMARY_REQUIRES_TYPE)) && // or if the flags don't give an exception
5ba3f43e 4257 (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE) &&
0a7de745
A
4258 !necp_ifnet_matches_type(ifp, parsed_parameters->required_interface_type, FALSE)) {
4259 return FALSE;
5ba3f43e
A
4260 }
4261
cb323159
A
4262 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE) {
4263 if (require_scoped_field) {
4264 matched_some_scoped_field = TRUE;
4265 }
4266 }
4267
39037602 4268 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IFTYPE) {
cb323159 4269 for (int i = 0; i < NECP_MAX_INTERFACE_PARAMETERS; i++) {
39037602
A
4270 if (parsed_parameters->prohibited_interface_types[i] == 0) {
4271 break;
4272 }
4273
4274 if (necp_ifnet_matches_type(ifp, parsed_parameters->prohibited_interface_types[i], TRUE)) {
0a7de745 4275 return FALSE;
39037602
A
4276 }
4277 }
4278 }
4279
4280 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IF) {
cb323159 4281 for (int i = 0; i < NECP_MAX_INTERFACE_PARAMETERS; i++) {
39037602
A
4282 if (strlen(parsed_parameters->prohibited_interfaces[i]) == 0) {
4283 break;
4284 }
4285
4286 if (necp_ifnet_matches_name(ifp, parsed_parameters->prohibited_interfaces[i], TRUE)) {
0a7de745 4287 return FALSE;
39037602
A
4288 }
4289 }
4290 }
4291
4292 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT) {
cb323159 4293 for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
39037602
A
4294 if (uuid_is_null(parsed_parameters->required_netagents[i])) {
4295 break;
4296 }
4297
4298 if (!necp_ifnet_matches_agent(ifp, &parsed_parameters->required_netagents[i], FALSE)) {
0a7de745 4299 return FALSE;
39037602 4300 }
cb323159
A
4301
4302 if (require_scoped_field) {
4303 matched_some_scoped_field = TRUE;
4304 }
39037602
A
4305 }
4306 }
4307
4308 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT) {
cb323159 4309 for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
39037602
A
4310 if (uuid_is_null(parsed_parameters->prohibited_netagents[i])) {
4311 break;
4312 }
4313
4314 if (necp_ifnet_matches_agent(ifp, &parsed_parameters->prohibited_netagents[i], TRUE)) {
0a7de745 4315 return FALSE;
39037602
A
4316 }
4317 }
4318 }
4319
4320 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE) {
cb323159 4321 for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
39037602 4322 if (strlen(parsed_parameters->required_netagent_types[i].netagent_domain) == 0 &&
0a7de745 4323 strlen(parsed_parameters->required_netagent_types[i].netagent_type) == 0) {
39037602
A
4324 break;
4325 }
4326
d9a64523 4327 if (!necp_ifnet_matches_agent_type(ifp, parsed_parameters->required_netagent_types[i].netagent_domain, parsed_parameters->required_netagent_types[i].netagent_type, FALSE)) {
0a7de745 4328 return FALSE;
39037602 4329 }
cb323159
A
4330
4331 if (require_scoped_field) {
4332 matched_some_scoped_field = TRUE;
4333 }
39037602
A
4334 }
4335 }
4336
4337 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT_TYPE) {
cb323159 4338 for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
39037602 4339 if (strlen(parsed_parameters->prohibited_netagent_types[i].netagent_domain) == 0 &&
0a7de745 4340 strlen(parsed_parameters->prohibited_netagent_types[i].netagent_type) == 0) {
39037602
A
4341 break;
4342 }
4343
d9a64523 4344 if (necp_ifnet_matches_agent_type(ifp, parsed_parameters->prohibited_netagent_types[i].netagent_domain, parsed_parameters->prohibited_netagent_types[i].netagent_type, TRUE)) {
0a7de745 4345 return FALSE;
39037602
A
4346 }
4347 }
4348 }
4349
4350 // Checked preferred properties
4351 if (preferred_count) {
4352 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT) {
cb323159 4353 for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
39037602
A
4354 if (uuid_is_null(parsed_parameters->preferred_netagents[i])) {
4355 break;
4356 }
4357
4358 if (necp_ifnet_matches_agent(ifp, &parsed_parameters->preferred_netagents[i], TRUE)) {
4359 (*preferred_count)++;
cb323159
A
4360 if (require_scoped_field) {
4361 matched_some_scoped_field = TRUE;
4362 }
39037602
A
4363 }
4364 }
4365 }
4366
4367 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT_TYPE) {
cb323159 4368 for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
39037602 4369 if (strlen(parsed_parameters->preferred_netagent_types[i].netagent_domain) == 0 &&
0a7de745 4370 strlen(parsed_parameters->preferred_netagent_types[i].netagent_type) == 0) {
39037602
A
4371 break;
4372 }
4373
d9a64523
A
4374 if (necp_ifnet_matches_agent_type(ifp, parsed_parameters->preferred_netagent_types[i].netagent_domain, parsed_parameters->preferred_netagent_types[i].netagent_type, TRUE)) {
4375 (*preferred_count)++;
cb323159
A
4376 if (require_scoped_field) {
4377 matched_some_scoped_field = TRUE;
4378 }
d9a64523
A
4379 }
4380 }
4381 }
4382
4383 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT) {
cb323159 4384 for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
d9a64523
A
4385 if (uuid_is_null(parsed_parameters->avoided_netagents[i])) {
4386 break;
4387 }
4388
4389 if (!necp_ifnet_matches_agent(ifp, &parsed_parameters->avoided_netagents[i], TRUE)) {
4390 (*preferred_count)++;
4391 }
4392 }
4393 }
4394
4395 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT_TYPE) {
cb323159 4396 for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
d9a64523 4397 if (strlen(parsed_parameters->avoided_netagent_types[i].netagent_domain) == 0 &&
0a7de745 4398 strlen(parsed_parameters->avoided_netagent_types[i].netagent_type) == 0) {
d9a64523
A
4399 break;
4400 }
4401
4402 if (!necp_ifnet_matches_agent_type(ifp, parsed_parameters->avoided_netagent_types[i].netagent_domain,
0a7de745 4403 parsed_parameters->avoided_netagent_types[i].netagent_type, TRUE)) {
39037602
A
4404 (*preferred_count)++;
4405 }
4406 }
4407 }
4408 }
4409
cb323159
A
4410 if (require_scoped_field) {
4411 return matched_some_scoped_field;
4412 }
4413
0a7de745 4414 return TRUE;
39037602
A
4415}
4416
4417static bool
d9a64523 4418necp_find_matching_interface_index(struct necp_client_parsed_parameters *parsed_parameters,
0a7de745 4419 u_int *return_ifindex, bool *validate_agents)
39037602
A
4420{
4421 struct ifnet *ifp = NULL;
4422 u_int32_t best_preferred_count = 0;
4423 bool has_preferred_fields = FALSE;
4424 *return_ifindex = 0;
4425
4426 if (parsed_parameters->required_interface_index != 0) {
4427 *return_ifindex = parsed_parameters->required_interface_index;
0a7de745 4428 return TRUE;
39037602
A
4429 }
4430
cb323159
A
4431 // Check and save off flags
4432 u_int32_t flags = 0;
4433 bool has_prohibit_flags = FALSE;
4434 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_FLAGS) {
4435 flags = parsed_parameters->flags;
4436 has_prohibit_flags = (parsed_parameters->flags &
4437 (NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_EXPENSIVE |
4438 NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_CONSTRAINED));
4439 }
4440
4441 if (!(parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_INTERESTING_IFNET_FIELDS) &&
4442 !has_prohibit_flags) {
0a7de745 4443 return TRUE;
39037602
A
4444 }
4445
d9a64523 4446 has_preferred_fields = (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_PREFERRED_FIELDS);
39037602
A
4447
4448 // We have interesting parameters to parse and find a matching interface
4449 ifnet_head_lock_shared();
4450
cb323159
A
4451 if (!(parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_SCOPED_FIELDS) &&
4452 !has_preferred_fields) {
39037602 4453 // We do have fields to match, but they are only prohibitory
5ba3f43e 4454 // If the first interface in the list matches, or there are no ordered interfaces, we don't need to scope
39037602 4455 ifp = TAILQ_FIRST(&ifnet_ordered_head);
cb323159 4456 if (ifp == NULL || necp_ifnet_matches_parameters(ifp, parsed_parameters, 0, NULL, false, false)) {
39037602
A
4457 // Don't set return_ifindex, so the client doesn't need to scope
4458 ifnet_head_done();
0a7de745 4459 return TRUE;
39037602
A
4460 }
4461 }
4462
4463 // First check the ordered interface list
4464 TAILQ_FOREACH(ifp, &ifnet_ordered_head, if_ordered_link) {
4465 u_int32_t preferred_count = 0;
cb323159 4466 if (necp_ifnet_matches_parameters(ifp, parsed_parameters, flags, &preferred_count, false, false)) {
39037602 4467 if (preferred_count > best_preferred_count ||
0a7de745 4468 *return_ifindex == 0) {
39037602
A
4469 // Everything matched, and is most preferred. Return this interface.
4470 *return_ifindex = ifp->if_index;
4471 best_preferred_count = preferred_count;
4472
4473 if (!has_preferred_fields) {
4474 break;
4475 }
4476 }
4477 }
cb323159
A
4478
4479 if (has_prohibit_flags &&
4480 ifp == TAILQ_FIRST(&ifnet_ordered_head)) {
4481 // This was the first interface. From here on, if the
4482 // client prohibited either expensive or constrained,
4483 // don't allow either as a secondary interface option.
4484 flags |= (NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_EXPENSIVE |
4485 NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_CONSTRAINED);
4486 }
39037602
A
4487 }
4488
cb323159
A
4489 bool is_listener = ((parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_FLAGS) &&
4490 (parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER));
4491
39037602 4492 // Then check the remaining interfaces
d9a64523 4493 if ((parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_SCOPED_FIELDS) &&
0a7de745 4494 ((!(parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE)) ||
cb323159
A
4495 !necp_interface_type_is_primary_eligible(parsed_parameters->required_interface_type) ||
4496 (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR) ||
4497 is_listener) &&
4498 (*return_ifindex == 0 || has_preferred_fields)) {
39037602
A
4499 TAILQ_FOREACH(ifp, &ifnet_head, if_link) {
4500 u_int32_t preferred_count = 0;
5ba3f43e 4501 if (NECP_IFP_IS_ON_ORDERED_LIST(ifp)) {
39037602
A
4502 // This interface was in the ordered list, skip
4503 continue;
4504 }
cb323159 4505 if (necp_ifnet_matches_parameters(ifp, parsed_parameters, flags, &preferred_count, false, true)) {
39037602 4506 if (preferred_count > best_preferred_count ||
0a7de745 4507 *return_ifindex == 0) {
39037602
A
4508 // Everything matched, and is most preferred. Return this interface.
4509 *return_ifindex = ifp->if_index;
4510 best_preferred_count = preferred_count;
4511
4512 if (!has_preferred_fields) {
4513 break;
4514 }
4515 }
4516 }
4517 }
4518 }
4519
4520 ifnet_head_done();
4521
f427ee49
A
4522 if (has_preferred_fields && best_preferred_count == 0 &&
4523 ((parsed_parameters->valid_fields & (NECP_PARSED_PARAMETERS_SCOPED_FIELDS | NECP_PARSED_PARAMETERS_PREFERRED_FIELDS)) ==
4524 (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_PREFERRED_FIELDS))) {
4525 // If only has preferred ifnet fields, and nothing was found, clear the interface index and return TRUE
39037602 4526 *return_ifindex = 0;
0a7de745 4527 return TRUE;
39037602
A
4528 }
4529
d9a64523 4530 if (*return_ifindex == 0 &&
0a7de745 4531 !(parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_SCOPED_IFNET_FIELDS)) {
d9a64523
A
4532 // Has required fields, but not including specific interface fields. Pass for now, and check
4533 // to see if agents are satisfied by policy.
4534 *validate_agents = TRUE;
0a7de745 4535 return TRUE;
d9a64523
A
4536 }
4537
0a7de745 4538 return *return_ifindex != 0;
39037602
A
4539}
4540
39037602
A
4541
4542static int
4543necp_skywalk_priv_check_cred(proc_t p, kauth_cred_t cred)
4544{
4545#pragma unused(p, cred)
0a7de745 4546 return 0;
39037602
A
4547}
4548
4549/// System calls
4550
4551int
4552necp_open(struct proc *p, struct necp_open_args *uap, int *retval)
4553{
4554#pragma unused(retval)
4555 int error = 0;
4556 struct necp_fd_data *fd_data = NULL;
4557 struct fileproc *fp = NULL;
4558 int fd = -1;
4559
d9a64523 4560 if (uap->flags & NECP_OPEN_FLAG_OBSERVER ||
0a7de745 4561 uap->flags & NECP_OPEN_FLAG_PUSH_OBSERVER) {
39037602 4562 if (necp_skywalk_priv_check_cred(p, kauth_cred_get()) != 0 &&
0a7de745 4563 priv_check_cred(kauth_cred_get(), PRIV_NET_PRIVILEGED_NETWORK_STATISTICS, 0) != 0) {
39037602
A
4564 NECPLOG0(LOG_ERR, "Client does not hold necessary entitlement to observe other NECP clients");
4565 error = EACCES;
4566 goto done;
4567 }
4568 }
4569
4570 error = falloc(p, &fp, &fd, vfs_context_current());
4571 if (error != 0) {
4572 goto done;
4573 }
4574
5ba3f43e 4575 if ((fd_data = zalloc(necp_client_fd_zone)) == NULL) {
39037602
A
4576 error = ENOMEM;
4577 goto done;
4578 }
4579
5ba3f43e
A
4580 memset(fd_data, 0, sizeof(*fd_data));
4581
4582 fd_data->necp_fd_type = necp_fd_type_client;
39037602 4583 fd_data->flags = uap->flags;
5ba3f43e 4584 RB_INIT(&fd_data->clients);
d9a64523 4585 RB_INIT(&fd_data->flows);
5ba3f43e 4586 TAILQ_INIT(&fd_data->update_list);
39037602
A
4587 lck_mtx_init(&fd_data->fd_lock, necp_fd_mtx_grp, necp_fd_mtx_attr);
4588 klist_init(&fd_data->si.si_note);
4589 fd_data->proc_pid = proc_pid(p);
4590
f427ee49
A
4591 fp->fp_glob->fg_flag = FREAD;
4592 fp->fp_glob->fg_ops = &necp_fd_ops;
4593 fp->fp_glob->fg_data = fd_data;
39037602
A
4594
4595 proc_fdlock(p);
4596
4597 *fdflags(p, fd) |= (UF_EXCLOSE | UF_FORKCLOSE);
4598 procfdtbl_releasefd(p, fd, NULL);
4599 fp_drop(p, fd, fp, 1);
39037602
A
4600
4601 *retval = fd;
4602
5ba3f43e
A
4603 if (fd_data->flags & NECP_OPEN_FLAG_PUSH_OBSERVER) {
4604 NECP_OBSERVER_LIST_LOCK_EXCLUSIVE();
4605 LIST_INSERT_HEAD(&necp_fd_observer_list, fd_data, chain);
4606 OSIncrementAtomic(&necp_observer_fd_count);
4607 NECP_OBSERVER_LIST_UNLOCK();
4608
4609 // Walk all existing clients and add them
4610 NECP_CLIENT_TREE_LOCK_SHARED();
4611 struct necp_client *existing_client = NULL;
4612 RB_FOREACH(existing_client, _necp_client_global_tree, &necp_client_global_tree) {
4613 NECP_CLIENT_LOCK(existing_client);
4614 necp_client_update_observer_add_internal(fd_data, existing_client);
4615 necp_client_update_observer_update_internal(fd_data, existing_client);
4616 NECP_CLIENT_UNLOCK(existing_client);
4617 }
4618 NECP_CLIENT_TREE_UNLOCK();
4619 } else {
4620 NECP_FD_LIST_LOCK_EXCLUSIVE();
4621 LIST_INSERT_HEAD(&necp_fd_list, fd_data, chain);
4622 OSIncrementAtomic(&necp_client_fd_count);
4623 NECP_FD_LIST_UNLOCK();
4624 }
39037602 4625
813fb2f6
A
4626 proc_fdunlock(p);
4627
39037602
A
4628done:
4629 if (error != 0) {
4630 if (fp != NULL) {
4631 fp_free(p, fd, fp);
4632 fp = NULL;
4633 }
4634 if (fd_data != NULL) {
5ba3f43e 4635 zfree(necp_client_fd_zone, fd_data);
39037602
A
4636 fd_data = NULL;
4637 }
4638 }
4639
0a7de745 4640 return error;
39037602
A
4641}
4642
cb323159
A
4643// All functions called directly from necp_client_action() to handle one of the
4644// types should be marked with NECP_CLIENT_ACTION_FUNCTION. This ensures that
4645// necp_client_action() does not inline all the actions into a single function.
4646#define NECP_CLIENT_ACTION_FUNCTION __attribute__((noinline))
4647
4648static NECP_CLIENT_ACTION_FUNCTION int
5ba3f43e 4649necp_client_add(struct proc *p, struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
39037602
A
4650{
4651 int error = 0;
4652 struct necp_client *client = NULL;
f427ee49 4653 const size_t buffer_size = uap->buffer_size;
39037602 4654
5ba3f43e
A
4655 if (fd_data->flags & NECP_OPEN_FLAG_PUSH_OBSERVER) {
4656 NECPLOG0(LOG_ERR, "NECP client observers with push enabled may not add their own clients");
0a7de745 4657 return EINVAL;
5ba3f43e
A
4658 }
4659
39037602 4660 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t) ||
f427ee49 4661 buffer_size == 0 || buffer_size > NECP_MAX_CLIENT_PARAMETERS_SIZE || uap->buffer == 0) {
0a7de745 4662 return EINVAL;
39037602
A
4663 }
4664
f427ee49 4665 if ((client = _MALLOC(sizeof(struct necp_client) + buffer_size, M_NECP,
0a7de745 4666 M_WAITOK | M_ZERO)) == NULL) {
39037602
A
4667 error = ENOMEM;
4668 goto done;
4669 }
4670
f427ee49 4671 error = copyin(uap->buffer, client->parameters, buffer_size);
39037602
A
4672 if (error) {
4673 NECPLOG(LOG_ERR, "necp_client_add parameters copyin error (%d)", error);
4674 goto done;
4675 }
4676
5ba3f43e
A
4677 lck_mtx_init(&client->lock, necp_fd_mtx_grp, necp_fd_mtx_attr);
4678 lck_mtx_init(&client->route_lock, necp_fd_mtx_grp, necp_fd_mtx_attr);
cb323159
A
4679
4680 os_ref_init(&client->reference_count, &necp_client_refgrp); // Hold our reference until close
5ba3f43e 4681
f427ee49 4682 client->parameters_length = buffer_size;
5ba3f43e 4683 client->proc_pid = fd_data->proc_pid; // Save off proc pid in case the client will persist past fd
d9a64523 4684 client->agent_handle = (void *)fd_data;
5ba3f43e 4685 client->platform_binary = ((csproc_get_platform_binary(p) == 0) ? 0 : 1);
39037602 4686
d9a64523 4687 necp_generate_client_id(client->client_id, false);
39037602 4688 LIST_INIT(&client->assertion_list);
d9a64523 4689 RB_INIT(&client->flow_registrations);
39037602
A
4690
4691 error = copyout(client->client_id, uap->client_id, sizeof(uuid_t));
4692 if (error) {
4693 NECPLOG(LOG_ERR, "necp_client_add client_id copyout error (%d)", error);
4694 goto done;
4695 }
4696
cb323159 4697
5ba3f43e
A
4698 necp_client_update_observer_add(client);
4699
4700 NECP_FD_LOCK(fd_data);
4701 RB_INSERT(_necp_client_tree, &fd_data->clients, client);
4702 OSIncrementAtomic(&necp_client_count);
4703 NECP_CLIENT_TREE_LOCK_EXCLUSIVE();
4704 RB_INSERT(_necp_client_global_tree, &necp_client_global_tree, client);
4705 NECP_CLIENT_TREE_UNLOCK();
39037602
A
4706
4707 // Prime the client result
5ba3f43e
A
4708 NECP_CLIENT_LOCK(client);
4709 (void)necp_update_client_result(current_proc(), fd_data, client, NULL);
4710 NECP_CLIENT_UNLOCK(client);
4711 NECP_FD_UNLOCK(fd_data);
39037602
A
4712done:
4713 if (error != 0) {
4714 if (client != NULL) {
4715 FREE(client, M_NECP);
4716 client = NULL;
4717 }
4718 }
4719 *retval = error;
4720
0a7de745 4721 return error;
39037602
A
4722}
4723
cb323159
A
4724static NECP_CLIENT_ACTION_FUNCTION int
4725necp_client_claim(struct proc *p, struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
4726{
4727 int error = 0;
4728 uuid_t client_id = {};
4729 struct necp_client *client = NULL;
4730
4731 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t)) {
4732 error = EINVAL;
4733 goto done;
4734 }
4735
4736 error = copyin(uap->client_id, client_id, sizeof(uuid_t));
4737 if (error) {
4738 NECPLOG(LOG_ERR, "necp_client_claim copyin client_id error (%d)", error);
4739 goto done;
4740 }
4741
4742 u_int64_t upid = proc_uniqueid(p);
4743
4744 NECP_FD_LIST_LOCK_SHARED();
4745
4746 struct necp_fd_data *find_fd = NULL;
4747 LIST_FOREACH(find_fd, &necp_fd_list, chain) {
4748 NECP_FD_LOCK(find_fd);
4749 struct necp_client *find_client = necp_client_fd_find_client_and_lock(find_fd, client_id);
4750 if (find_client != NULL) {
4751 if (find_client->delegated_upid == upid) {
4752 // Matched the client to claim; remove from the old fd
4753 client = find_client;
4754 RB_REMOVE(_necp_client_tree, &find_fd->clients, client);
4755 necp_client_retain_locked(client);
4756 }
4757 NECP_CLIENT_UNLOCK(find_client);
4758 }
4759 NECP_FD_UNLOCK(find_fd);
4760
4761 if (client != NULL) {
4762 break;
4763 }
4764 }
4765
4766 NECP_FD_LIST_UNLOCK();
4767
4768 if (client == NULL) {
4769 error = ENOENT;
4770 goto done;
4771 }
4772
4773 client->proc_pid = fd_data->proc_pid; // Transfer client to claiming pid
f427ee49
A
4774 client->agent_handle = (void *)fd_data;
4775 client->platform_binary = ((csproc_get_platform_binary(p) == 0) ? 0 : 1);
cb323159
A
4776
4777 // Add matched client to our fd and re-run result
4778 NECP_FD_LOCK(fd_data);
4779 RB_INSERT(_necp_client_tree, &fd_data->clients, client);
4780 NECP_CLIENT_LOCK(client);
4781 (void)necp_update_client_result(current_proc(), fd_data, client, NULL);
4782 NECP_CLIENT_UNLOCK(client);
4783 NECP_FD_UNLOCK(fd_data);
4784
4785 necp_client_release(client);
4786
4787done:
4788 *retval = error;
4789
4790 return error;
4791}
4792
4793static NECP_CLIENT_ACTION_FUNCTION int
39037602
A
4794necp_client_remove(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
4795{
4796 int error = 0;
5ba3f43e
A
4797 uuid_t client_id = {};
4798 struct ifnet_stats_per_flow flow_ifnet_stats = {};
f427ee49 4799 const size_t buffer_size = uap->buffer_size;
39037602
A
4800
4801 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t)) {
4802 error = EINVAL;
4803 goto done;
4804 }
4805
4806 error = copyin(uap->client_id, client_id, sizeof(uuid_t));
4807 if (error) {
4808 NECPLOG(LOG_ERR, "necp_client_remove copyin client_id error (%d)", error);
4809 goto done;
4810 }
4811
f427ee49
A
4812 if (uap->buffer != 0 && buffer_size == sizeof(flow_ifnet_stats)) {
4813 error = copyin(uap->buffer, &flow_ifnet_stats, buffer_size);
5ba3f43e
A
4814 if (error) {
4815 NECPLOG(LOG_ERR, "necp_client_remove flow_ifnet_stats copyin error (%d)", error);
a39ff7e2 4816 // Not fatal; make sure to zero-out stats in case of partial copy
0a7de745 4817 memset(&flow_ifnet_stats, 0, sizeof(flow_ifnet_stats));
a39ff7e2 4818 error = 0;
5ba3f43e
A
4819 }
4820 } else if (uap->buffer != 0) {
f427ee49 4821 NECPLOG(LOG_ERR, "necp_client_remove unexpected parameters length (%zu)", buffer_size);
5ba3f43e
A
4822 }
4823
5ba3f43e 4824 NECP_FD_LOCK(fd_data);
a39ff7e2 4825
5ba3f43e 4826 pid_t pid = fd_data->proc_pid;
d9a64523 4827 struct necp_client *client = necp_client_fd_find_client_unlocked(fd_data, client_id);
a39ff7e2 4828 if (client != NULL) {
d9a64523
A
4829 // Remove any flow registrations that match
4830 struct necp_client_flow_registration *flow_registration = NULL;
4831 struct necp_client_flow_registration *temp_flow_registration = NULL;
4832 RB_FOREACH_SAFE(flow_registration, _necp_fd_flow_tree, &fd_data->flows, temp_flow_registration) {
4833 if (flow_registration->client == client) {
4834 NECP_FLOW_TREE_LOCK_EXCLUSIVE();
4835 RB_REMOVE(_necp_client_flow_global_tree, &necp_client_flow_global_tree, flow_registration);
4836 NECP_FLOW_TREE_UNLOCK();
4837 RB_REMOVE(_necp_fd_flow_tree, &fd_data->flows, flow_registration);
4838 }
4839 }
4840 // Remove client from lists
a39ff7e2
A
4841 NECP_CLIENT_TREE_LOCK_EXCLUSIVE();
4842 RB_REMOVE(_necp_client_global_tree, &necp_client_global_tree, client);
4843 NECP_CLIENT_TREE_UNLOCK();
4844 RB_REMOVE(_necp_client_tree, &fd_data->clients, client);
39037602 4845 }
5ba3f43e 4846
d9a64523 4847
5ba3f43e
A
4848 NECP_FD_UNLOCK(fd_data);
4849
a39ff7e2
A
4850 if (client != NULL) {
4851 ASSERT(error == 0);
5ba3f43e 4852 necp_destroy_client(client, pid, true);
a39ff7e2
A
4853 } else {
4854 error = ENOENT;
4855 NECPLOG(LOG_ERR, "necp_client_remove invalid client_id (%d)", error);
5ba3f43e 4856 }
39037602
A
4857done:
4858 *retval = error;
4859
0a7de745 4860 return error;
39037602
A
4861}
4862
f427ee49
A
4863static struct necp_client_flow_registration *
4864necp_client_fd_find_flow(struct necp_fd_data *client_fd, uuid_t flow_id)
4865{
4866 NECP_FD_ASSERT_LOCKED(client_fd);
4867 struct necp_client_flow_registration *flow = NULL;
4868
4869 if (necp_client_id_is_flow(flow_id)) {
4870 struct necp_client_flow_registration find;
4871 uuid_copy(find.registration_id, flow_id);
4872 flow = RB_FIND(_necp_fd_flow_tree, &client_fd->flows, &find);
4873 }
4874
4875 return flow;
4876}
4877
4878static NECP_CLIENT_ACTION_FUNCTION int
4879necp_client_remove_flow(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
4880{
4881 int error = 0;
4882 uuid_t flow_id = {};
4883 struct ifnet_stats_per_flow flow_ifnet_stats = {};
4884 const size_t buffer_size = uap->buffer_size;
4885
4886 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t)) {
4887 error = EINVAL;
4888 NECPLOG(LOG_ERR, "necp_client_remove_flow invalid client_id (length %zu)", (size_t)uap->client_id_len);
4889 goto done;
4890 }
4891
4892 error = copyin(uap->client_id, flow_id, sizeof(uuid_t));
4893 if (error) {
4894 NECPLOG(LOG_ERR, "necp_client_remove_flow copyin client_id error (%d)", error);
4895 goto done;
4896 }
4897
4898 if (uap->buffer != 0 && buffer_size == sizeof(flow_ifnet_stats)) {
4899 error = copyin(uap->buffer, &flow_ifnet_stats, buffer_size);
4900 if (error) {
4901 NECPLOG(LOG_ERR, "necp_client_remove flow_ifnet_stats copyin error (%d)", error);
4902 // Not fatal
4903 }
4904 } else if (uap->buffer != 0) {
4905 NECPLOG(LOG_ERR, "necp_client_remove unexpected parameters length (%zu)", buffer_size);
4906 }
4907
4908 NECP_FD_LOCK(fd_data);
4909 struct necp_client *client = NULL;
4910 struct necp_client_flow_registration *flow_registration = necp_client_fd_find_flow(fd_data, flow_id);
4911 if (flow_registration != NULL) {
4912 NECP_FLOW_TREE_LOCK_EXCLUSIVE();
4913 RB_REMOVE(_necp_client_flow_global_tree, &necp_client_flow_global_tree, flow_registration);
4914 NECP_FLOW_TREE_UNLOCK();
4915 RB_REMOVE(_necp_fd_flow_tree, &fd_data->flows, flow_registration);
4916
4917 client = flow_registration->client;
4918 if (client != NULL) {
4919 necp_client_retain(client);
4920 }
4921 }
4922 NECP_FD_UNLOCK(fd_data);
4923
4924 if (flow_registration != NULL && client != NULL) {
4925 NECP_CLIENT_LOCK(client);
4926 if (flow_registration->client == client) {
4927 necp_destroy_client_flow_registration(client, flow_registration, fd_data->proc_pid, false);
4928 }
4929 necp_client_release_locked(client);
4930 NECP_CLIENT_UNLOCK(client);
4931 }
4932
4933done:
4934 *retval = error;
4935 if (error != 0) {
4936 NECPLOG(LOG_ERR, "Remove flow error (%d)", error);
4937 }
4938
4939 return error;
4940}
d9a64523 4941
cb323159
A
4942// Don't inline the function since it includes necp_client_parsed_parameters on the stack
4943static __attribute__((noinline)) int
5ba3f43e
A
4944necp_client_check_tcp_heuristics(struct necp_client *client, struct necp_client_flow *flow, u_int32_t *flags, u_int8_t *tfo_cookie, u_int8_t *tfo_cookie_len)
4945{
4946 struct necp_client_parsed_parameters parsed_parameters;
4947 int error = 0;
4948
4949 error = necp_client_parse_parameters(client->parameters,
0a7de745
A
4950 (u_int32_t)client->parameters_length,
4951 &parsed_parameters);
5ba3f43e
A
4952 if (error) {
4953 NECPLOG(LOG_ERR, "necp_client_parse_parameters error (%d)", error);
0a7de745 4954 return error;
5ba3f43e
A
4955 }
4956
4957 if ((flow->remote_addr.sa.sa_family != AF_INET &&
0a7de745
A
4958 flow->remote_addr.sa.sa_family != AF_INET6) ||
4959 (flow->local_addr.sa.sa_family != AF_INET &&
4960 flow->local_addr.sa.sa_family != AF_INET6)) {
4961 return EINVAL;
5ba3f43e
A
4962 }
4963
4964 NECP_CLIENT_ROUTE_LOCK(client);
4965
4966 if (client->current_route == NULL) {
0a7de745
A
4967 error = ENOENT;
4968 goto do_unlock;
5ba3f43e
A
4969 }
4970
4971 bool check_ecn = false;
4972 do {
4973 if ((parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_ECN_ENABLE) ==
0a7de745 4974 NECP_CLIENT_PARAMETER_FLAG_ECN_ENABLE) {
5ba3f43e
A
4975 check_ecn = true;
4976 break;
4977 }
4978
4979 if ((parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_ECN_DISABLE) ==
0a7de745 4980 NECP_CLIENT_PARAMETER_FLAG_ECN_DISABLE) {
5ba3f43e
A
4981 break;
4982 }
4983
4984 if (client->current_route != NULL) {
4985 if (client->current_route->rt_ifp->if_eflags & IFEF_ECN_ENABLE) {
4986 check_ecn = true;
4987 break;
4988 }
4989 if (client->current_route->rt_ifp->if_eflags & IFEF_ECN_DISABLE) {
4990 break;
4991 }
4992 }
4993
4994 bool inbound = ((parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) == 0);
4995 if ((inbound && tcp_ecn_inbound == 1) ||
0a7de745 4996 (!inbound && tcp_ecn_outbound == 1)) {
5ba3f43e
A
4997 check_ecn = true;
4998 }
4999 } while (false);
5000
5001 if (check_ecn) {
5002 if (tcp_heuristic_do_ecn_with_address(client->current_route->rt_ifp,
0a7de745 5003 (union sockaddr_in_4_6 *)&flow->local_addr)) {
5ba3f43e
A
5004 *flags |= NECP_CLIENT_RESULT_FLAG_ECN_ENABLED;
5005 }
5006 }
5007
5008 if ((parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_TFO_ENABLE) ==
0a7de745 5009 NECP_CLIENT_PARAMETER_FLAG_TFO_ENABLE) {
5ba3f43e 5010 if (!tcp_heuristic_do_tfo_with_address(client->current_route->rt_ifp,
0a7de745
A
5011 (union sockaddr_in_4_6 *)&flow->local_addr,
5012 (union sockaddr_in_4_6 *)&flow->remote_addr,
5013 tfo_cookie, tfo_cookie_len)) {
5ba3f43e
A
5014 *flags |= NECP_CLIENT_RESULT_FLAG_FAST_OPEN_BLOCKED;
5015 *tfo_cookie_len = 0;
5016 }
5017 } else {
5018 *flags |= NECP_CLIENT_RESULT_FLAG_FAST_OPEN_BLOCKED;
5019 *tfo_cookie_len = 0;
5020 }
5021do_unlock:
5022 NECP_CLIENT_ROUTE_UNLOCK(client);
5023
0a7de745 5024 return error;
5ba3f43e
A
5025}
5026
d9a64523
A
5027static size_t
5028necp_client_calculate_flow_tlv_size(struct necp_client_flow_registration *flow_registration)
5029{
5030 size_t assigned_results_size = 0;
5031 struct necp_client_flow *flow = NULL;
5032 LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
5033 if (flow->assigned) {
5034 size_t header_length = 0;
5035 if (flow->nexus) {
5036 header_length = sizeof(struct necp_client_nexus_flow_header);
5037 } else {
5038 header_length = sizeof(struct necp_client_flow_header);
5039 }
5040 assigned_results_size += (header_length + flow->assigned_results_length);
5041
5042 if (flow->has_protoctl_event) {
5043 assigned_results_size += sizeof(struct necp_client_flow_protoctl_event_header);
5044 }
5045 }
5046 }
5047 return assigned_results_size;
5048}
5049
5050static int
5051necp_client_fillout_flow_tlvs(struct necp_client *client,
0a7de745
A
5052 bool client_is_observed,
5053 struct necp_client_flow_registration *flow_registration,
5054 struct necp_client_action_args *uap,
5055 size_t *assigned_results_cursor)
d9a64523
A
5056{
5057 int error = 0;
5058 struct necp_client_flow *flow = NULL;
5059 LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
5060 if (flow->assigned) {
5061 // Write TLV headers
5062 struct necp_client_nexus_flow_header header = {};
5063 u_int32_t length = 0;
5064 u_int32_t flags = 0;
5065 u_int8_t tfo_cookie_len = 0;
5066 u_int8_t type = 0;
5067
5068 type = NECP_CLIENT_RESULT_FLOW_ID;
5069 length = sizeof(header.flow_header.flow_id);
5070 memcpy(&header.flow_header.flow_id_tlv_header.type, &type, sizeof(type));
5071 memcpy(&header.flow_header.flow_id_tlv_header.length, &length, sizeof(length));
5072 uuid_copy(header.flow_header.flow_id, flow_registration->registration_id);
5073
5074 if (flow->nexus) {
5075 if (flow->check_tcp_heuristics) {
5076 u_int8_t tfo_cookie[NECP_TFO_COOKIE_LEN_MAX];
5077 tfo_cookie_len = NECP_TFO_COOKIE_LEN_MAX;
5078
5079 if (necp_client_check_tcp_heuristics(client, flow, &flags,
0a7de745 5080 tfo_cookie, &tfo_cookie_len) != 0) {
d9a64523
A
5081 tfo_cookie_len = 0;
5082 } else {
5083 flow->check_tcp_heuristics = FALSE;
5084
5085 if (tfo_cookie_len != 0) {
5086 type = NECP_CLIENT_RESULT_TFO_COOKIE;
5087 length = tfo_cookie_len;
5088 memcpy(&header.tfo_cookie_tlv_header.type, &type, sizeof(type));
5089 memcpy(&header.tfo_cookie_tlv_header.length, &length, sizeof(length));
5090 memcpy(&header.tfo_cookie_value, tfo_cookie, tfo_cookie_len);
5091 }
5092 }
5093 }
5094 }
5095
5096 size_t header_length = 0;
5097 if (flow->nexus) {
5098 if (tfo_cookie_len != 0) {
5099 header_length = sizeof(struct necp_client_nexus_flow_header) - (NECP_TFO_COOKIE_LEN_MAX - tfo_cookie_len);
5100 } else {
5101 header_length = sizeof(struct necp_client_nexus_flow_header) - sizeof(struct necp_tlv_header) - NECP_TFO_COOKIE_LEN_MAX;
5102 }
5103 } else {
5104 header_length = sizeof(struct necp_client_flow_header);
5105 }
5106
5107 type = NECP_CLIENT_RESULT_FLAGS;
5108 length = sizeof(header.flow_header.flags_value);
5109 memcpy(&header.flow_header.flags_tlv_header.type, &type, sizeof(type));
5110 memcpy(&header.flow_header.flags_tlv_header.length, &length, sizeof(length));
5111 if (flow->assigned) {
5112 flags |= NECP_CLIENT_RESULT_FLAG_FLOW_ASSIGNED;
5113 }
5114 if (flow->viable) {
5115 flags |= NECP_CLIENT_RESULT_FLAG_FLOW_VIABLE;
5116 }
5117 if (flow_registration->defunct) {
5118 flags |= NECP_CLIENT_RESULT_FLAG_DEFUNCT;
5119 }
5120 flags |= flow->necp_flow_flags;
5121 memcpy(&header.flow_header.flags_value, &flags, sizeof(flags));
5122
5123 type = NECP_CLIENT_RESULT_INTERFACE;
5124 length = sizeof(header.flow_header.interface_value);
5125 memcpy(&header.flow_header.interface_tlv_header.type, &type, sizeof(type));
5126 memcpy(&header.flow_header.interface_tlv_header.length, &length, sizeof(length));
5127
5128 struct necp_client_result_interface interface_struct;
5129 interface_struct.generation = 0;
5130 interface_struct.index = flow->interface_index;
5131
5132 memcpy(&header.flow_header.interface_value, &interface_struct, sizeof(interface_struct));
5133 if (flow->nexus) {
5134 type = NECP_CLIENT_RESULT_NETAGENT;
5135 length = sizeof(header.agent_value);
5136 memcpy(&header.agent_tlv_header.type, &type, sizeof(type));
5137 memcpy(&header.agent_tlv_header.length, &length, sizeof(length));
5138
5139 struct necp_client_result_netagent agent_struct;
5140 agent_struct.generation = 0;
5141 uuid_copy(agent_struct.netagent_uuid, flow->u.nexus_agent);
5142
5143 memcpy(&header.agent_value, &agent_struct, sizeof(agent_struct));
5144 }
5145
5146 // Don't include outer TLV header in length field
5147 type = NECP_CLIENT_RESULT_FLOW;
5148 length = (header_length - sizeof(struct necp_tlv_header) + flow->assigned_results_length);
5149 if (flow->has_protoctl_event) {
5150 length += sizeof(struct necp_client_flow_protoctl_event_header);
5151 }
5152 memcpy(&header.flow_header.outer_header.type, &type, sizeof(type));
5153 memcpy(&header.flow_header.outer_header.length, &length, sizeof(length));
5154
5155 error = copyout(&header, uap->buffer + client->result_length + *assigned_results_cursor, header_length);
5156 if (error) {
5157 NECPLOG(LOG_ERR, "necp_client_copy assigned results tlv_header copyout error (%d)", error);
0a7de745 5158 return error;
d9a64523
A
5159 }
5160 *assigned_results_cursor += header_length;
5161
5162 if (flow->assigned_results && flow->assigned_results_length) {
5163 // Write inner TLVs
5164 error = copyout(flow->assigned_results, uap->buffer + client->result_length + *assigned_results_cursor,
0a7de745 5165 flow->assigned_results_length);
d9a64523
A
5166 if (error) {
5167 NECPLOG(LOG_ERR, "necp_client_copy assigned results copyout error (%d)", error);
0a7de745 5168 return error;
d9a64523
A
5169 }
5170 }
5171 *assigned_results_cursor += flow->assigned_results_length;
5172
5173 /* Read the protocol event and reset it */
5174 if (flow->has_protoctl_event) {
5175 struct necp_client_flow_protoctl_event_header protoctl_event_header = {};
5176
5177 type = NECP_CLIENT_RESULT_PROTO_CTL_EVENT;
5178 length = sizeof(protoctl_event_header.protoctl_event);
5179
5180 memcpy(&protoctl_event_header.protoctl_tlv_header.type, &type, sizeof(type));
5181 memcpy(&protoctl_event_header.protoctl_tlv_header.length, &length, sizeof(length));
5182 memcpy(&protoctl_event_header.protoctl_event, &flow->protoctl_event,
0a7de745 5183 sizeof(flow->protoctl_event));
d9a64523
A
5184
5185 error = copyout(&protoctl_event_header, uap->buffer + client->result_length + *assigned_results_cursor,
0a7de745 5186 sizeof(protoctl_event_header));
d9a64523
A
5187
5188 if (error) {
5189 NECPLOG(LOG_ERR, "necp_client_copy protocol control event results"
0a7de745
A
5190 " tlv_header copyout error (%d)", error);
5191 return error;
d9a64523
A
5192 }
5193 *assigned_results_cursor += sizeof(protoctl_event_header);
5194 flow->has_protoctl_event = FALSE;
5195 flow->protoctl_event.protoctl_event_code = 0;
5196 flow->protoctl_event.protoctl_event_val = 0;
5197 flow->protoctl_event.protoctl_event_tcp_seq_num = 0;
5198 }
5199 }
5200 }
5201 if (!client_is_observed) {
5202 flow_registration->flow_result_read = TRUE;
5203 }
0a7de745 5204 return 0;
d9a64523
A
5205}
5206
39037602 5207static int
d9a64523 5208necp_client_copy_internal(struct necp_client *client, uuid_t client_id, bool client_is_observed, struct necp_client_action_args *uap, int *retval)
39037602 5209{
d9a64523 5210 NECP_CLIENT_ASSERT_LOCKED(client);
39037602
A
5211 int error = 0;
5212 // Copy results out
5213 if (uap->action == NECP_CLIENT_ACTION_COPY_PARAMETERS) {
5214 if (uap->buffer_size < client->parameters_length) {
0a7de745 5215 return EINVAL;
39037602
A
5216 }
5217 error = copyout(client->parameters, uap->buffer, client->parameters_length);
5218 if (error) {
5219 NECPLOG(LOG_ERR, "necp_client_copy parameters copyout error (%d)", error);
0a7de745 5220 return error;
39037602
A
5221 }
5222 *retval = client->parameters_length;
5ba3f43e 5223 } else if (uap->action == NECP_CLIENT_ACTION_COPY_UPDATED_RESULT &&
0a7de745 5224 client->result_read && !necp_client_has_unread_flows(client)) {
5ba3f43e
A
5225 // Copy updates only, but nothing to read
5226 // Just return 0 for bytes read
5227 *retval = 0;
5228 } else if (uap->action == NECP_CLIENT_ACTION_COPY_RESULT ||
0a7de745 5229 uap->action == NECP_CLIENT_ACTION_COPY_UPDATED_RESULT) {
5ba3f43e 5230 size_t assigned_results_size = 0;
5ba3f43e 5231
d9a64523
A
5232 bool some_flow_is_defunct = false;
5233 struct necp_client_flow_registration *single_flow_registration = NULL;
5234 if (necp_client_id_is_flow(client_id)) {
5235 single_flow_registration = necp_client_find_flow(client, client_id);
5236 if (single_flow_registration != NULL) {
5237 assigned_results_size += necp_client_calculate_flow_tlv_size(single_flow_registration);
5238 }
5239 } else {
5240 // This request is for the client, so copy everything
5241 struct necp_client_flow_registration *flow_registration = NULL;
5242 RB_FOREACH(flow_registration, _necp_client_flow_tree, &client->flow_registrations) {
5243 if (flow_registration->defunct) {
5244 some_flow_is_defunct = true;
5ba3f43e 5245 }
d9a64523 5246 assigned_results_size += necp_client_calculate_flow_tlv_size(flow_registration);
5ba3f43e
A
5247 }
5248 }
5249 if (uap->buffer_size < (client->result_length + assigned_results_size)) {
0a7de745 5250 return EINVAL;
d9a64523
A
5251 }
5252
5253 u_int32_t original_flags = 0;
5254 bool flags_updated = false;
5255 if (some_flow_is_defunct && client->legacy_client_is_flow) {
5256 // If our client expects the defunct flag in the client, add it now
5257 u_int32_t client_flags = 0;
5258 u_int32_t value_size = 0;
5259 u_int8_t *flags_pointer = necp_buffer_get_tlv_value(client->result, 0, &value_size);
5260 if (flags_pointer != NULL && value_size == sizeof(client_flags)) {
5261 memcpy(&client_flags, flags_pointer, value_size);
5262 original_flags = client_flags;
5263 client_flags |= NECP_CLIENT_RESULT_FLAG_DEFUNCT;
5264 (void)necp_buffer_write_tlv_if_different(client->result, NECP_CLIENT_RESULT_FLAGS,
0a7de745
A
5265 sizeof(client_flags), &client_flags, &flags_updated,
5266 client->result, sizeof(client->result));
d9a64523 5267 }
39037602 5268 }
d9a64523 5269
39037602 5270 error = copyout(client->result, uap->buffer, client->result_length);
d9a64523
A
5271
5272 if (flags_updated) {
5273 // Revert stored flags
5274 (void)necp_buffer_write_tlv_if_different(client->result, NECP_CLIENT_RESULT_FLAGS,
0a7de745
A
5275 sizeof(original_flags), &original_flags, &flags_updated,
5276 client->result, sizeof(client->result));
d9a64523
A
5277 }
5278
39037602
A
5279 if (error) {
5280 NECPLOG(LOG_ERR, "necp_client_copy result copyout error (%d)", error);
0a7de745 5281 return error;
39037602 5282 }
5ba3f43e
A
5283
5284 size_t assigned_results_cursor = 0;
d9a64523
A
5285 if (necp_client_id_is_flow(client_id)) {
5286 if (single_flow_registration != NULL) {
5287 error = necp_client_fillout_flow_tlvs(client, client_is_observed, single_flow_registration, uap, &assigned_results_cursor);
5288 if (error != 0) {
0a7de745 5289 return error;
5ba3f43e 5290 }
d9a64523
A
5291 }
5292 } else {
5293 // This request is for the client, so copy everything
5294 struct necp_client_flow_registration *flow_registration = NULL;
5295 RB_FOREACH(flow_registration, _necp_client_flow_tree, &client->flow_registrations) {
5296 error = necp_client_fillout_flow_tlvs(client, client_is_observed, flow_registration, uap, &assigned_results_cursor);
5297 if (error != 0) {
0a7de745 5298 return error;
5ba3f43e 5299 }
39037602 5300 }
39037602
A
5301 }
5302
5ba3f43e
A
5303 *retval = client->result_length + assigned_results_cursor;
5304
39037602
A
5305 if (!client_is_observed) {
5306 client->result_read = TRUE;
39037602
A
5307 }
5308 }
5309
0a7de745 5310 return 0;
39037602
A
5311}
5312
cb323159 5313static NECP_CLIENT_ACTION_FUNCTION int
39037602
A
5314necp_client_copy(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
5315{
5316 int error = 0;
39037602
A
5317 struct necp_client *client = NULL;
5318 uuid_t client_id;
5319 uuid_clear(client_id);
5320
5321 *retval = 0;
5322
5323 if (uap->buffer_size == 0 || uap->buffer == 0) {
0a7de745 5324 return EINVAL;
39037602
A
5325 }
5326
5327 if (uap->action != NECP_CLIENT_ACTION_COPY_PARAMETERS &&
0a7de745
A
5328 uap->action != NECP_CLIENT_ACTION_COPY_RESULT &&
5329 uap->action != NECP_CLIENT_ACTION_COPY_UPDATED_RESULT) {
5330 return EINVAL;
39037602
A
5331 }
5332
5333 if (uap->client_id) {
5334 if (uap->client_id_len != sizeof(uuid_t)) {
f427ee49 5335 NECPLOG(LOG_ERR, "Incorrect length (got %zu, expected %zu)", (size_t)uap->client_id_len, sizeof(uuid_t));
0a7de745 5336 return ERANGE;
39037602
A
5337 }
5338
5339 error = copyin(uap->client_id, client_id, sizeof(uuid_t));
5340 if (error) {
5341 NECPLOG(LOG_ERR, "necp_client_copy client_id copyin error (%d)", error);
0a7de745 5342 return error;
39037602
A
5343 }
5344 }
5345
a39ff7e2
A
5346 const bool is_wildcard = (bool)uuid_is_null(client_id);
5347
5ba3f43e 5348 NECP_FD_LOCK(fd_data);
a39ff7e2
A
5349
5350 if (is_wildcard) {
5351 if (uap->action == NECP_CLIENT_ACTION_COPY_RESULT || uap->action == NECP_CLIENT_ACTION_COPY_UPDATED_RESULT) {
5352 struct necp_client *find_client = NULL;
5353 RB_FOREACH(find_client, _necp_client_tree, &fd_data->clients) {
5354 NECP_CLIENT_LOCK(find_client);
d9a64523 5355 if (!find_client->result_read || necp_client_has_unread_flows(find_client)) {
a39ff7e2
A
5356 client = find_client;
5357 // Leave the client locked, and break
5358 break;
5359 }
5360 NECP_CLIENT_UNLOCK(find_client);
39037602 5361 }
39037602 5362 }
a39ff7e2
A
5363 } else {
5364 client = necp_client_fd_find_client_and_lock(fd_data, client_id);
39037602
A
5365 }
5366
5367 if (client != NULL) {
a39ff7e2 5368 // If client is set, it is locked
d9a64523 5369 error = necp_client_copy_internal(client, client_id, FALSE, uap, retval);
a39ff7e2 5370 NECP_CLIENT_UNLOCK(client);
39037602
A
5371 }
5372
a39ff7e2 5373 // Unlock our own fd before moving on or returning
5ba3f43e 5374 NECP_FD_UNLOCK(fd_data);
39037602
A
5375
5376 if (client == NULL) {
5377 if (fd_data->flags & NECP_OPEN_FLAG_OBSERVER) {
5378 // Observers are allowed to lookup clients on other fds
5379
5ba3f43e
A
5380 // Lock tree
5381 NECP_CLIENT_TREE_LOCK_SHARED();
39037602 5382
5ba3f43e 5383 bool found_client = FALSE;
39037602 5384
d9a64523 5385 client = necp_find_client_and_lock(client_id);
5ba3f43e 5386 if (client != NULL) {
5ba3f43e
A
5387 // Matched, copy out data
5388 found_client = TRUE;
d9a64523 5389 error = necp_client_copy_internal(client, client_id, TRUE, uap, retval);
5ba3f43e 5390 NECP_CLIENT_UNLOCK(client);
39037602
A
5391 }
5392
5ba3f43e
A
5393 // Unlock tree
5394 NECP_CLIENT_TREE_UNLOCK();
39037602
A
5395
5396 // No client found, fail
5ba3f43e 5397 if (!found_client) {
0a7de745 5398 return ENOENT;
39037602
A
5399 }
5400 } else {
5401 // No client found, and not allowed to search other fds, fail
0a7de745 5402 return ENOENT;
39037602
A
5403 }
5404 }
5405
0a7de745 5406 return error;
39037602
A
5407}
5408
cb323159 5409static NECP_CLIENT_ACTION_FUNCTION int
5ba3f43e
A
5410necp_client_copy_client_update(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
5411{
5412 int error = 0;
5413
5414 *retval = 0;
5415
5416 if (!(fd_data->flags & NECP_OPEN_FLAG_PUSH_OBSERVER)) {
5417 NECPLOG0(LOG_ERR, "NECP fd is not observer, cannot copy client update");
0a7de745 5418 return EINVAL;
5ba3f43e
A
5419 }
5420
5421 if (uap->client_id_len != sizeof(uuid_t) || uap->client_id == 0) {
5422 NECPLOG0(LOG_ERR, "Client id invalid, cannot copy client update");
0a7de745 5423 return EINVAL;
5ba3f43e
A
5424 }
5425
5426 if (uap->buffer_size == 0 || uap->buffer == 0) {
5427 NECPLOG0(LOG_ERR, "Buffer invalid, cannot copy client update");
0a7de745 5428 return EINVAL;
5ba3f43e
A
5429 }
5430
5431 NECP_FD_LOCK(fd_data);
5432 struct necp_client_update *client_update = TAILQ_FIRST(&fd_data->update_list);
5433 if (client_update != NULL) {
5434 TAILQ_REMOVE(&fd_data->update_list, client_update, chain);
5435 VERIFY(fd_data->update_count > 0);
5436 fd_data->update_count--;
5437 }
5438 NECP_FD_UNLOCK(fd_data);
5439
5440 if (client_update != NULL) {
5441 error = copyout(client_update->client_id, uap->client_id, sizeof(uuid_t));
5442 if (error) {
5443 NECPLOG(LOG_ERR, "Copy client update copyout client id error (%d)", error);
5444 } else {
5445 if (uap->buffer_size < client_update->update_length) {
f427ee49 5446 NECPLOG(LOG_ERR, "Buffer size cannot hold update (%zu < %zu)", (size_t)uap->buffer_size, client_update->update_length);
5ba3f43e
A
5447 error = EINVAL;
5448 } else {
5449 error = copyout(&client_update->update, uap->buffer, client_update->update_length);
5450 if (error) {
5451 NECPLOG(LOG_ERR, "Copy client update copyout error (%d)", error);
5452 } else {
5453 *retval = client_update->update_length;
5454 }
5455 }
5456 }
5457
5458 FREE(client_update, M_NECP);
5459 client_update = NULL;
5460 } else {
5461 error = ENOENT;
5462 }
5463
0a7de745 5464 return error;
5ba3f43e
A
5465}
5466
5467static int
d9a64523 5468necp_client_copy_parameters_locked(struct necp_client *client,
0a7de745 5469 struct necp_client_nexus_parameters *parameters)
5ba3f43e
A
5470{
5471 VERIFY(parameters != NULL);
5472
5473 struct necp_client_parsed_parameters parsed_parameters = {};
5474 int error = necp_client_parse_parameters(client->parameters, (u_int32_t)client->parameters_length, &parsed_parameters);
5475
5476 parameters->pid = client->proc_pid;
5477 if (parsed_parameters.valid_fields & NECP_PARSED_PARAMETERS_FIELD_EFFECTIVE_PID) {
5478 parameters->epid = parsed_parameters.effective_pid;
5479 } else {
5480 parameters->epid = parameters->pid;
5481 }
5482 memcpy(&parameters->local_addr, &parsed_parameters.local_addr, sizeof(parameters->local_addr));
5483 memcpy(&parameters->remote_addr, &parsed_parameters.remote_addr, sizeof(parameters->remote_addr));
5484 parameters->ip_protocol = parsed_parameters.ip_protocol;
cb323159
A
5485 if (parsed_parameters.valid_fields & NECP_PARSED_PARAMETERS_FIELD_TRANSPORT_PROTOCOL) {
5486 parameters->transport_protocol = parsed_parameters.transport_protocol;
5487 } else {
5488 parameters->transport_protocol = parsed_parameters.ip_protocol;
5489 }
5490 parameters->ethertype = parsed_parameters.ethertype;
5ba3f43e 5491 parameters->traffic_class = parsed_parameters.traffic_class;
ea3f0419
A
5492 if (uuid_is_null(client->override_euuid)) {
5493 uuid_copy(parameters->euuid, parsed_parameters.effective_uuid);
5494 } else {
5495 uuid_copy(parameters->euuid, client->override_euuid);
5496 }
5ba3f43e 5497 parameters->is_listener = (parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) ? 1 : 0;
cb323159
A
5498 parameters->is_interpose = (parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_INTERPOSE) ? 1 : 0;
5499 parameters->is_custom_ether = (parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_CUSTOM_ETHER) ? 1 : 0;
5ba3f43e
A
5500 parameters->policy_id = client->policy_id;
5501
5502 // parse client result flag
5503 u_int32_t client_result_flags = 0;
5504 u_int32_t value_size = 0;
5505 u_int8_t *flags_pointer = NULL;
5506 flags_pointer = necp_buffer_get_tlv_value(client->result, 0, &value_size);
5507 if (flags_pointer && value_size == sizeof(client_result_flags)) {
5508 memcpy(&client_result_flags, flags_pointer, value_size);
5509 }
5510 parameters->allow_qos_marking = (client_result_flags & NECP_CLIENT_RESULT_FLAG_ALLOW_QOS_MARKING) ? 1 : 0;
5511
cb323159
A
5512 if (parsed_parameters.valid_fields & NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR_PREFERENCE) {
5513 if (parsed_parameters.local_address_preference == NECP_CLIENT_PARAMETER_LOCAL_ADDRESS_PREFERENCE_DEFAULT) {
5514 parameters->override_address_selection = false;
5515 } else if (parsed_parameters.local_address_preference == NECP_CLIENT_PARAMETER_LOCAL_ADDRESS_PREFERENCE_TEMPORARY) {
5516 parameters->override_address_selection = true;
5517 parameters->use_stable_address = false;
5518 } else if (parsed_parameters.local_address_preference == NECP_CLIENT_PARAMETER_LOCAL_ADDRESS_PREFERENCE_STABLE) {
5519 parameters->override_address_selection = true;
5520 parameters->use_stable_address = true;
5521 }
5522 } else {
5523 parameters->override_address_selection = false;
5524 }
5525
0a7de745 5526 return error;
5ba3f43e
A
5527}
5528
cb323159 5529static NECP_CLIENT_ACTION_FUNCTION int
39037602
A
5530necp_client_list(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
5531{
5532 int error = 0;
5533 struct necp_client *find_client = NULL;
5534 uuid_t *list = NULL;
5535 u_int32_t requested_client_count = 0;
5536 u_int32_t client_count = 0;
5ba3f43e 5537 size_t copy_buffer_size = 0;
39037602
A
5538
5539 if (uap->buffer_size < sizeof(requested_client_count) || uap->buffer == 0) {
5540 error = EINVAL;
5541 goto done;
5542 }
5543
5544 if (!(fd_data->flags & NECP_OPEN_FLAG_OBSERVER)) {
5545 NECPLOG0(LOG_ERR, "Client does not hold necessary entitlement to list other NECP clients");
5546 error = EACCES;
5547 goto done;
5548 }
5549
5550 error = copyin(uap->buffer, &requested_client_count, sizeof(requested_client_count));
5551 if (error) {
5552 goto done;
5553 }
5554
5ba3f43e
A
5555 if (os_mul_overflow(sizeof(uuid_t), requested_client_count, &copy_buffer_size)) {
5556 error = ERANGE;
5557 goto done;
5558 }
5559
5560 if (uap->buffer_size - sizeof(requested_client_count) != copy_buffer_size) {
5561 error = EINVAL;
5562 goto done;
5563 }
5564
5565 if (copy_buffer_size > NECP_MAX_CLIENT_LIST_SIZE) {
39037602
A
5566 error = EINVAL;
5567 goto done;
5568 }
5569
5570 if (requested_client_count > 0) {
5ba3f43e 5571 if ((list = _MALLOC(copy_buffer_size, M_NECP, M_WAITOK | M_ZERO)) == NULL) {
39037602
A
5572 error = ENOMEM;
5573 goto done;
5574 }
5575 }
5576
5ba3f43e
A
5577 // Lock tree
5578 NECP_CLIENT_TREE_LOCK_SHARED();
5579
5580 find_client = NULL;
5581 RB_FOREACH(find_client, _necp_client_global_tree, &necp_client_global_tree) {
5582 NECP_CLIENT_LOCK(find_client);
5583 if (!uuid_is_null(find_client->client_id)) {
5584 if (client_count < requested_client_count) {
5585 uuid_copy(list[client_count], find_client->client_id);
39037602 5586 }
5ba3f43e 5587 client_count++;
39037602 5588 }
5ba3f43e 5589 NECP_CLIENT_UNLOCK(find_client);
39037602
A
5590 }
5591
5ba3f43e
A
5592 // Unlock tree
5593 NECP_CLIENT_TREE_UNLOCK();
39037602
A
5594
5595 error = copyout(&client_count, uap->buffer, sizeof(client_count));
5596 if (error) {
5597 NECPLOG(LOG_ERR, "necp_client_list buffer copyout error (%d)", error);
5598 goto done;
5599 }
5600
5601 if (requested_client_count > 0 &&
0a7de745
A
5602 client_count > 0 &&
5603 list != NULL) {
5ba3f43e 5604 error = copyout(list, uap->buffer + sizeof(client_count), copy_buffer_size);
39037602
A
5605 if (error) {
5606 NECPLOG(LOG_ERR, "necp_client_list client count copyout error (%d)", error);
5607 goto done;
5608 }
5609 }
5610done:
5611 if (list != NULL) {
5612 FREE(list, M_NECP);
5613 }
5614 *retval = error;
39037602 5615
0a7de745 5616 return error;
39037602
A
5617}
5618
f427ee49
A
5619static NECP_CLIENT_ACTION_FUNCTION int
5620necp_client_add_flow(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
5621{
5622 int error = 0;
5623 struct necp_client *client = NULL;
5624 uuid_t client_id;
5625 struct necp_client_nexus_parameters parameters = {};
5626 struct proc *proc = PROC_NULL;
5627 struct necp_client_add_flow *add_request = NULL;
5628 struct necp_client_add_flow *allocated_add_request = NULL;
5629 struct necp_client_add_flow_default default_add_request = {};
5630 const size_t buffer_size = uap->buffer_size;
5631
5632 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t)) {
5633 error = EINVAL;
5634 NECPLOG(LOG_ERR, "necp_client_add_flow invalid client_id (length %zu)", (size_t)uap->client_id_len);
5635 goto done;
5636 }
5637
5638 if (uap->buffer == 0 || buffer_size < sizeof(struct necp_client_add_flow)) {
5639 error = EINVAL;
5640 NECPLOG(LOG_ERR, "necp_client_add_flow invalid buffer (length %zu)", buffer_size);
5641 goto done;
5642 }
5643
5644 error = copyin(uap->client_id, client_id, sizeof(uuid_t));
5645 if (error) {
5646 NECPLOG(LOG_ERR, "necp_client_add_flow copyin client_id error (%d)", error);
5647 goto done;
5648 }
5649
5650 if (buffer_size <= sizeof(struct necp_client_add_flow_default)) {
5651 // Fits in default size
5652 error = copyin(uap->buffer, &default_add_request, buffer_size);
5653 if (error) {
5654 NECPLOG(LOG_ERR, "necp_client_add_flow copyin default_add_request error (%d)", error);
5655 goto done;
5656 }
5657
5658 add_request = (struct necp_client_add_flow *)&default_add_request;
5659 } else {
5660 allocated_add_request = _MALLOC(buffer_size, M_NECP, M_WAITOK | M_ZERO);
5661 if (allocated_add_request == NULL) {
5662 error = ENOMEM;
5663 goto done;
5664 }
5665
5666 error = copyin(uap->buffer, allocated_add_request, buffer_size);
5667 if (error) {
5668 NECPLOG(LOG_ERR, "necp_client_add_flow copyin default_add_request error (%d)", error);
5669 goto done;
5670 }
5671
5672 add_request = (struct necp_client_add_flow *)allocated_add_request;
5673 }
5674
5675 NECP_FD_LOCK(fd_data);
5676 pid_t pid = fd_data->proc_pid;
5677 proc = proc_find(pid);
5678 if (proc == PROC_NULL) {
5679 NECP_FD_UNLOCK(fd_data);
5680 NECPLOG(LOG_ERR, "necp_client_add_flow process not found for pid %d error (%d)", pid, error);
5681 error = ESRCH;
5682 goto done;
5683 }
5684
5685 client = necp_client_fd_find_client_and_lock(fd_data, client_id);
5686 if (client == NULL) {
5687 error = ENOENT;
5688 NECP_FD_UNLOCK(fd_data);
5689 goto done;
5690 }
5691
5692 // Using ADD_FLOW indicates that the client supports multiple flows per client
5693 client->legacy_client_is_flow = false;
5694
5695 necp_client_retain_locked(client);
5696 necp_client_copy_parameters_locked(client, &parameters);
5697
5698 struct necp_client_flow_registration *new_registration = necp_client_create_flow_registration(fd_data, client);
5699 if (new_registration == NULL) {
5700 error = ENOMEM;
5701 NECP_CLIENT_UNLOCK(client);
5702 NECP_FD_UNLOCK(fd_data);
5703 NECPLOG0(LOG_ERR, "Failed to allocate flow registration");
5704 goto done;
5705 }
5706
5707 new_registration->flags = add_request->flags;
5708
5709 // Copy new ID out to caller
5710 uuid_copy(add_request->registration_id, new_registration->registration_id);
5711
5712 // Copy override address
5713 if (add_request->flags & NECP_CLIENT_FLOW_FLAGS_OVERRIDE_ADDRESS) {
5714 size_t offset_of_address = (sizeof(struct necp_client_add_flow) +
5715 add_request->stats_request_count * sizeof(struct necp_client_flow_stats));
5716 if (buffer_size >= offset_of_address + sizeof(struct sockaddr_in)) {
5717 struct sockaddr *override_address = (struct sockaddr *)(((uint8_t *)add_request) + offset_of_address);
5718 if (buffer_size >= offset_of_address + override_address->sa_len &&
5719 override_address->sa_len <= sizeof(parameters.remote_addr)) {
5720 memcpy(&parameters.remote_addr, override_address, override_address->sa_len);
5721 }
5722 }
5723 }
5724
5725
5726 if (error == 0 &&
5727 (add_request->flags & NECP_CLIENT_FLOW_FLAGS_BROWSE ||
5728 add_request->flags & NECP_CLIENT_FLOW_FLAGS_RESOLVE)) {
5729 uint32_t interface_index = IFSCOPE_NONE;
5730 ifnet_head_lock_shared();
5731 struct ifnet *interface = NULL;
5732 TAILQ_FOREACH(interface, &ifnet_head, if_link) {
5733 ifnet_lock_shared(interface);
5734 if (interface->if_agentids != NULL) {
5735 for (u_int32_t i = 0; i < interface->if_agentcount; i++) {
5736 if (uuid_compare(interface->if_agentids[i], add_request->agent_uuid) == 0) {
5737 interface_index = interface->if_index;
5738 break;
5739 }
5740 }
5741 }
5742 ifnet_lock_done(interface);
5743 if (interface_index != IFSCOPE_NONE) {
5744 break;
5745 }
5746 }
5747 ifnet_head_done();
5748
5749 necp_client_add_nexus_flow_if_needed(new_registration, add_request->agent_uuid, interface_index);
5750
5751 error = netagent_client_message_with_params(add_request->agent_uuid,
5752 ((new_registration->flags & NECP_CLIENT_FLOW_FLAGS_USE_CLIENT_ID) ?
5753 client->client_id :
5754 new_registration->registration_id),
5755 pid, client->agent_handle,
5756 NETAGENT_MESSAGE_TYPE_CLIENT_ASSERT,
5757 (struct necp_client_agent_parameters *)&parameters,
5758 NULL, NULL);
5759 if (error != 0) {
5760 NECPLOG(LOG_ERR, "netagent_client_message error (%d)", error);
5761 }
5762 }
5763
5764 if (error != 0) {
5765 // Encountered an error in adding the flow, destroy the flow registration
5766 NECP_FLOW_TREE_LOCK_EXCLUSIVE();
5767 RB_REMOVE(_necp_client_flow_global_tree, &necp_client_flow_global_tree, new_registration);
5768 NECP_FLOW_TREE_UNLOCK();
5769 RB_REMOVE(_necp_fd_flow_tree, &fd_data->flows, new_registration);
5770 necp_destroy_client_flow_registration(client, new_registration, fd_data->proc_pid, true);
5771 new_registration = NULL;
5772 }
5773
5774 NECP_CLIENT_UNLOCK(client);
5775 NECP_FD_UNLOCK(fd_data);
5776
5777 necp_client_release(client);
5778
5779 if (error != 0) {
5780 goto done;
5781 }
5782
5783 // Copy the request back out to the caller with assigned fields
5784 error = copyout(add_request, uap->buffer, buffer_size);
5785 if (error != 0) {
5786 NECPLOG(LOG_ERR, "necp_client_add_flow copyout add_request error (%d)", error);
5787 }
5788
5789done:
5790 *retval = error;
5791 if (error != 0) {
5792 NECPLOG(LOG_ERR, "Add flow error (%d)", error);
5793 }
5794
5795 if (allocated_add_request != NULL) {
5796 FREE(allocated_add_request, M_NECP);
5797 }
5798
5799 if (proc != PROC_NULL) {
5800 proc_rele(proc);
5801 }
5802 return error;
5803}
5804
5ba3f43e 5805
39037602
A
5806static void
5807necp_client_add_assertion(struct necp_client *client, uuid_t netagent_uuid)
5808{
5809 struct necp_client_assertion *new_assertion = NULL;
5810
5811 MALLOC(new_assertion, struct necp_client_assertion *, sizeof(*new_assertion), M_NECP, M_WAITOK);
5812 if (new_assertion == NULL) {
5813 NECPLOG0(LOG_ERR, "Failed to allocate assertion");
5814 return;
5815 }
5816
5817 uuid_copy(new_assertion->asserted_netagent, netagent_uuid);
5818
5819 LIST_INSERT_HEAD(&client->assertion_list, new_assertion, assertion_chain);
5820}
5821
5822static bool
5823necp_client_remove_assertion(struct necp_client *client, uuid_t netagent_uuid)
5824{
5825 struct necp_client_assertion *found_assertion = NULL;
5826 struct necp_client_assertion *search_assertion = NULL;
5827 LIST_FOREACH(search_assertion, &client->assertion_list, assertion_chain) {
5828 if (uuid_compare(search_assertion->asserted_netagent, netagent_uuid) == 0) {
5829 found_assertion = search_assertion;
5830 break;
5831 }
5832 }
5833
5834 if (found_assertion == NULL) {
5835 NECPLOG0(LOG_ERR, "Netagent uuid not previously asserted");
5836 return false;
5837 }
5838
5839 LIST_REMOVE(found_assertion, assertion_chain);
5840 FREE(found_assertion, M_NECP);
5841 return true;
5842}
5843
cb323159 5844static NECP_CLIENT_ACTION_FUNCTION int
39037602
A
5845necp_client_agent_action(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
5846{
5847 int error = 0;
39037602
A
5848 struct necp_client *client = NULL;
5849 uuid_t client_id;
5850 bool acted_on_agent = FALSE;
5851 u_int8_t *parameters = NULL;
f427ee49 5852 const size_t buffer_size = uap->buffer_size;
39037602
A
5853
5854 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t) ||
f427ee49 5855 buffer_size == 0 || uap->buffer == 0) {
a39ff7e2 5856 NECPLOG0(LOG_ERR, "necp_client_agent_action invalid parameters");
39037602
A
5857 error = EINVAL;
5858 goto done;
5859 }
5860
5861 error = copyin(uap->client_id, client_id, sizeof(uuid_t));
5862 if (error) {
5863 NECPLOG(LOG_ERR, "necp_client_agent_action copyin client_id error (%d)", error);
5864 goto done;
5865 }
5866
f427ee49 5867 if (buffer_size > NECP_MAX_AGENT_ACTION_SIZE) {
9d749ea3
A
5868 NECPLOG(LOG_ERR, "necp_client_agent_action invalid buffer size (>%u)", NECP_MAX_AGENT_ACTION_SIZE);
5869 error = EINVAL;
5870 goto done;
5871 }
5872
f427ee49 5873 if ((parameters = _MALLOC(buffer_size, M_NECP, M_WAITOK | M_ZERO)) == NULL) {
a39ff7e2 5874 NECPLOG0(LOG_ERR, "necp_client_agent_action malloc failed");
39037602
A
5875 error = ENOMEM;
5876 goto done;
5877 }
5878
f427ee49 5879 error = copyin(uap->buffer, parameters, buffer_size);
39037602
A
5880 if (error) {
5881 NECPLOG(LOG_ERR, "necp_client_agent_action parameters copyin error (%d)", error);
5882 goto done;
5883 }
5884
5ba3f43e
A
5885 NECP_FD_LOCK(fd_data);
5886 client = necp_client_fd_find_client_and_lock(fd_data, client_id);
5887 if (client != NULL) {
39037602 5888 size_t offset = 0;
f427ee49 5889 while ((offset + sizeof(struct necp_tlv_header)) <= buffer_size) {
39037602
A
5890 u_int8_t type = necp_buffer_get_tlv_type(parameters, offset);
5891 u_int32_t length = necp_buffer_get_tlv_length(parameters, offset);
5892
f427ee49 5893 if (length > (buffer_size - (offset + sizeof(struct necp_tlv_header)))) {
813fb2f6
A
5894 // If the length is larger than what can fit in the remaining parameters size, bail
5895 NECPLOG(LOG_ERR, "Invalid TLV length (%u)", length);
5896 break;
5897 }
5898
5899 if (length > 0) {
39037602
A
5900 u_int8_t *value = necp_buffer_get_tlv_value(parameters, offset, NULL);
5901 if (length >= sizeof(uuid_t) &&
0a7de745
A
5902 value != NULL &&
5903 (type == NECP_CLIENT_PARAMETER_TRIGGER_AGENT ||
5904 type == NECP_CLIENT_PARAMETER_ASSERT_AGENT ||
5905 type == NECP_CLIENT_PARAMETER_UNASSERT_AGENT)) {
5906 uuid_t agent_uuid;
5907 uuid_copy(agent_uuid, value);
5908 u_int8_t netagent_message_type = 0;
5909 if (type == NECP_CLIENT_PARAMETER_TRIGGER_AGENT) {
5910 netagent_message_type = NETAGENT_MESSAGE_TYPE_CLIENT_TRIGGER;
5911 } else if (type == NECP_CLIENT_PARAMETER_ASSERT_AGENT) {
5912 netagent_message_type = NETAGENT_MESSAGE_TYPE_CLIENT_ASSERT;
5913 } else if (type == NECP_CLIENT_PARAMETER_UNASSERT_AGENT) {
5914 netagent_message_type = NETAGENT_MESSAGE_TYPE_CLIENT_UNASSERT;
5915 }
39037602 5916
0a7de745
A
5917 // Before unasserting, verify that the assertion was already taken
5918 if (type == NECP_CLIENT_PARAMETER_UNASSERT_AGENT) {
5919 if (!necp_client_remove_assertion(client, agent_uuid)) {
5920 error = ENOENT;
39037602
A
5921 break;
5922 }
0a7de745 5923 }
39037602 5924
0a7de745
A
5925 struct necp_client_nexus_parameters parsed_parameters = {};
5926 necp_client_copy_parameters_locked(client, &parsed_parameters);
5927
5928 error = netagent_client_message_with_params(agent_uuid,
5929 client_id,
5930 fd_data->proc_pid,
5931 client->agent_handle,
5932 netagent_message_type,
cb323159 5933 (struct necp_client_agent_parameters *)&parsed_parameters,
0a7de745
A
5934 NULL, NULL);
5935 if (error == 0) {
5936 acted_on_agent = TRUE;
5937 } else {
5938 break;
5939 }
5940
5941 // Only save the assertion if the action succeeded
5942 if (type == NECP_CLIENT_PARAMETER_ASSERT_AGENT) {
5943 necp_client_add_assertion(client, agent_uuid);
39037602 5944 }
0a7de745 5945 }
39037602
A
5946 }
5947
5ba3f43e 5948 offset += sizeof(struct necp_tlv_header) + length;
39037602 5949 }
5ba3f43e
A
5950
5951 NECP_CLIENT_UNLOCK(client);
39037602 5952 }
5ba3f43e 5953 NECP_FD_UNLOCK(fd_data);
39037602
A
5954
5955 if (!acted_on_agent &&
0a7de745 5956 error == 0) {
39037602
A
5957 error = ENOENT;
5958 }
5959done:
5960 *retval = error;
5961 if (parameters != NULL) {
5962 FREE(parameters, M_NECP);
5963 parameters = NULL;
5964 }
5ba3f43e 5965
0a7de745 5966 return error;
39037602
A
5967}
5968
cb323159 5969static NECP_CLIENT_ACTION_FUNCTION int
39037602
A
5970necp_client_copy_agent(__unused struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
5971{
5972 int error = 0;
5973 uuid_t agent_uuid;
f427ee49 5974 const size_t buffer_size = uap->buffer_size;
39037602
A
5975
5976 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t) ||
f427ee49 5977 buffer_size == 0 || uap->buffer == 0) {
39037602
A
5978 NECPLOG0(LOG_ERR, "necp_client_copy_agent bad input");
5979 error = EINVAL;
5980 goto done;
5981 }
5982
5983 error = copyin(uap->client_id, agent_uuid, sizeof(uuid_t));
5984 if (error) {
5985 NECPLOG(LOG_ERR, "necp_client_copy_agent copyin agent_uuid error (%d)", error);
5986 goto done;
5987 }
5988
f427ee49 5989 error = netagent_copyout(agent_uuid, uap->buffer, buffer_size);
39037602 5990 if (error) {
5ba3f43e 5991 // netagent_copyout already logs appropriate errors
39037602
A
5992 goto done;
5993 }
5994done:
5995 *retval = error;
5ba3f43e 5996
0a7de745 5997 return error;
39037602
A
5998}
5999
cb323159 6000static NECP_CLIENT_ACTION_FUNCTION int
813fb2f6
A
6001necp_client_agent_use(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
6002{
6003 int error = 0;
813fb2f6
A
6004 struct necp_client *client = NULL;
6005 uuid_t client_id;
f427ee49
A
6006 struct necp_agent_use_parameters parameters = {};
6007 const size_t buffer_size = uap->buffer_size;
813fb2f6
A
6008
6009 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t) ||
f427ee49 6010 buffer_size != sizeof(parameters) || uap->buffer == 0) {
813fb2f6
A
6011 error = EINVAL;
6012 goto done;
6013 }
6014
6015 error = copyin(uap->client_id, client_id, sizeof(uuid_t));
6016 if (error) {
6017 NECPLOG(LOG_ERR, "Copyin client_id error (%d)", error);
6018 goto done;
6019 }
6020
f427ee49 6021 error = copyin(uap->buffer, &parameters, buffer_size);
813fb2f6
A
6022 if (error) {
6023 NECPLOG(LOG_ERR, "Parameters copyin error (%d)", error);
6024 goto done;
6025 }
6026
5ba3f43e
A
6027 NECP_FD_LOCK(fd_data);
6028 client = necp_client_fd_find_client_and_lock(fd_data, client_id);
6029 if (client != NULL) {
813fb2f6 6030 error = netagent_use(parameters.agent_uuid, &parameters.out_use_count);
5ba3f43e 6031 NECP_CLIENT_UNLOCK(client);
813fb2f6
A
6032 } else {
6033 error = ENOENT;
6034 }
6035
5ba3f43e 6036 NECP_FD_UNLOCK(fd_data);
813fb2f6
A
6037
6038 if (error == 0) {
f427ee49 6039 error = copyout(&parameters, uap->buffer, buffer_size);
813fb2f6
A
6040 if (error) {
6041 NECPLOG(LOG_ERR, "Parameters copyout error (%d)", error);
6042 goto done;
6043 }
6044 }
6045
6046done:
6047 *retval = error;
6048
0a7de745 6049 return error;
813fb2f6
A
6050}
6051
cb323159 6052static NECP_CLIENT_ACTION_FUNCTION int
39037602
A
6053necp_client_copy_interface(__unused struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
6054{
6055 int error = 0;
6056 u_int32_t interface_index = 0;
cb323159 6057 struct necp_interface_details interface_details = {};
39037602
A
6058
6059 if (uap->client_id == 0 || uap->client_id_len != sizeof(u_int32_t) ||
f427ee49 6060 uap->buffer_size < sizeof(interface_details) ||
cb323159 6061 uap->buffer == 0) {
39037602
A
6062 NECPLOG0(LOG_ERR, "necp_client_copy_interface bad input");
6063 error = EINVAL;
6064 goto done;
6065 }
6066
6067 error = copyin(uap->client_id, &interface_index, sizeof(u_int32_t));
6068 if (error) {
6069 NECPLOG(LOG_ERR, "necp_client_copy_interface copyin interface_index error (%d)", error);
6070 goto done;
6071 }
6072
6073 if (interface_index == 0) {
6074 error = ENOENT;
6075 NECPLOG(LOG_ERR, "necp_client_copy_interface bad interface_index (%d)", interface_index);
6076 goto done;
6077 }
6078
f427ee49 6079 lck_mtx_lock(rnh_lock);
39037602
A
6080 ifnet_head_lock_shared();
6081 ifnet_t interface = NULL;
813fb2f6 6082 if (interface_index != IFSCOPE_NONE && interface_index <= (u_int32_t)if_index) {
39037602
A
6083 interface = ifindex2ifnet[interface_index];
6084 }
6085
6086 if (interface != NULL) {
6087 if (interface->if_xname != NULL) {
6088 strlcpy((char *)&interface_details.name, interface->if_xname, sizeof(interface_details.name));
6089 }
6090 interface_details.index = interface->if_index;
6091 interface_details.generation = ifnet_get_generation(interface);
6092 if (interface->if_delegated.ifp != NULL) {
6093 interface_details.delegate_index = interface->if_delegated.ifp->if_index;
6094 }
6095 interface_details.functional_type = if_functional_type(interface, TRUE);
6096 if (IFNET_IS_EXPENSIVE(interface)) {
6097 interface_details.flags |= NECP_INTERFACE_FLAG_EXPENSIVE;
6098 }
cb323159
A
6099 if (IFNET_IS_CONSTRAINED(interface)) {
6100 interface_details.flags |= NECP_INTERFACE_FLAG_CONSTRAINED;
6101 }
5ba3f43e
A
6102 if ((interface->if_eflags & IFEF_TXSTART) == IFEF_TXSTART) {
6103 interface_details.flags |= NECP_INTERFACE_FLAG_TXSTART;
6104 }
6105 if ((interface->if_eflags & IFEF_NOACKPRI) == IFEF_NOACKPRI) {
6106 interface_details.flags |= NECP_INTERFACE_FLAG_NOACKPRI;
6107 }
d9a64523
A
6108 if ((interface->if_eflags & IFEF_3CA) == IFEF_3CA) {
6109 interface_details.flags |= NECP_INTERFACE_FLAG_3CARRIERAGG;
6110 }
6111 if (IFNET_IS_LOW_POWER(interface)) {
6112 interface_details.flags |= NECP_INTERFACE_FLAG_IS_LOW_POWER;
6113 }
cb323159
A
6114 if (interface->if_xflags & IFXF_MPK_LOG) {
6115 interface_details.flags |= NECP_INTERFACE_FLAG_MPK_LOG;
6116 }
f427ee49
A
6117 if (interface->if_flags & IFF_MULTICAST) {
6118 interface_details.flags |= NECP_INTERFACE_FLAG_SUPPORTS_MULTICAST;
6119 }
6120 if (IS_INTF_CLAT46(interface)) {
6121 interface_details.flags |= NECP_INTERFACE_FLAG_HAS_NAT64;
6122 }
39037602
A
6123 interface_details.mtu = interface->if_mtu;
6124
5ba3f43e 6125 u_int8_t ipv4_signature_len = sizeof(interface_details.ipv4_signature.signature);
39037602 6126 u_int16_t ipv4_signature_flags;
5ba3f43e 6127 if (ifnet_get_netsignature(interface, AF_INET, &ipv4_signature_len, &ipv4_signature_flags,
0a7de745 6128 (u_int8_t *)&interface_details.ipv4_signature) != 0) {
5ba3f43e
A
6129 ipv4_signature_len = 0;
6130 }
6131 interface_details.ipv4_signature.signature_len = ipv4_signature_len;
39037602 6132
f427ee49
A
6133 // Check for default scoped routes for IPv4 and IPv6
6134 union necp_sockaddr_union default_address;
6135 struct rtentry *v4Route = NULL;
6136 memset(&default_address, 0, sizeof(default_address));
6137 default_address.sa.sa_family = AF_INET;
6138 default_address.sa.sa_len = sizeof(struct sockaddr_in);
6139 v4Route = rtalloc1_scoped_locked((struct sockaddr *)&default_address, 0, 0,
6140 interface->if_index);
6141 if (v4Route != NULL) {
6142 if (v4Route->rt_ifp != NULL && !IS_INTF_CLAT46(v4Route->rt_ifp)) {
6143 interface_details.flags |= NECP_INTERFACE_FLAG_IPV4_ROUTABLE;
6144 }
6145 rtfree_locked(v4Route);
6146 v4Route = NULL;
6147 }
6148
6149 struct rtentry *v6Route = NULL;
6150 memset(&default_address, 0, sizeof(default_address));
6151 default_address.sa.sa_family = AF_INET6;
6152 default_address.sa.sa_len = sizeof(struct sockaddr_in6);
6153 v6Route = rtalloc1_scoped_locked((struct sockaddr *)&default_address, 0, 0,
6154 interface->if_index);
6155 if (v6Route != NULL) {
6156 if (v6Route->rt_ifp != NULL) {
6157 interface_details.flags |= NECP_INTERFACE_FLAG_IPV6_ROUTABLE;
6158 }
6159 rtfree_locked(v6Route);
6160 v6Route = NULL;
6161 }
6162
5ba3f43e 6163 u_int8_t ipv6_signature_len = sizeof(interface_details.ipv6_signature.signature);
39037602 6164 u_int16_t ipv6_signature_flags;
5ba3f43e 6165 if (ifnet_get_netsignature(interface, AF_INET6, &ipv6_signature_len, &ipv6_signature_flags,
0a7de745 6166 (u_int8_t *)&interface_details.ipv6_signature) != 0) {
5ba3f43e
A
6167 ipv6_signature_len = 0;
6168 }
6169 interface_details.ipv6_signature.signature_len = ipv6_signature_len;
cb323159
A
6170
6171 ifnet_lock_shared(interface);
6172 struct ifaddr *ifa = NULL;
6173 TAILQ_FOREACH(ifa, &interface->if_addrhead, ifa_link) {
6174 IFA_LOCK(ifa);
6175 if (ifa->ifa_addr->sa_family == AF_INET) {
6176 interface_details.flags |= NECP_INTERFACE_FLAG_HAS_NETMASK;
6177 interface_details.ipv4_netmask = ((struct in_ifaddr *)ifa)->ia_sockmask.sin_addr.s_addr;
6178 if (interface->if_flags & IFF_BROADCAST) {
6179 interface_details.flags |= NECP_INTERFACE_FLAG_HAS_BROADCAST;
6180 interface_details.ipv4_broadcast = ((struct in_ifaddr *)ifa)->ia_broadaddr.sin_addr.s_addr;
6181 }
6182 }
6183 IFA_UNLOCK(ifa);
6184 }
6185 ifnet_lock_done(interface);
39037602
A
6186 }
6187
6188 ifnet_head_done();
f427ee49 6189 lck_mtx_unlock(rnh_lock);
39037602 6190
cb323159 6191 // If the client is using an older version of the struct, copy that length
f427ee49 6192 error = copyout(&interface_details, uap->buffer, sizeof(interface_details));
39037602
A
6193 if (error) {
6194 NECPLOG(LOG_ERR, "necp_client_copy_interface copyout error (%d)", error);
6195 goto done;
6196 }
6197done:
6198 *retval = error;
6199
0a7de745 6200 return error;
39037602
A
6201}
6202
5ba3f43e 6203
cb323159 6204static NECP_CLIENT_ACTION_FUNCTION int
5ba3f43e 6205necp_client_copy_route_statistics(__unused struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
39037602
A
6206{
6207 int error = 0;
5ba3f43e
A
6208 struct necp_client *client = NULL;
6209 uuid_t client_id;
39037602 6210
5ba3f43e 6211 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t) ||
0a7de745 6212 uap->buffer_size < sizeof(struct necp_stat_counts) || uap->buffer == 0) {
5ba3f43e 6213 NECPLOG0(LOG_ERR, "necp_client_copy_route_statistics bad input");
39037602
A
6214 error = EINVAL;
6215 goto done;
6216 }
6217
5ba3f43e 6218 error = copyin(uap->client_id, client_id, sizeof(uuid_t));
39037602 6219 if (error) {
5ba3f43e 6220 NECPLOG(LOG_ERR, "necp_client_copy_route_statistics copyin client_id error (%d)", error);
39037602
A
6221 goto done;
6222 }
6223
5ba3f43e
A
6224 // Lock
6225 NECP_FD_LOCK(fd_data);
6226 client = necp_client_fd_find_client_and_lock(fd_data, client_id);
6227 if (client != NULL) {
6228 NECP_CLIENT_ROUTE_LOCK(client);
a39ff7e2 6229 struct necp_stat_counts route_stats = {};
5ba3f43e 6230 if (client->current_route != NULL && client->current_route->rt_stats != NULL) {
0a7de745 6231 struct nstat_counts *rt_stats = client->current_route->rt_stats;
a39ff7e2
A
6232 atomic_get_64(route_stats.necp_stat_rxpackets, &rt_stats->nstat_rxpackets);
6233 atomic_get_64(route_stats.necp_stat_rxbytes, &rt_stats->nstat_rxbytes);
6234 atomic_get_64(route_stats.necp_stat_txpackets, &rt_stats->nstat_txpackets);
6235 atomic_get_64(route_stats.necp_stat_txbytes, &rt_stats->nstat_txbytes);
6236 route_stats.necp_stat_rxduplicatebytes = rt_stats->nstat_rxduplicatebytes;
6237 route_stats.necp_stat_rxoutoforderbytes = rt_stats->nstat_rxoutoforderbytes;
6238 route_stats.necp_stat_txretransmit = rt_stats->nstat_txretransmit;
6239 route_stats.necp_stat_connectattempts = rt_stats->nstat_connectattempts;
6240 route_stats.necp_stat_connectsuccesses = rt_stats->nstat_connectsuccesses;
6241 route_stats.necp_stat_min_rtt = rt_stats->nstat_min_rtt;
6242 route_stats.necp_stat_avg_rtt = rt_stats->nstat_avg_rtt;
6243 route_stats.necp_stat_var_rtt = rt_stats->nstat_var_rtt;
6244 route_stats.necp_stat_route_flags = client->current_route->rt_flags;
39037602 6245 }
5ba3f43e
A
6246
6247 // Unlock before copying out
6248 NECP_CLIENT_ROUTE_UNLOCK(client);
6249 NECP_CLIENT_UNLOCK(client);
6250 NECP_FD_UNLOCK(fd_data);
6251
6252 error = copyout(&route_stats, uap->buffer, sizeof(route_stats));
6253 if (error) {
6254 NECPLOG(LOG_ERR, "necp_client_copy_route_statistics copyout error (%d)", error);
39037602 6255 }
5ba3f43e
A
6256 } else {
6257 // Unlock
6258 NECP_FD_UNLOCK(fd_data);
6259 error = ENOENT;
39037602 6260 }
39037602 6261
5ba3f43e
A
6262
6263done:
6264 *retval = error;
0a7de745 6265 return error;
39037602
A
6266}
6267
cb323159 6268static NECP_CLIENT_ACTION_FUNCTION int
5ba3f43e 6269necp_client_update_cache(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
39037602
A
6270{
6271 int error = 0;
39037602
A
6272 struct necp_client *client = NULL;
6273 uuid_t client_id;
6274
6275 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t)) {
6276 error = EINVAL;
6277 goto done;
6278 }
6279
6280 error = copyin(uap->client_id, client_id, sizeof(uuid_t));
6281 if (error) {
5ba3f43e 6282 NECPLOG(LOG_ERR, "necp_client_update_cache copyin client_id error (%d)", error);
39037602
A
6283 goto done;
6284 }
6285
5ba3f43e
A
6286 NECP_FD_LOCK(fd_data);
6287 client = necp_client_fd_find_client_and_lock(fd_data, client_id);
6288 if (client == NULL) {
6289 NECP_FD_UNLOCK(fd_data);
6290 error = ENOENT;
6291 goto done;
6292 }
6293
d9a64523
A
6294 struct necp_client_flow_registration *flow_registration = necp_client_find_flow(client, client_id);
6295 if (flow_registration == NULL) {
6296 NECP_CLIENT_UNLOCK(client);
6297 NECP_FD_UNLOCK(fd_data);
6298 error = ENOENT;
6299 goto done;
6300 }
6301
5ba3f43e
A
6302 NECP_CLIENT_ROUTE_LOCK(client);
6303 // This needs to be changed when TFO/ECN is supported by multiple flows
d9a64523 6304 struct necp_client_flow *flow = LIST_FIRST(&flow_registration->flow_list);
5ba3f43e 6305 if (flow == NULL ||
0a7de745
A
6306 (flow->remote_addr.sa.sa_family != AF_INET &&
6307 flow->remote_addr.sa.sa_family != AF_INET6) ||
6308 (flow->local_addr.sa.sa_family != AF_INET &&
6309 flow->local_addr.sa.sa_family != AF_INET6)) {
5ba3f43e
A
6310 error = EINVAL;
6311 NECPLOG(LOG_ERR, "necp_client_update_cache no flow error (%d)", error);
6312 goto done_unlock;
6313 }
6314
6315 necp_cache_buffer cache_buffer;
6316 memset(&cache_buffer, 0, sizeof(cache_buffer));
6317
6318 if (uap->buffer_size != sizeof(necp_cache_buffer) ||
0a7de745 6319 uap->buffer == USER_ADDR_NULL) {
5ba3f43e
A
6320 error = EINVAL;
6321 goto done_unlock;
39037602
A
6322 }
6323
5ba3f43e
A
6324 error = copyin(uap->buffer, &cache_buffer, sizeof(cache_buffer));
6325 if (error) {
6326 NECPLOG(LOG_ERR, "necp_client_update_cache copyin cache buffer error (%d)", error);
6327 goto done_unlock;
6328 }
6329
6330 if (cache_buffer.necp_cache_buf_type == NECP_CLIENT_CACHE_TYPE_ECN &&
6331 cache_buffer.necp_cache_buf_ver == NECP_CLIENT_CACHE_TYPE_ECN_VER_1) {
6332 if (cache_buffer.necp_cache_buf_size != sizeof(necp_tcp_ecn_cache) ||
6333 cache_buffer.necp_cache_buf_addr == USER_ADDR_NULL) {
6334 error = EINVAL;
6335 goto done_unlock;
6336 }
6337
6338 necp_tcp_ecn_cache ecn_cache_buffer;
6339 memset(&ecn_cache_buffer, 0, sizeof(ecn_cache_buffer));
6340
6341 error = copyin(cache_buffer.necp_cache_buf_addr, &ecn_cache_buffer, sizeof(necp_tcp_ecn_cache));
6342 if (error) {
6343 NECPLOG(LOG_ERR, "necp_client_update_cache copyin ecn cache buffer error (%d)", error);
6344 goto done_unlock;
6345 }
6346
6347 if (client->current_route != NULL && client->current_route->rt_ifp != NULL) {
6348 if (!client->platform_binary) {
0a7de745 6349 ecn_cache_buffer.necp_tcp_ecn_heuristics_success = 0;
5ba3f43e
A
6350 }
6351 tcp_heuristics_ecn_update(&ecn_cache_buffer, client->current_route->rt_ifp,
0a7de745 6352 (union sockaddr_in_4_6 *)&flow->local_addr);
5ba3f43e
A
6353 }
6354 } else if (cache_buffer.necp_cache_buf_type == NECP_CLIENT_CACHE_TYPE_TFO &&
0a7de745 6355 cache_buffer.necp_cache_buf_ver == NECP_CLIENT_CACHE_TYPE_TFO_VER_1) {
5ba3f43e
A
6356 if (cache_buffer.necp_cache_buf_size != sizeof(necp_tcp_tfo_cache) ||
6357 cache_buffer.necp_cache_buf_addr == USER_ADDR_NULL) {
6358 error = EINVAL;
6359 goto done_unlock;
6360 }
6361
6362 necp_tcp_tfo_cache tfo_cache_buffer;
6363 memset(&tfo_cache_buffer, 0, sizeof(tfo_cache_buffer));
6364
6365 error = copyin(cache_buffer.necp_cache_buf_addr, &tfo_cache_buffer, sizeof(necp_tcp_tfo_cache));
6366 if (error) {
6367 NECPLOG(LOG_ERR, "necp_client_update_cache copyin tfo cache buffer error (%d)", error);
6368 goto done_unlock;
6369 }
6370
6371 if (client->current_route != NULL && client->current_route->rt_ifp != NULL) {
6372 if (!client->platform_binary) {
0a7de745 6373 tfo_cache_buffer.necp_tcp_tfo_heuristics_success = 0;
5ba3f43e
A
6374 }
6375 tcp_heuristics_tfo_update(&tfo_cache_buffer, client->current_route->rt_ifp,
0a7de745
A
6376 (union sockaddr_in_4_6 *)&flow->local_addr,
6377 (union sockaddr_in_4_6 *)&flow->remote_addr);
5ba3f43e 6378 }
39037602 6379 } else {
0a7de745 6380 error = EINVAL;
39037602 6381 }
5ba3f43e
A
6382done_unlock:
6383 NECP_CLIENT_ROUTE_UNLOCK(client);
6384 NECP_CLIENT_UNLOCK(client);
6385 NECP_FD_UNLOCK(fd_data);
39037602
A
6386done:
6387 *retval = error;
0a7de745 6388 return error;
39037602
A
6389}
6390
cb323159
A
6391#define NECP_CLIENT_ACTION_SIGN_DEFAULT_HOSTNAME_LENGTH 64
6392#define NECP_CLIENT_ACTION_SIGN_MAX_HOSTNAME_LENGTH 1024
6393
6394#define NECP_CLIENT_ACTION_SIGN_TAG_LENGTH 32
6395
6396static NECP_CLIENT_ACTION_FUNCTION int
6397necp_client_sign(__unused struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
6398{
6399 int error = 0;
6400 u_int32_t hostname_length = 0;
6401 u_int8_t tag[NECP_CLIENT_ACTION_SIGN_TAG_LENGTH] = {};
6402 struct necp_client_signable signable = {};
6403 union necp_sockaddr_union address_answer = {};
6404 u_int8_t *client_hostname = NULL;
6405 u_int8_t *allocated_hostname = NULL;
6406 u_int8_t default_hostname[NECP_CLIENT_ACTION_SIGN_DEFAULT_HOSTNAME_LENGTH] = "";
6407 uint32_t tag_size = sizeof(tag);
6408
6409 *retval = 0;
6410
6411 const bool has_resolver_entitlement = (priv_check_cred(kauth_cred_get(), PRIV_NET_VALIDATED_RESOLVER, 0) == 0);
6412 if (!has_resolver_entitlement) {
6413 NECPLOG0(LOG_ERR, "Process does not hold the necessary entitlement to sign resolver answers");
6414 error = EPERM;
6415 goto done;
6416 }
6417
6418 if (uap->client_id == 0 || uap->client_id_len < sizeof(struct necp_client_signable)) {
6419 error = EINVAL;
6420 goto done;
6421 }
6422
6423 if (uap->buffer == 0 || uap->buffer_size != NECP_CLIENT_ACTION_SIGN_TAG_LENGTH) {
6424 error = EINVAL;
6425 goto done;
6426 }
6427
6428 error = copyin(uap->client_id, &signable, sizeof(signable));
6429 if (error) {
6430 NECPLOG(LOG_ERR, "necp_client_sign copyin signable error (%d)", error);
6431 goto done;
6432 }
6433
6434 if (signable.sign_type != NECP_CLIENT_SIGN_TYPE_RESOLVER_ANSWER) {
6435 NECPLOG(LOG_ERR, "necp_client_sign unknown signable type (%u)", signable.sign_type);
6436 error = EINVAL;
6437 goto done;
6438 }
6439
6440 if (uap->client_id_len < sizeof(struct necp_client_resolver_answer)) {
6441 error = EINVAL;
6442 goto done;
6443 }
6444
6445 error = copyin(uap->client_id + sizeof(signable), &address_answer, sizeof(address_answer));
6446 if (error) {
6447 NECPLOG(LOG_ERR, "necp_client_sign copyin address_answer error (%d)", error);
6448 goto done;
6449 }
6450
6451 error = copyin(uap->client_id + sizeof(signable) + sizeof(address_answer), &hostname_length, sizeof(hostname_length));
6452 if (error) {
6453 NECPLOG(LOG_ERR, "necp_client_sign copyin hostname_length error (%d)", error);
6454 goto done;
6455 }
6456
6457 if (hostname_length > NECP_CLIENT_ACTION_SIGN_MAX_HOSTNAME_LENGTH) {
6458 error = EINVAL;
6459 goto done;
6460 }
6461
6462 if (hostname_length > NECP_CLIENT_ACTION_SIGN_DEFAULT_HOSTNAME_LENGTH) {
6463 if ((allocated_hostname = _MALLOC(hostname_length, M_NECP, M_WAITOK | M_ZERO)) == NULL) {
6464 NECPLOG(LOG_ERR, "necp_client_sign malloc hostname %u failed", hostname_length);
6465 error = ENOMEM;
6466 goto done;
6467 }
6468
6469 client_hostname = allocated_hostname;
6470 } else {
6471 client_hostname = default_hostname;
6472 }
6473
6474 error = copyin(uap->client_id + sizeof(signable) + sizeof(address_answer) + sizeof(hostname_length), client_hostname, hostname_length);
6475 if (error) {
6476 NECPLOG(LOG_ERR, "necp_client_sign copyin hostname error (%d)", error);
6477 goto done;
6478 }
6479
6480 address_answer.sin.sin_port = 0;
6481 error = necp_sign_resolver_answer(signable.client_id, client_hostname, hostname_length,
6482 (u_int8_t *)&address_answer, sizeof(address_answer),
6483 tag, &tag_size);
6484 if (tag_size != sizeof(tag)) {
6485 NECPLOG(LOG_ERR, "necp_client_sign unexpected tag size %u", tag_size);
6486 error = EINVAL;
6487 goto done;
6488 }
6489 error = copyout(tag, uap->buffer, tag_size);
6490 if (error) {
6491 NECPLOG(LOG_ERR, "necp_client_sign copyout error (%d)", error);
6492 goto done;
6493 }
6494
6495done:
6496 if (allocated_hostname != NULL) {
6497 FREE(allocated_hostname, M_NECP);
6498 allocated_hostname = NULL;
6499 }
6500 *retval = error;
6501 return error;
6502}
6503
39037602
A
6504int
6505necp_client_action(struct proc *p, struct necp_client_action_args *uap, int *retval)
6506{
f427ee49 6507 struct fileproc *fp;
39037602
A
6508 int error = 0;
6509 int return_value = 0;
6510 struct necp_fd_data *fd_data = NULL;
f427ee49
A
6511
6512 error = necp_find_fd_data(p, uap->necp_fd, &fp, &fd_data);
39037602
A
6513 if (error != 0) {
6514 NECPLOG(LOG_ERR, "necp_client_action find fd error (%d)", error);
0a7de745 6515 return error;
39037602
A
6516 }
6517
6518 u_int32_t action = uap->action;
6519 switch (action) {
0a7de745
A
6520 case NECP_CLIENT_ACTION_ADD: {
6521 return_value = necp_client_add(p, fd_data, uap, retval);
6522 break;
6523 }
cb323159
A
6524 case NECP_CLIENT_ACTION_CLAIM: {
6525 return_value = necp_client_claim(p, fd_data, uap, retval);
6526 break;
6527 }
0a7de745
A
6528 case NECP_CLIENT_ACTION_REMOVE: {
6529 return_value = necp_client_remove(fd_data, uap, retval);
6530 break;
6531 }
6532 case NECP_CLIENT_ACTION_COPY_PARAMETERS:
6533 case NECP_CLIENT_ACTION_COPY_RESULT:
6534 case NECP_CLIENT_ACTION_COPY_UPDATED_RESULT: {
6535 return_value = necp_client_copy(fd_data, uap, retval);
6536 break;
6537 }
6538 case NECP_CLIENT_ACTION_COPY_LIST: {
6539 return_value = necp_client_list(fd_data, uap, retval);
6540 break;
6541 }
f427ee49
A
6542 case NECP_CLIENT_ACTION_ADD_FLOW: {
6543 return_value = necp_client_add_flow(fd_data, uap, retval);
6544 break;
6545 }
6546 case NECP_CLIENT_ACTION_REMOVE_FLOW: {
6547 return_value = necp_client_remove_flow(fd_data, uap, retval);
6548 break;
6549 }
0a7de745
A
6550 case NECP_CLIENT_ACTION_AGENT: {
6551 return_value = necp_client_agent_action(fd_data, uap, retval);
6552 break;
6553 }
6554 case NECP_CLIENT_ACTION_COPY_AGENT: {
6555 return_value = necp_client_copy_agent(fd_data, uap, retval);
6556 break;
6557 }
6558 case NECP_CLIENT_ACTION_AGENT_USE: {
6559 return_value = necp_client_agent_use(fd_data, uap, retval);
6560 break;
6561 }
6562 case NECP_CLIENT_ACTION_COPY_INTERFACE: {
6563 return_value = necp_client_copy_interface(fd_data, uap, retval);
6564 break;
6565 }
6566 case NECP_CLIENT_ACTION_COPY_ROUTE_STATISTICS: {
6567 return_value = necp_client_copy_route_statistics(fd_data, uap, retval);
6568 break;
6569 }
6570 case NECP_CLIENT_ACTION_UPDATE_CACHE: {
6571 return_value = necp_client_update_cache(fd_data, uap, retval);
6572 break;
6573 }
6574 case NECP_CLIENT_ACTION_COPY_CLIENT_UPDATE: {
6575 return_value = necp_client_copy_client_update(fd_data, uap, retval);
6576 break;
6577 }
cb323159
A
6578 case NECP_CLIENT_ACTION_SIGN: {
6579 return_value = necp_client_sign(fd_data, uap, retval);
6580 break;
6581 }
0a7de745
A
6582 default: {
6583 NECPLOG(LOG_ERR, "necp_client_action unknown action (%u)", action);
6584 return_value = EINVAL;
6585 break;
6586 }
39037602
A
6587 }
6588
f427ee49 6589 fp_drop(p, uap->necp_fd, fp, 0);
0a7de745 6590 return return_value;
39037602
A
6591}
6592
6593#define NECP_MAX_MATCH_POLICY_PARAMETER_SIZE 1024
6594
6595int
6596necp_match_policy(struct proc *p, struct necp_match_policy_args *uap, int32_t *retval)
6597{
6598#pragma unused(retval)
6599 u_int8_t *parameters = NULL;
d9a64523 6600 struct necp_aggregate_result returned_result;
39037602
A
6601 int error = 0;
6602
6603 if (uap == NULL) {
6604 error = EINVAL;
6605 goto done;
6606 }
6607
6608 if (uap->parameters == 0 || uap->parameters_size == 0 || uap->parameters_size > NECP_MAX_MATCH_POLICY_PARAMETER_SIZE || uap->returned_result == 0) {
6609 error = EINVAL;
6610 goto done;
6611 }
6612
6613 MALLOC(parameters, u_int8_t *, uap->parameters_size, M_NECP, M_WAITOK | M_ZERO);
6614 if (parameters == NULL) {
6615 error = ENOMEM;
6616 goto done;
6617 }
6618 // Copy parameters in
6619 error = copyin(uap->parameters, parameters, uap->parameters_size);
6620 if (error) {
6621 goto done;
6622 }
6623
5ba3f43e 6624 error = necp_application_find_policy_match_internal(p, parameters, uap->parameters_size,
ea3f0419 6625 &returned_result, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, false, false, NULL);
39037602
A
6626 if (error) {
6627 goto done;
6628 }
6629
6630 // Copy return value back
6631 error = copyout(&returned_result, uap->returned_result, sizeof(struct necp_aggregate_result));
6632 if (error) {
6633 goto done;
6634 }
6635done:
6636 if (parameters != NULL) {
6637 FREE(parameters, M_NECP);
6638 }
0a7de745 6639 return error;
39037602
A
6640}
6641
6642/// Socket operations
6643#define NECP_MAX_SOCKET_ATTRIBUTE_STRING_LENGTH 253
6644
6645static bool
6646necp_set_socket_attribute(u_int8_t *buffer, size_t buffer_length, u_int8_t type, char **buffer_p)
6647{
6648 int error = 0;
6649 int cursor = 0;
6650 size_t string_size = 0;
6651 char *local_string = NULL;
6652 u_int8_t *value = NULL;
6653
cb323159 6654 cursor = necp_buffer_find_tlv(buffer, buffer_length, 0, type, NULL, 0);
39037602
A
6655 if (cursor < 0) {
6656 // This will clear out the parameter
6657 goto done;
6658 }
6659
6660 string_size = necp_buffer_get_tlv_length(buffer, cursor);
6661 if (string_size == 0 || string_size > NECP_MAX_SOCKET_ATTRIBUTE_STRING_LENGTH) {
6662 // This will clear out the parameter
6663 goto done;
6664 }
6665
6666 MALLOC(local_string, char *, string_size + 1, M_NECP, M_WAITOK | M_ZERO);
6667 if (local_string == NULL) {
f427ee49 6668 NECPLOG(LOG_ERR, "Failed to allocate a socket attribute buffer (size %zu)", string_size);
39037602
A
6669 goto fail;
6670 }
6671
6672 value = necp_buffer_get_tlv_value(buffer, cursor, NULL);
6673 if (value == NULL) {
6674 NECPLOG0(LOG_ERR, "Failed to get socket attribute");
6675 goto fail;
6676 }
6677
6678 memcpy(local_string, value, string_size);
6679 local_string[string_size] = 0;
6680
6681done:
6682 if (*buffer_p != NULL) {
6683 FREE(*buffer_p, M_NECP);
6684 *buffer_p = NULL;
6685 }
6686
6687 *buffer_p = local_string;
0a7de745 6688 return 0;
39037602
A
6689fail:
6690 if (local_string != NULL) {
6691 FREE(local_string, M_NECP);
6692 }
0a7de745 6693 return error;
39037602
A
6694}
6695
6696errno_t
6697necp_set_socket_attributes(struct socket *so, struct sockopt *sopt)
6698{
6699 int error = 0;
6700 u_int8_t *buffer = NULL;
6701 struct inpcb *inp = NULL;
6702
f427ee49 6703 if (SOCK_DOM(so) != PF_INET && SOCK_DOM(so) != PF_INET6) {
39037602
A
6704 error = EINVAL;
6705 goto done;
6706 }
6707
6708 inp = sotoinpcb(so);
6709
6710 size_t valsize = sopt->sopt_valsize;
6711 if (valsize == 0 ||
0a7de745 6712 valsize > ((sizeof(struct necp_tlv_header) + NECP_MAX_SOCKET_ATTRIBUTE_STRING_LENGTH) * 2)) {
39037602
A
6713 goto done;
6714 }
6715
6716 MALLOC(buffer, u_int8_t *, valsize, M_NECP, M_WAITOK | M_ZERO);
6717 if (buffer == NULL) {
6718 goto done;
6719 }
6720
6721 error = sooptcopyin(sopt, buffer, valsize, 0);
6722 if (error) {
6723 goto done;
6724 }
6725
6726 error = necp_set_socket_attribute(buffer, valsize, NECP_TLV_ATTRIBUTE_DOMAIN, &inp->inp_necp_attributes.inp_domain);
6727 if (error) {
6728 NECPLOG0(LOG_ERR, "Could not set domain TLV for socket attributes");
6729 goto done;
6730 }
6731
6732 error = necp_set_socket_attribute(buffer, valsize, NECP_TLV_ATTRIBUTE_ACCOUNT, &inp->inp_necp_attributes.inp_account);
6733 if (error) {
6734 NECPLOG0(LOG_ERR, "Could not set account TLV for socket attributes");
6735 goto done;
6736 }
6737
6738 if (necp_debug) {
6739 NECPLOG(LOG_DEBUG, "Set on socket: Domain %s, Account %s", inp->inp_necp_attributes.inp_domain, inp->inp_necp_attributes.inp_account);
6740 }
6741done:
6742 if (buffer != NULL) {
6743 FREE(buffer, M_NECP);
6744 }
6745
0a7de745 6746 return error;
39037602
A
6747}
6748
6749errno_t
6750necp_get_socket_attributes(struct socket *so, struct sockopt *sopt)
6751{
6752 int error = 0;
6753 u_int8_t *buffer = NULL;
6754 u_int8_t *cursor = NULL;
6755 size_t valsize = 0;
5c9f4661 6756 struct inpcb *inp = NULL;
39037602 6757
f427ee49 6758 if (SOCK_DOM(so) != PF_INET && SOCK_DOM(so) != PF_INET6) {
5c9f4661
A
6759 error = EINVAL;
6760 goto done;
6761 }
6762
6763 inp = sotoinpcb(so);
39037602 6764 if (inp->inp_necp_attributes.inp_domain != NULL) {
5ba3f43e 6765 valsize += sizeof(struct necp_tlv_header) + strlen(inp->inp_necp_attributes.inp_domain);
39037602
A
6766 }
6767 if (inp->inp_necp_attributes.inp_account != NULL) {
5ba3f43e 6768 valsize += sizeof(struct necp_tlv_header) + strlen(inp->inp_necp_attributes.inp_account);
39037602
A
6769 }
6770 if (valsize == 0) {
6771 goto done;
6772 }
6773
6774 MALLOC(buffer, u_int8_t *, valsize, M_NECP, M_WAITOK | M_ZERO);
6775 if (buffer == NULL) {
6776 goto done;
6777 }
6778
6779 cursor = buffer;
6780 if (inp->inp_necp_attributes.inp_domain != NULL) {
5ba3f43e 6781 cursor = necp_buffer_write_tlv(cursor, NECP_TLV_ATTRIBUTE_DOMAIN, strlen(inp->inp_necp_attributes.inp_domain), inp->inp_necp_attributes.inp_domain,
0a7de745 6782 buffer, valsize);
39037602
A
6783 }
6784
6785 if (inp->inp_necp_attributes.inp_account != NULL) {
5ba3f43e 6786 cursor = necp_buffer_write_tlv(cursor, NECP_TLV_ATTRIBUTE_ACCOUNT, strlen(inp->inp_necp_attributes.inp_account), inp->inp_necp_attributes.inp_account,
0a7de745 6787 buffer, valsize);
39037602
A
6788 }
6789
6790 error = sooptcopyout(sopt, buffer, valsize);
6791 if (error) {
6792 goto done;
6793 }
6794done:
6795 if (buffer != NULL) {
6796 FREE(buffer, M_NECP);
6797 }
5ba3f43e 6798
0a7de745 6799 return error;
39037602
A
6800}
6801
5ba3f43e
A
6802void *
6803necp_create_nexus_assign_message(uuid_t nexus_instance, u_int32_t nexus_port, void *key, uint32_t key_length,
cb323159 6804 struct necp_client_endpoint *local_endpoint, struct necp_client_endpoint *remote_endpoint, struct ether_addr *local_ether_addr,
0a7de745 6805 u_int32_t flow_adv_index, void *flow_stats, size_t *message_length)
5ba3f43e
A
6806{
6807 u_int8_t *buffer = NULL;
6808 u_int8_t *cursor = NULL;
6809 size_t valsize = 0;
6810 bool has_nexus_assignment = FALSE;
6811
5ba3f43e
A
6812 if (!uuid_is_null(nexus_instance)) {
6813 has_nexus_assignment = TRUE;
6814 valsize += sizeof(struct necp_tlv_header) + sizeof(uuid_t);
6815 valsize += sizeof(struct necp_tlv_header) + sizeof(u_int32_t);
6816 }
6817 if (flow_adv_index != NECP_FLOWADV_IDX_INVALID) {
6818 valsize += sizeof(struct necp_tlv_header) + sizeof(u_int32_t);
6819 }
6820 if (key != NULL && key_length > 0) {
6821 valsize += sizeof(struct necp_tlv_header) + key_length;
6822 }
6823 if (local_endpoint != NULL) {
6824 valsize += sizeof(struct necp_tlv_header) + sizeof(struct necp_client_endpoint);
6825 }
6826 if (remote_endpoint != NULL) {
6827 valsize += sizeof(struct necp_tlv_header) + sizeof(struct necp_client_endpoint);
6828 }
cb323159
A
6829 if (local_ether_addr != NULL) {
6830 valsize += sizeof(struct necp_tlv_header) + sizeof(struct ether_addr);
6831 }
d9a64523
A
6832 if (flow_stats != NULL) {
6833 valsize += sizeof(struct necp_tlv_header) + sizeof(void *);
6834 }
5ba3f43e 6835 if (valsize == 0) {
0a7de745 6836 return NULL;
5ba3f43e
A
6837 }
6838
6839 MALLOC(buffer, u_int8_t *, valsize, M_NETAGENT, M_WAITOK | M_ZERO); // Use M_NETAGENT area, since it is expected upon free
6840 if (buffer == NULL) {
0a7de745 6841 return NULL;
5ba3f43e
A
6842 }
6843
6844 cursor = buffer;
6845 if (has_nexus_assignment) {
6846 cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_RESULT_NEXUS_INSTANCE, sizeof(uuid_t), nexus_instance, buffer, valsize);
6847 cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_RESULT_NEXUS_PORT, sizeof(u_int32_t), &nexus_port, buffer, valsize);
6848 }
6849 if (flow_adv_index != NECP_FLOWADV_IDX_INVALID) {
6850 cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_RESULT_NEXUS_PORT_FLOW_INDEX, sizeof(u_int32_t), &flow_adv_index, buffer, valsize);
6851 }
6852 if (key != NULL && key_length > 0) {
6853 cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_PARAMETER_NEXUS_KEY, key_length, key, buffer, valsize);
6854 }
6855 if (local_endpoint != NULL) {
6856 cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_RESULT_LOCAL_ENDPOINT, sizeof(struct necp_client_endpoint), local_endpoint, buffer, valsize);
6857 }
6858 if (remote_endpoint != NULL) {
6859 cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_RESULT_REMOTE_ENDPOINT, sizeof(struct necp_client_endpoint), remote_endpoint, buffer, valsize);
6860 }
cb323159
A
6861 if (local_ether_addr != NULL) {
6862 cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_RESULT_LOCAL_ETHER_ADDR, sizeof(struct ether_addr), local_ether_addr, buffer, valsize);
6863 }
d9a64523
A
6864 if (flow_stats != NULL) {
6865 cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_RESULT_NEXUS_FLOW_STATS, sizeof(void *), &flow_stats, buffer, valsize);
6866 }
5ba3f43e
A
6867
6868 *message_length = valsize;
6869
0a7de745 6870 return buffer;
5ba3f43e
A
6871}
6872
6873void
6874necp_inpcb_remove_cb(struct inpcb *inp)
6875{
6876 if (!uuid_is_null(inp->necp_client_uuid)) {
6877 necp_client_unregister_socket_flow(inp->necp_client_uuid, inp);
6878 uuid_clear(inp->necp_client_uuid);
6879 }
6880}
6881
39037602
A
6882void
6883necp_inpcb_dispose(struct inpcb *inp)
6884{
a39ff7e2 6885 necp_inpcb_remove_cb(inp); // Clear out socket registrations if not yet done
39037602
A
6886 if (inp->inp_necp_attributes.inp_domain != NULL) {
6887 FREE(inp->inp_necp_attributes.inp_domain, M_NECP);
6888 inp->inp_necp_attributes.inp_domain = NULL;
6889 }
6890 if (inp->inp_necp_attributes.inp_account != NULL) {
6891 FREE(inp->inp_necp_attributes.inp_account, M_NECP);
6892 inp->inp_necp_attributes.inp_account = NULL;
6893 }
6894}
6895
5ba3f43e
A
6896void
6897necp_mppcb_dispose(struct mppcb *mpp)
6898{
6899 if (!uuid_is_null(mpp->necp_client_uuid)) {
6900 necp_client_unregister_multipath_cb(mpp->necp_client_uuid, mpp);
6901 uuid_clear(mpp->necp_client_uuid);
6902 }
6903}
6904
39037602
A
6905/// Module init
6906
6907errno_t
6908necp_client_init(void)
6909{
39037602
A
6910 necp_fd_grp_attr = lck_grp_attr_alloc_init();
6911 if (necp_fd_grp_attr == NULL) {
a39ff7e2
A
6912 panic("lck_grp_attr_alloc_init failed\n");
6913 /* NOTREACHED */
39037602
A
6914 }
6915
6916 necp_fd_mtx_grp = lck_grp_alloc_init("necp_fd", necp_fd_grp_attr);
6917 if (necp_fd_mtx_grp == NULL) {
a39ff7e2
A
6918 panic("lck_grp_alloc_init failed\n");
6919 /* NOTREACHED */
39037602
A
6920 }
6921
6922 necp_fd_mtx_attr = lck_attr_alloc_init();
6923 if (necp_fd_mtx_attr == NULL) {
a39ff7e2
A
6924 panic("lck_attr_alloc_init failed\n");
6925 /* NOTREACHED */
39037602
A
6926 }
6927
5ba3f43e 6928 necp_flow_size = sizeof(struct necp_client_flow);
0a7de745 6929 necp_flow_cache = mcache_create(NECP_FLOW_ZONE_NAME, necp_flow_size, sizeof(uint64_t), 0, MCR_SLEEP);
a39ff7e2
A
6930 if (necp_flow_cache == NULL) {
6931 panic("mcache_create(necp_flow_cache) failed\n");
6932 /* NOTREACHED */
39037602
A
6933 }
6934
d9a64523 6935 necp_flow_registration_size = sizeof(struct necp_client_flow_registration);
0a7de745 6936 necp_flow_registration_cache = mcache_create(NECP_FLOW_REGISTRATION_ZONE_NAME, necp_flow_registration_size, sizeof(uint64_t), 0, MCR_SLEEP);
d9a64523
A
6937 if (necp_flow_registration_cache == NULL) {
6938 panic("mcache_create(necp_client_flow_registration) failed\n");
6939 /* NOTREACHED */
6940 }
6941
5ba3f43e 6942 necp_client_update_tcall = thread_call_allocate_with_options(necp_update_all_clients_callout, NULL,
0a7de745 6943 THREAD_CALL_PRIORITY_KERNEL, THREAD_CALL_OPTIONS_ONCE);
5ba3f43e
A
6944 VERIFY(necp_client_update_tcall != NULL);
6945
39037602 6946 lck_rw_init(&necp_fd_lock, necp_fd_mtx_grp, necp_fd_mtx_attr);
5ba3f43e
A
6947 lck_rw_init(&necp_observer_lock, necp_fd_mtx_grp, necp_fd_mtx_attr);
6948 lck_rw_init(&necp_client_tree_lock, necp_fd_mtx_grp, necp_fd_mtx_attr);
0a7de745 6949 lck_rw_init(&necp_flow_tree_lock, necp_fd_mtx_grp, necp_fd_mtx_attr);
5ba3f43e 6950 lck_rw_init(&necp_collect_stats_list_lock, necp_fd_mtx_grp, necp_fd_mtx_attr);
39037602
A
6951
6952 LIST_INIT(&necp_fd_list);
5ba3f43e 6953 LIST_INIT(&necp_fd_observer_list);
d9a64523 6954 LIST_INIT(&necp_collect_stats_flow_list);
5ba3f43e
A
6955
6956 RB_INIT(&necp_client_global_tree);
d9a64523 6957 RB_INIT(&necp_client_flow_global_tree);
39037602 6958
0a7de745 6959 return 0;
a39ff7e2
A
6960}
6961
6962void
6963necp_client_reap_caches(boolean_t purge)
6964{
6965 mcache_reap_now(necp_flow_cache, purge);
d9a64523 6966 mcache_reap_now(necp_flow_registration_cache, purge);
39037602 6967}
a39ff7e2 6968