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