1 /*
2 * Copyright (c) 2021, 2023 Apple Inc. All rights reserved.
3 * @APPLE_LICENSE_HEADER_START@
4 *
5 * This file contains Original Code and/or Modifications of Original Code
6 * as defined in and that are subject to the Apple Public Source License
7 * Version 2.0 (the 'License'). You may not use this file except in
8 * compliance with the License. Please obtain a copy of the License at
9 * http://www.opensource.apple.com/apsl/ and read it before using this
10 * file.
11 *
12 * The Original Code and all software distributed under the License are
13 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
14 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
15 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
17 * Please see the License for the specific language governing rights and
18 * limitations under the License.
19 *
20 * @APPLE_LICENSE_HEADER_END@
21 */
22
23 /*
24 * LOCKING STRATEGY
25 *
26 * The struct socket's so_flow_db field (struct soflow_db and its hash entries
27 * struct soflow_hash_entry) is protected by the socket lock. This covers all the
28 * socket paths that calls soflow_get_flow() as well as the garbage collection.
29 * For the socket detach path, soflow_detach() cannot assume the socket lock is
30 * held. Thus, reference counts are added to both struct soflow_db and struct
31 * soflow_hash_entry to avoid access after freed issues.
32 *
33 * The global list, soflow_entry_head, keeps track of all struct soflow_hash_entry
34 * entries which is used by garbage collection when detecting idle entries. This list
35 * is protected by the global lock soflow_lck_rw.
36 *
37 */
38
39 #include <sys/types.h>
40 #include <sys/kern_control.h>
41 #include <sys/queue.h>
42 #include <sys/domain.h>
43 #include <sys/protosw.h>
44 #include <sys/syslog.h>
45 #include <sys/systm.h>
46 #include <sys/sysproto.h>
47 #include <sys/socket.h>
48 #include <sys/socketvar.h>
49
50 #include <kern/sched_prim.h>
51 #include <kern/locks.h>
52 #include <kern/zalloc.h>
53 #include <kern/debug.h>
54 #include <net/ntstat.h>
55 #include <netinet6/in6_var.h>
56
57 #define _IP_VHL
58 #include <netinet/ip.h>
59 #include <netinet/in_pcb.h>
60 #include <netinet/udp.h>
61 #include <netinet/udp_var.h>
62
63 #include <string.h>
64 #include <libkern/libkern.h>
65 #include <kern/socket_flows.h>
66 #include <net/sockaddr_utils.h>
67
68 extern struct inpcbinfo ripcbinfo;
69
70 /*
71 * Per-Socket Flow Management
72 */
73
74 static int soflow_log_level = LOG_ERR;
75 static int soflow_log_port = 0;
76 static int soflow_log_pid = 0;
77 static int soflow_log_proto = 0;
78 static int soflow_nstat_disable = 0;
79 static int soflow_disable = 0;
80 static long soflow_attached_count = 0;
81 static long soflow_attached_high_water_mark = 0;
82 static os_log_t soflow_log_handle = NULL;
83
84 /*
85 * Sysctls for debug logs control
86 */
87 SYSCTL_NODE(_net, OID_AUTO, soflow, CTLFLAG_RW | CTLFLAG_LOCKED, 0, "soflow");
88
89 SYSCTL_INT(_net_soflow, OID_AUTO, log_level, CTLFLAG_RW | CTLFLAG_LOCKED,
90 &soflow_log_level, 0, "");
91
92 SYSCTL_INT(_net_soflow, OID_AUTO, log_port, CTLFLAG_RW | CTLFLAG_LOCKED,
93 &soflow_log_port, 0, "");
94
95 SYSCTL_INT(_net_soflow, OID_AUTO, log_pid, CTLFLAG_RW | CTLFLAG_LOCKED,
96 &soflow_log_pid, 0, "");
97
98 SYSCTL_INT(_net_soflow, OID_AUTO, log_proto, CTLFLAG_RW | CTLFLAG_LOCKED,
99 &soflow_log_proto, 0, "");
100
101 SYSCTL_INT(_net_soflow, OID_AUTO, nstat_disable, CTLFLAG_RW | CTLFLAG_LOCKED,
102 &soflow_nstat_disable, 0, "");
103
104 SYSCTL_INT(_net_soflow, OID_AUTO, disable, CTLFLAG_RW | CTLFLAG_LOCKED,
105 &soflow_disable, 0, "");
106
107 SYSCTL_LONG(_net_soflow, OID_AUTO, count, CTLFLAG_LOCKED | CTLFLAG_RD, &soflow_attached_count, "");
108 SYSCTL_LONG(_net_soflow, OID_AUTO, high_water_mark, CTLFLAG_LOCKED | CTLFLAG_RD, &soflow_attached_high_water_mark, "");
109
110 #define SOFLOW_LOG(level, so, debug, fmt, ...) \
111 do { \
112 if (soflow_log_level >= level && debug && soflow_log_handle) { \
113 if (level == LOG_ERR) { \
114 os_log_error(soflow_log_handle, "SOFLOW - %s:%d <pid %d so %llx> " fmt "\n", __FUNCTION__, __LINE__, \
115 so ? SOFLOW_SOCKET_PID(so) : 0, so ? (uint64_t)VM_KERNEL_ADDRPERM(so) : 0, ##__VA_ARGS__); \
116 } else { \
117 os_log(soflow_log_handle, "SOFLOW - %s:%d <pid %d so %llx> " fmt "\n", __FUNCTION__, __LINE__, \
118 so ? SOFLOW_SOCKET_PID(so) : 0, so ? (uint64_t)VM_KERNEL_ADDRPERM(so) : 0, ##__VA_ARGS__); \
119 } \
120 } \
121 } while (0)
122
123 #define SOFLOW_ENTRY_LOG(level, so, entry, debug, msg) \
124 do { \
125 if (soflow_log_level >= level && entry && debug) { \
126 soflow_entry_log(level, so, entry, msg); \
127 } \
128 } while (0)
129
130 #define SOFLOW_HASH(laddr, faddr, lport, fport) ((faddr) ^ ((laddr) >> 16) ^ (fport) ^ (lport))
131
132 #define SOFLOW_IS_UDP(so) (so && SOCK_CHECK_TYPE(so, SOCK_DGRAM) && SOCK_CHECK_PROTO(so, IPPROTO_UDP))
133 #define SOFLOW_GET_SO_PROTO(so) (so ? SOCK_PROTO(so) : IPPROTO_MAX)
134
135 #define SOFLOW_SOCKET_PID(so) ((so->so_flags & SOF_DELEGATED) ? so->e_pid : so->last_pid)
136
137 #define SOFLOW_ENABLE_DEBUG(so, entry) \
138 ((soflow_log_port == 0 || !entry || soflow_log_port == ntohs(entry->soflow_lport) || soflow_log_port == ntohs(entry->soflow_fport)) && \
139 (soflow_log_pid == 0 || !so || soflow_log_pid == SOFLOW_SOCKET_PID(so)) && \
140 (soflow_log_proto == 0 || !so || soflow_log_proto == SOFLOW_GET_SO_PROTO(so)))
141
142 os_refgrp_decl(static, soflow_refgrp, "soflow_ref_group", NULL);
143
144 #define SOFLOW_ENTRY_FREE(entry) \
145 if (entry && (os_ref_release(&entry->soflow_ref_count) == 0)) { \
146 soflow_entry_free(entry); \
147 }
148
149 #define SOFLOW_DB_FREE(db) \
150 if (db && (os_ref_release(&db->soflow_db_ref_count) == 0)) { \
151 soflow_db_free(db); \
152 }
153
154 static int soflow_initialized = 0;
155
156 TAILQ_HEAD(soflow_entry_head, soflow_hash_entry) soflow_entry_head;
157 static LCK_GRP_DECLARE(soflow_lck_grp, "Socket Flow");
158 static LCK_RW_DECLARE(soflow_lck_rw, &soflow_lck_grp);
159
160 #define SOFLOW_LOCK_EXCLUSIVE lck_rw_lock_exclusive(&soflow_lck_rw)
161 #define SOFLOW_UNLOCK_EXCLUSIVE lck_rw_unlock_exclusive(&soflow_lck_rw)
162 #define SOFLOW_LOCK_SHARED lck_rw_lock_shared(&soflow_lck_rw)
163 #define SOFLOW_UNLOCK_SHARED lck_rw_unlock_shared(&soflow_lck_rw)
164
165 /*
166 * Flow Garbage Collection:
167 */
168 static struct thread *soflow_gc_thread;
169 static soflow_feat_gc_needed_func soflow_feat_gc_needed_func_ptr = NULL;
170 static soflow_feat_gc_perform_func soflow_feat_gc_perform_func_ptr = NULL;
171
172 #define SOFLOW_GC_IDLE_TO 30 // Flow Idle Timeout in seconds
173 #define SOFLOW_GC_MAX_COUNT 100 // Max sockets to be handled per run
174 #define SOFLOW_GC_RUN_INTERVAL_NSEC (10 * NSEC_PER_SEC) // GC wakes up every 10 seconds
175
176 /*
177 * Feature Context Handling:
178 */
179 static soflow_feat_detach_entry_func soflow_feat_detach_entry_func_ptr = NULL;
180 static soflow_feat_detach_db_func soflow_feat_detach_db_func_ptr = NULL;
181
182 static void soflow_gc_thread_func(void *v, wait_result_t w);
183 static void soflow_gc_expire(void *v, wait_result_t w);
184 static boolean_t soflow_entry_local_address_needs_update(struct soflow_hash_entry *);
185 static boolean_t soflow_entry_local_port_needs_update(struct socket *, struct soflow_hash_entry *);
186
187 static void
soflow_init(void)188 soflow_init(void)
189 {
190 if (soflow_initialized) {
191 return;
192 }
193 soflow_initialized = 1;
194
195 if (soflow_log_handle == NULL) {
196 soflow_log_handle = os_log_create("com.apple.xnu.net.soflow", "soflow");
197 }
198
199 TAILQ_INIT(&soflow_entry_head);
200
201 // Spawn thread for gargage collection
202 if (kernel_thread_start(soflow_gc_thread_func, NULL,
203 &soflow_gc_thread) != KERN_SUCCESS) {
204 panic_plain("%s: Can't create SOFLOW GC thread", __func__);
205 /* NOTREACHED */
206 }
207 /* this must not fail */
208 VERIFY(soflow_gc_thread != NULL);
209 }
210
211 static void
soflow_entry_log(int level,struct socket * so,struct soflow_hash_entry * entry,const char * msg)212 soflow_entry_log(int level, struct socket *so, struct soflow_hash_entry *entry, const char* msg)
213 {
214 #pragma unused(level, msg)
215 char local[MAX_IPv6_STR_LEN + 6] = { 0 };
216 char remote[MAX_IPv6_STR_LEN + 6] = { 0 };
217 const void *addr;
218
219 // No sock or not UDP, no-op
220 if (entry == NULL) {
221 return;
222 }
223
224 switch (entry->soflow_family) {
225 case AF_INET6:
226 addr = &entry->soflow_laddr.addr6;
227 inet_ntop(AF_INET6, addr, local, sizeof(local));
228 addr = &entry->soflow_faddr.addr6;
229 inet_ntop(AF_INET6, addr, remote, sizeof(local));
230 break;
231 case AF_INET:
232 addr = &entry->soflow_laddr.addr46.ia46_addr4.s_addr;
233 inet_ntop(AF_INET, addr, local, sizeof(local));
234 addr = &entry->soflow_faddr.addr46.ia46_addr4.s_addr;
235 inet_ntop(AF_INET, addr, remote, sizeof(local));
236 break;
237 default:
238 return;
239 }
240
241 SOFLOW_LOG(level, so, entry->soflow_debug, "<%s>: %s <%s(%d) entry %p, featureID %llu> outifp %d lport %d fport %d laddr %s faddr %s hash %X "
242 "<rx p %llu b %llu, tx p %llu b %llu>",
243 msg, entry->soflow_outgoing ? "OUT" : "IN ",
244 SOFLOW_IS_UDP(so) ? "UDP" : "proto", SOFLOW_GET_SO_PROTO(so),
245 entry, entry->soflow_feat_ctxt_id,
246 entry->soflow_outifindex,
247 ntohs(entry->soflow_lport), ntohs(entry->soflow_fport), local, remote,
248 entry->soflow_flowhash,
249 entry->soflow_rxpackets, entry->soflow_rxbytes, entry->soflow_txpackets, entry->soflow_txbytes);
250 }
251
252 bool
soflow_fill_hash_entry_from_address(struct soflow_hash_entry * entry,bool isLocal,struct sockaddr * addr,bool islocalUpdate)253 soflow_fill_hash_entry_from_address(struct soflow_hash_entry *entry, bool isLocal, struct sockaddr *addr, bool islocalUpdate)
254 {
255 struct sockaddr_in *sin = NULL;
256 struct sockaddr_in6 *sin6 = NULL;
257
258 if (entry == NULL || addr == NULL) {
259 return FALSE;
260 }
261
262 switch (addr->sa_family) {
263 case AF_INET:
264 sin = satosin(addr);
265 if (sin->sin_len < sizeof(*sin)) {
266 return FALSE;
267 }
268 if (isLocal == TRUE) {
269 if (sin->sin_port != 0) {
270 entry->soflow_lport = sin->sin_port;
271 if (islocalUpdate) {
272 entry->soflow_lport_updated = TRUE;
273 }
274 }
275 if (sin->sin_addr.s_addr != INADDR_ANY) {
276 entry->soflow_laddr.addr46.ia46_addr4.s_addr = sin->sin_addr.s_addr;
277 if (islocalUpdate) {
278 entry->soflow_laddr_updated = TRUE;
279 }
280 }
281 } else {
282 if (sin->sin_port != 0) {
283 entry->soflow_fport = sin->sin_port;
284 }
285 if (sin->sin_addr.s_addr != INADDR_ANY) {
286 entry->soflow_faddr.addr46.ia46_addr4.s_addr = sin->sin_addr.s_addr;
287 }
288 }
289 entry->soflow_family = AF_INET;
290 return TRUE;
291 case AF_INET6:
292 sin6 = satosin6(addr);
293 if (sin6->sin6_len < sizeof(*sin6)) {
294 return FALSE;
295 }
296 if (isLocal == TRUE) {
297 if (sin6->sin6_port != 0) {
298 entry->soflow_lport = sin6->sin6_port;
299 if (islocalUpdate) {
300 entry->soflow_lport_updated = TRUE;
301 }
302 }
303 if (!IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
304 entry->soflow_laddr.addr6 = sin6->sin6_addr;
305 entry->soflow_laddr6_ifscope = sin6->sin6_scope_id;
306 in6_verify_ifscope(&sin6->sin6_addr, sin6->sin6_scope_id);
307 if (islocalUpdate) {
308 entry->soflow_laddr_updated = TRUE;
309 }
310 }
311 } else {
312 if (sin6->sin6_port != 0) {
313 entry->soflow_fport = sin6->sin6_port;
314 }
315 if (!IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
316 entry->soflow_faddr.addr6 = sin6->sin6_addr;
317 entry->soflow_faddr6_ifscope = sin6->sin6_scope_id;
318 in6_verify_ifscope(&sin6->sin6_addr, sin6->sin6_scope_id);
319 }
320 }
321 entry->soflow_family = AF_INET6;
322 return TRUE;
323 default:
324 return FALSE;
325 }
326 }
327
328 bool
soflow_fill_hash_entry_from_inp(struct soflow_hash_entry * entry,bool isLocal,struct inpcb * inp,bool islocalUpdate)329 soflow_fill_hash_entry_from_inp(struct soflow_hash_entry *entry, bool isLocal, struct inpcb *inp, bool islocalUpdate)
330 {
331 if (entry == NULL || inp == NULL) {
332 return FALSE;
333 }
334
335 if (inp->inp_vflag & INP_IPV6) {
336 if (isLocal == TRUE) {
337 if (inp->inp_lport) {
338 entry->soflow_lport = inp->inp_lport;
339 if (islocalUpdate) {
340 entry->soflow_lport_updated = TRUE;
341 }
342 }
343 if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
344 entry->soflow_laddr.addr6 = inp->in6p_laddr;
345 entry->soflow_laddr6_ifscope = inp->inp_lifscope;
346 in6_verify_ifscope(&entry->soflow_laddr.addr6, inp->inp_lifscope);
347 if (islocalUpdate) {
348 entry->soflow_laddr_updated = TRUE;
349 }
350 }
351 } else {
352 if (inp->inp_fport) {
353 entry->soflow_fport = inp->inp_fport;
354 }
355 if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
356 entry->soflow_faddr.addr6 = inp->in6p_faddr;
357 entry->soflow_faddr6_ifscope = inp->inp_fifscope;
358 in6_verify_ifscope(&entry->soflow_faddr.addr6, inp->inp_fifscope);
359 }
360 }
361 entry->soflow_family = AF_INET6;
362 return TRUE;
363 } else if (inp->inp_vflag & INP_IPV4) {
364 if (isLocal == TRUE) {
365 if (inp->inp_lport) {
366 entry->soflow_lport = inp->inp_lport;
367 if (islocalUpdate) {
368 entry->soflow_lport_updated = TRUE;
369 }
370 }
371 if (inp->inp_laddr.s_addr) {
372 entry->soflow_laddr.addr46.ia46_addr4.s_addr = inp->inp_laddr.s_addr;
373 if (islocalUpdate) {
374 entry->soflow_laddr_updated = TRUE;
375 }
376 }
377 } else {
378 if (inp->inp_fport) {
379 entry->soflow_fport = inp->inp_fport;
380 }
381 if (inp->inp_faddr.s_addr) {
382 entry->soflow_faddr.addr46.ia46_addr4.s_addr = inp->inp_faddr.s_addr;
383 }
384 }
385 entry->soflow_family = AF_INET;
386 return TRUE;
387 }
388 return FALSE;
389 }
390
391 static errno_t
soflow_db_init(struct socket * so)392 soflow_db_init(struct socket *so)
393 {
394 errno_t error = 0;
395 struct soflow_db * __single db = NULL;
396 struct soflow_hash_entry *hash_entry = NULL;
397
398 db = kalloc_type(struct soflow_db, Z_WAITOK | Z_ZERO | Z_NOFAIL);
399 db->soflow_db_so = so;
400 void * __single hash = hashinit(SOFLOW_HASH_SIZE, M_CFIL, &db->soflow_db_hashmask);
401 db->soflow_db_hashbase = __unsafe_forge_bidi_indexable(struct soflow_hash_head *, hash, SOFLOW_HASH_SIZE * sizeof(void*));
402 if (db->soflow_db_hashbase == NULL) {
403 kfree_type(struct soflow_db, db);
404 error = ENOMEM;
405 goto done;
406 }
407 db->soflow_db_debug = SOFLOW_ENABLE_DEBUG(so, hash_entry);
408 os_ref_init(&db->soflow_db_ref_count, &soflow_refgrp);
409 so->so_flow_db = db;
410 done:
411 return error;
412 }
413
414 static void
soflow_entry_free(struct soflow_hash_entry * hash_entry)415 soflow_entry_free(struct soflow_hash_entry *hash_entry)
416 {
417 struct socket *so = (hash_entry && hash_entry->soflow_db) ? hash_entry->soflow_db->soflow_db_so : NULL;
418
419 if (hash_entry == NULL) {
420 return;
421 }
422
423 SOFLOW_ENTRY_LOG(LOG_INFO, so, hash_entry, hash_entry->soflow_debug, "Free entry");
424 kfree_type(struct soflow_hash_entry, hash_entry);
425 }
426
427 static void
soflow_db_remove_entry(struct soflow_db * db,struct soflow_hash_entry * hash_entry)428 soflow_db_remove_entry(struct soflow_db *db, struct soflow_hash_entry *hash_entry)
429 {
430 if (hash_entry == NULL) {
431 return;
432 }
433 if (db == NULL || db->soflow_db_count == 0) {
434 return;
435 }
436
437 #if defined(NSTAT_EXTENSION_FILTER_DOMAIN_INFO)
438 if (hash_entry->soflow_nstat_context != NULL) {
439 SOFLOW_LOG(LOG_INFO, db->soflow_db_so, hash_entry->soflow_debug, "<Close nstat> - context %lX", (unsigned long)hash_entry->soflow_nstat_context);
440 nstat_provider_stats_close(hash_entry->soflow_nstat_context);
441 hash_entry->soflow_nstat_context = NULL;
442 SOFLOW_ENTRY_FREE(hash_entry);
443 }
444 #endif
445
446 db->soflow_db_count--;
447 if (db->soflow_db_only_entry == hash_entry) {
448 db->soflow_db_only_entry = NULL;
449 }
450 LIST_REMOVE(hash_entry, soflow_entry_link);
451
452 // Feature context present, give feature a chance to detach and clean up
453 if (hash_entry->soflow_feat_ctxt != NULL && soflow_feat_detach_entry_func_ptr != NULL) {
454 soflow_feat_detach_entry_func_ptr(db->soflow_db_so, hash_entry);
455 hash_entry->soflow_feat_ctxt = NULL;
456 hash_entry->soflow_feat_ctxt_id = 0;
457 }
458
459 hash_entry->soflow_db = NULL;
460
461 SOFLOW_LOCK_EXCLUSIVE;
462 if (soflow_initialized) {
463 TAILQ_REMOVE(&soflow_entry_head, hash_entry, soflow_entry_list_link);
464 soflow_attached_count--;
465 }
466 SOFLOW_UNLOCK_EXCLUSIVE;
467
468 SOFLOW_ENTRY_FREE(hash_entry);
469 }
470
471 static void
soflow_db_free(struct soflow_db * db)472 soflow_db_free(struct soflow_db *db)
473 {
474 struct soflow_hash_entry *entry = NULL;
475 struct soflow_hash_entry *temp_entry = NULL;
476 struct soflow_hash_head *flowhash = NULL;
477
478 if (db == NULL) {
479 return;
480 }
481
482 SOFLOW_LOG(LOG_INFO, db->soflow_db_so, db->soflow_db_debug, "<db %p> freeing db (count == %d)", db, db->soflow_db_count);
483
484 for (int i = 0; i < SOFLOW_HASH_SIZE; i++) {
485 flowhash = &db->soflow_db_hashbase[i];
486 LIST_FOREACH_SAFE(entry, flowhash, soflow_entry_link, temp_entry) {
487 SOFLOW_ENTRY_LOG(LOG_INFO, db->soflow_db_so, entry, entry->soflow_debug, "Remove entry");
488 soflow_db_remove_entry(db, entry);
489 }
490 }
491
492 if (soflow_feat_detach_db_func_ptr != NULL) {
493 soflow_feat_detach_db_func_ptr(db->soflow_db_so, db);
494 }
495
496 // Make sure all entries are cleaned up!
497 VERIFY(db->soflow_db_count == 0);
498 hashdestroy(db->soflow_db_hashbase, M_CFIL, db->soflow_db_hashmask);
499 kfree_type(struct soflow_db, db);
500 }
501
502 void
soflow_detach(struct socket * so)503 soflow_detach(struct socket *so)
504 {
505 if (so == NULL || so->so_flow_db == NULL) {
506 return;
507 }
508 SOFLOW_DB_FREE(so->so_flow_db);
509 so->so_flow_db = NULL;
510 }
511
512 static boolean_t
soflow_match_entries_v4(struct soflow_hash_entry * entry1,struct soflow_hash_entry * entry2,boolean_t remoteOnly)513 soflow_match_entries_v4(struct soflow_hash_entry *entry1, struct soflow_hash_entry *entry2, boolean_t remoteOnly)
514 {
515 if (entry1 == NULL || entry2 == NULL) {
516 return false;
517 }
518
519 // Ignore local match if remoteOnly or if local has been updated since entry added
520 boolean_t lport_matched = (remoteOnly || entry1->soflow_lport_updated || entry1->soflow_lport == entry2->soflow_lport);
521 boolean_t laddr_matched = (remoteOnly || entry1->soflow_laddr_updated ||
522 entry1->soflow_laddr.addr46.ia46_addr4.s_addr == entry2->soflow_laddr.addr46.ia46_addr4.s_addr);
523
524 // Entries match if local and remote ports and addresses all matched
525 return lport_matched && entry1->soflow_fport == entry2->soflow_fport &&
526 laddr_matched && entry1->soflow_faddr.addr46.ia46_addr4.s_addr == entry2->soflow_faddr.addr46.ia46_addr4.s_addr;
527 }
528
529 static boolean_t
soflow_match_entries_v6(struct soflow_hash_entry * entry1,struct soflow_hash_entry * entry2,boolean_t remoteOnly)530 soflow_match_entries_v6(struct soflow_hash_entry *entry1, struct soflow_hash_entry *entry2, boolean_t remoteOnly)
531 {
532 if (entry1 == NULL || entry2 == NULL) {
533 return false;
534 }
535
536 // Ignore local match if remoteOnly or if local has been updated since entry added
537 boolean_t lport_matched = (remoteOnly || entry1->soflow_lport_updated || entry1->soflow_lport == entry2->soflow_lport);
538 boolean_t laddr_matched = (remoteOnly || entry1->soflow_laddr_updated ||
539 in6_are_addr_equal_scoped(&entry1->soflow_laddr.addr6, &entry2->soflow_laddr.addr6, entry1->soflow_laddr6_ifscope, entry2->soflow_laddr6_ifscope));
540
541 // Entries match if local and remote ports and addresses all matched
542 return lport_matched && entry1->soflow_fport == entry2->soflow_fport &&
543 laddr_matched && in6_are_addr_equal_scoped(&entry1->soflow_faddr.addr6, &entry2->soflow_faddr.addr6, entry1->soflow_faddr6_ifscope, entry2->soflow_faddr6_ifscope);
544 }
545
546 static struct soflow_hash_entry *
soflow_db_lookup_entry_internal(struct soflow_db * db,struct sockaddr * local,struct sockaddr * remote,boolean_t remoteOnly,boolean_t withLocalPort)547 soflow_db_lookup_entry_internal(struct soflow_db *db, struct sockaddr *local, struct sockaddr *remote, boolean_t remoteOnly, boolean_t withLocalPort)
548 {
549 struct soflow_hash_entry matchentry = { };
550 struct soflow_hash_entry *nextentry = NULL;
551 struct inpcb *inp = sotoinpcb(db->soflow_db_so);
552 u_int32_t hashkey_faddr = 0, hashkey_laddr = 0;
553 u_int16_t hashkey_fport = 0, hashkey_lport = 0;
554 int inp_hash_element = 0;
555 struct soflow_hash_head *flowhash = NULL;
556
557 if (inp == NULL || db == NULL) {
558 return NULL;
559 }
560
561 if (local != NULL) {
562 soflow_fill_hash_entry_from_address(&matchentry, TRUE, local, FALSE);
563 } else {
564 soflow_fill_hash_entry_from_inp(&matchentry, TRUE, inp, FALSE);
565 }
566 if (remote != NULL) {
567 soflow_fill_hash_entry_from_address(&matchentry, FALSE, remote, FALSE);
568 } else {
569 soflow_fill_hash_entry_from_inp(&matchentry, FALSE, inp, FALSE);
570 }
571 matchentry.soflow_debug = SOFLOW_ENABLE_DEBUG(db->soflow_db_so, (&matchentry));
572 SOFLOW_ENTRY_LOG(LOG_DEBUG, db->soflow_db_so, &matchentry, true, "Looking for entry");
573
574 if (inp->inp_vflag & INP_IPV6) {
575 hashkey_faddr = matchentry.soflow_faddr.addr6.s6_addr32[3];
576 hashkey_laddr = (remoteOnly == false) ? matchentry.soflow_laddr.addr6.s6_addr32[3] : 0;
577 } else {
578 hashkey_faddr = matchentry.soflow_faddr.addr46.ia46_addr4.s_addr;
579 hashkey_laddr = (remoteOnly == false) ? matchentry.soflow_laddr.addr46.ia46_addr4.s_addr : 0;
580 }
581
582 hashkey_fport = matchentry.soflow_fport;
583 hashkey_lport = (remoteOnly == false || withLocalPort == true) ? matchentry.soflow_lport : 0;
584
585 inp_hash_element = SOFLOW_HASH(hashkey_laddr, hashkey_faddr, hashkey_lport, hashkey_fport);
586 inp_hash_element &= db->soflow_db_hashmask;
587 flowhash = &db->soflow_db_hashbase[inp_hash_element];
588
589 LIST_FOREACH(nextentry, flowhash, soflow_entry_link) {
590 if (inp->inp_vflag & INP_IPV6) {
591 if (soflow_match_entries_v6(nextentry, &matchentry, remoteOnly)) {
592 SOFLOW_ENTRY_LOG(LOG_DEBUG, db->soflow_db_so, nextentry, nextentry->soflow_debug, "Found entry v6");
593 break;
594 }
595 } else if (inp->inp_vflag & INP_IPV4) {
596 if (soflow_match_entries_v4(nextentry, &matchentry, remoteOnly)) {
597 SOFLOW_ENTRY_LOG(LOG_DEBUG, db->soflow_db_so, nextentry, nextentry->soflow_debug, "Found entry v4");
598 break;
599 }
600 }
601 }
602
603 if (nextentry == NULL) {
604 SOFLOW_ENTRY_LOG(LOG_DEBUG, db->soflow_db_so, &matchentry, matchentry.soflow_debug, "Entry not found");
605 }
606 return nextentry;
607 }
608
609 static struct soflow_hash_entry *
soflow_db_lookup_entry(struct soflow_db * db,struct sockaddr * local,struct sockaddr * remote,boolean_t remoteOnly)610 soflow_db_lookup_entry(struct soflow_db *db, struct sockaddr *local, struct sockaddr *remote, boolean_t remoteOnly)
611 {
612 struct soflow_hash_entry *entry = soflow_db_lookup_entry_internal(db, local, remote, remoteOnly, false);
613 if (entry == NULL && remoteOnly == true) {
614 entry = soflow_db_lookup_entry_internal(db, local, remote, remoteOnly, true);
615 }
616 return entry;
617 }
618
619 static struct soflow_hash_entry *
soflow_db_lookup_by_feature_context_id(struct soflow_db * db,u_int64_t feature_context_id)620 soflow_db_lookup_by_feature_context_id(struct soflow_db *db, u_int64_t feature_context_id)
621 {
622 struct soflow_hash_head *flowhash = NULL;
623 u_int32_t inp_hash_element = (u_int32_t)(feature_context_id & 0x0ffffffff);
624 struct soflow_hash_entry *nextentry;
625
626 inp_hash_element &= db->soflow_db_hashmask;
627 flowhash = &db->soflow_db_hashbase[inp_hash_element];
628
629 LIST_FOREACH(nextentry, flowhash, soflow_entry_link) {
630 SOFLOW_ENTRY_LOG(LOG_DEBUG, db->soflow_db_so, nextentry, nextentry->soflow_debug, "Looking at entry");
631 if (nextentry->soflow_feat_ctxt != NULL &&
632 nextentry->soflow_feat_ctxt_id == feature_context_id) {
633 SOFLOW_ENTRY_LOG(LOG_DEBUG, db->soflow_db_so, nextentry, nextentry->soflow_debug, "Found entry by feature context id");
634 break;
635 }
636 }
637
638 if (nextentry == NULL) {
639 SOFLOW_LOG(LOG_DEBUG, db->soflow_db_so, db->soflow_db_debug, "No entry found for featureID %llu <count %d hash %X %X>",
640 feature_context_id, db->soflow_db_count, inp_hash_element, (u_int32_t)(feature_context_id & 0x0ffffffff));
641 }
642 return nextentry;
643 }
644
645 void *
soflow_db_get_feature_context(struct soflow_db * db,u_int64_t feature_context_id)646 soflow_db_get_feature_context(struct soflow_db *db, u_int64_t feature_context_id)
647 {
648 struct soflow_hash_entry *hash_entry = NULL;
649 void * __single context = NULL;
650
651 if (db == NULL || db->soflow_db_so == NULL || feature_context_id == 0) {
652 return NULL;
653 }
654
655 socket_lock_assert_owned(db->soflow_db_so);
656
657 // Take refcount of db before use.
658 // Abort if db is already being freed.
659 if (os_ref_retain_try(&db->soflow_db_ref_count) == false) {
660 return NULL;
661 }
662
663 // This is an optimization for datagram sockets with only one single flow.
664 if (db->soflow_db_count == 1) {
665 if (db->soflow_db_only_entry != NULL &&
666 db->soflow_db_only_entry->soflow_feat_ctxt != NULL && db->soflow_db_only_entry->soflow_feat_ctxt_id == feature_context_id) {
667 SOFLOW_ENTRY_LOG(LOG_DEBUG, db->soflow_db_so, db->soflow_db_only_entry, db->soflow_db_only_entry->soflow_debug, "MATCHED only entry for featureID");
668 context = db->soflow_db_only_entry->soflow_feat_ctxt;
669 } else {
670 SOFLOW_LOG(LOG_DEBUG, db->soflow_db_so, db->soflow_db_debug, "MISMATCHED only entry for featureID %llu (entry %p - cfil %p id %llu)",
671 feature_context_id,
672 db->soflow_db_only_entry,
673 db->soflow_db_only_entry ? db->soflow_db_only_entry->soflow_feat_ctxt : NULL,
674 db->soflow_db_only_entry ? db->soflow_db_only_entry->soflow_feat_ctxt_id : 0);
675 }
676 } else {
677 hash_entry = soflow_db_lookup_by_feature_context_id(db, feature_context_id);
678 context = hash_entry != NULL ? hash_entry->soflow_feat_ctxt : NULL;
679 }
680
681 SOFLOW_DB_FREE(db);
682 return context;
683 }
684
685 u_int64_t
soflow_db_get_feature_context_id(struct soflow_db * db,struct sockaddr * local,struct sockaddr * remote)686 soflow_db_get_feature_context_id(struct soflow_db *db, struct sockaddr *local, struct sockaddr *remote)
687 {
688 struct soflow_hash_entry *hash_entry = NULL;
689 uint64_t context_id = 0;
690
691 if (db == NULL || db->soflow_db_so == NULL) {
692 return 0;
693 }
694
695 socket_lock_assert_owned(db->soflow_db_so);
696
697 // Take refcount of db before use.
698 // Abort if db is already being freed.
699 if (os_ref_retain_try(&db->soflow_db_ref_count) == false) {
700 return 0;
701 }
702
703 hash_entry = soflow_db_lookup_entry(db, local, remote, false);
704 if (hash_entry == NULL) {
705 // No match with both local and remote, try match with remote only
706 hash_entry = soflow_db_lookup_entry(db, local, remote, true);
707 }
708 if (hash_entry != NULL && hash_entry->soflow_feat_ctxt != NULL) {
709 context_id = hash_entry->soflow_feat_ctxt_id;
710 }
711
712 SOFLOW_DB_FREE(db);
713
714 return context_id;
715 }
716
717 static struct soflow_hash_entry *
soflow_db_add_entry(struct soflow_db * db,struct sockaddr * local,struct sockaddr * remote)718 soflow_db_add_entry(struct soflow_db *db, struct sockaddr *local, struct sockaddr *remote)
719 {
720 struct soflow_hash_entry *entry = NULL;
721 struct inpcb *inp = db ? sotoinpcb(db->soflow_db_so) : NULL;
722 u_int32_t hashkey_faddr = 0, hashkey_laddr = 0;
723 int inp_hash_element = 0;
724 struct soflow_hash_head *flowhash = NULL;
725
726 if (db == NULL || inp == NULL) {
727 goto done;
728 }
729
730 entry = kalloc_type(struct soflow_hash_entry, Z_WAITOK | Z_ZERO | Z_NOFAIL);
731 os_ref_init(&entry->soflow_ref_count, &soflow_refgrp);
732
733 if (local != NULL) {
734 soflow_fill_hash_entry_from_address(entry, TRUE, local, FALSE);
735 } else {
736 soflow_fill_hash_entry_from_inp(entry, TRUE, inp, FALSE);
737 }
738 if (remote != NULL) {
739 soflow_fill_hash_entry_from_address(entry, FALSE, remote, FALSE);
740 } else {
741 soflow_fill_hash_entry_from_inp(entry, FALSE, inp, FALSE);
742 }
743 entry->soflow_lastused = net_uptime();
744 entry->soflow_db = db;
745 entry->soflow_debug = SOFLOW_ENABLE_DEBUG(db->soflow_db_so, entry);
746
747 if (inp->inp_vflag & INP_IPV6) {
748 hashkey_faddr = entry->soflow_faddr.addr6.s6_addr32[3];
749 hashkey_laddr = entry->soflow_laddr.addr6.s6_addr32[3];
750 } else {
751 hashkey_faddr = entry->soflow_faddr.addr46.ia46_addr4.s_addr;
752 hashkey_laddr = entry->soflow_laddr.addr46.ia46_addr4.s_addr;
753 }
754 entry->soflow_flowhash = SOFLOW_HASH(hashkey_laddr, hashkey_faddr,
755 entry->soflow_lport, entry->soflow_fport);
756 inp_hash_element = entry->soflow_flowhash & db->soflow_db_hashmask;
757
758 socket_lock_assert_owned(db->soflow_db_so);
759
760 // Take refcount of db before use.
761 // Abort if db is already being freed.
762 if (os_ref_retain_try(&db->soflow_db_ref_count) == false) {
763 return NULL;
764 }
765
766 flowhash = &db->soflow_db_hashbase[inp_hash_element];
767
768 LIST_INSERT_HEAD(flowhash, entry, soflow_entry_link);
769 db->soflow_db_count++;
770 db->soflow_db_only_entry = entry;
771 SOFLOW_LOG(LOG_INFO, db->soflow_db_so, db->soflow_db_debug, "total count %d", db->soflow_db_count);
772
773 SOFLOW_DB_FREE(db);
774
775 done:
776 return entry;
777 }
778
779 static boolean_t
soflow_udp_get_address_from_control(sa_family_t family,struct mbuf * control,uint8_t * __counted_by (* count)* address_ptr,int * count)780 soflow_udp_get_address_from_control(sa_family_t family, struct mbuf *control, uint8_t *__counted_by(*count) *address_ptr, int *count)
781 {
782 struct cmsghdr *cm;
783 struct in6_pktinfo *pi6;
784 struct socket *so = NULL;
785
786 if (control == NULL || address_ptr == NULL) {
787 return false;
788 }
789
790 for (; control != NULL; control = control->m_next) {
791 if (control->m_type != MT_CONTROL) {
792 continue;
793 }
794
795 for (cm = M_FIRST_CMSGHDR(control);
796 is_cmsg_valid(control, cm);
797 cm = M_NXT_CMSGHDR(control, cm)) {
798 SOFLOW_LOG(LOG_DEBUG, so, true, "Check control type %d", cm->cmsg_type);
799
800 switch (cm->cmsg_type) {
801 case IP_RECVDSTADDR:
802 if (family == AF_INET &&
803 cm->cmsg_level == IPPROTO_IP &&
804 cm->cmsg_len == CMSG_LEN(sizeof(struct in_addr))) {
805 *address_ptr = CMSG_DATA(cm);
806 *count = sizeof(struct in_addr);
807 return true;
808 }
809 break;
810 case IPV6_PKTINFO:
811 case IPV6_2292PKTINFO:
812 if (family == AF_INET6 &&
813 cm->cmsg_level == IPPROTO_IPV6 &&
814 cm->cmsg_len == CMSG_LEN(sizeof(struct in6_pktinfo))) {
815 pi6 = (struct in6_pktinfo *)(void *)CMSG_DATA(cm);
816 *address_ptr = (uint8_t *)&pi6->ipi6_addr;
817 *count = sizeof(struct in6_addr);
818 return true;
819 }
820 break;
821 default:
822 break;
823 }
824 }
825 }
826 return false;
827 }
828
829 static boolean_t
soflow_entry_local_address_needs_update(struct soflow_hash_entry * entry)830 soflow_entry_local_address_needs_update(struct soflow_hash_entry *entry)
831 {
832 if (entry->soflow_family == AF_INET6) {
833 return IN6_IS_ADDR_UNSPECIFIED(&entry->soflow_laddr.addr6);
834 } else if (entry->soflow_family == AF_INET) {
835 return entry->soflow_laddr.addr46.ia46_addr4.s_addr == INADDR_ANY;
836 }
837 return false;
838 }
839
840 static boolean_t
soflow_entry_local_port_needs_update(struct socket * so,struct soflow_hash_entry * entry)841 soflow_entry_local_port_needs_update(struct socket *so, struct soflow_hash_entry *entry)
842 {
843 if (SOFLOW_IS_UDP(so)) {
844 return entry->soflow_lport == 0;
845 }
846 return false;
847 }
848
849 static void
soflow_entry_update_local(struct soflow_db * db,struct soflow_hash_entry * entry,struct sockaddr * local,struct mbuf * control,u_short rcv_ifindex)850 soflow_entry_update_local(struct soflow_db *db, struct soflow_hash_entry *entry, struct sockaddr *local, struct mbuf *control, u_short rcv_ifindex)
851 {
852 struct inpcb *inp = sotoinpcb(db->soflow_db_so);
853 union sockaddr_in_4_6 address_buf = { };
854
855 if (inp == NULL || entry == NULL) {
856 return;
857 }
858
859 if (entry->soflow_outifindex == 0 && (inp->inp_last_outifp != NULL || rcv_ifindex != 0)) {
860 entry->soflow_outifindex = inp->inp_last_outifp ? inp->inp_last_outifp->if_index : rcv_ifindex;
861 SOFLOW_ENTRY_LOG(LOG_INFO, db->soflow_db_so, entry, entry->soflow_debug, "Updated outifp");
862 }
863
864 if (soflow_entry_local_address_needs_update(entry)) {
865 // Flow does not have a local address yet. Retrieve local address
866 // from control mbufs if present.
867 if (local == NULL && control != NULL) {
868 int size = 0;
869 uint8_t * __counted_by(size) addr_ptr = NULL;
870 boolean_t result = soflow_udp_get_address_from_control(entry->soflow_family, control, &addr_ptr, &size);
871
872 if (result && size && addr_ptr) {
873 switch (entry->soflow_family) {
874 case AF_INET:
875 if (size == sizeof(struct in_addr)) {
876 address_buf.sin.sin_port = 0;
877 address_buf.sin.sin_family = AF_INET;
878 address_buf.sin.sin_len = sizeof(struct sockaddr_in);
879 (void) memcpy(&address_buf.sin.sin_addr, addr_ptr, sizeof(struct in_addr));
880 local = sintosa(&address_buf.sin);
881 }
882 break;
883 case AF_INET6:
884 if (size == sizeof(struct in6_addr)) {
885 address_buf.sin6.sin6_port = 0;
886 address_buf.sin6.sin6_family = AF_INET6;
887 address_buf.sin6.sin6_len = sizeof(struct sockaddr_in6);
888 (void) memcpy(&address_buf.sin6.sin6_addr, addr_ptr, sizeof(struct in6_addr));
889 local = sin6tosa(&address_buf.sin6);
890 }
891 break;
892 default:
893 break;
894 }
895 }
896 }
897 if (local != NULL) {
898 soflow_fill_hash_entry_from_address(entry, TRUE, local, TRUE);
899 } else {
900 soflow_fill_hash_entry_from_inp(entry, TRUE, inp, TRUE);
901 }
902 if (entry->soflow_laddr_updated) {
903 SOFLOW_ENTRY_LOG(LOG_INFO, db->soflow_db_so, entry, entry->soflow_debug, "Updated address");
904 }
905 }
906
907 if (soflow_entry_local_port_needs_update(db->soflow_db_so, entry)) {
908 soflow_fill_hash_entry_from_inp(entry, TRUE, inp, TRUE);
909 if (entry->soflow_lport_updated) {
910 SOFLOW_ENTRY_LOG(LOG_INFO, db->soflow_db_so, entry, entry->soflow_debug, "Updated port");
911 }
912 }
913
914 return;
915 }
916
917 #if defined(NSTAT_EXTENSION_FILTER_DOMAIN_INFO)
918 static u_int32_t
ifnet_to_flags(struct ifnet * ifp,struct socket * so)919 ifnet_to_flags(struct ifnet *ifp, struct socket *so)
920 {
921 u_int32_t flags = 0;
922
923 if (ifp != NULL) {
924 flags = nstat_ifnet_to_flags(ifp);
925 if ((flags & NSTAT_IFNET_IS_WIFI) && ((flags & (NSTAT_IFNET_IS_AWDL | NSTAT_IFNET_IS_LLW)) == 0)) {
926 flags |= NSTAT_IFNET_IS_WIFI_INFRA;
927 }
928 } else {
929 flags = NSTAT_IFNET_IS_UNKNOWN_TYPE;
930 }
931
932 if (so != NULL && (so->so_flags1 & SOF1_CELLFALLBACK)) {
933 flags |= NSTAT_IFNET_VIA_CELLFALLBACK;
934 }
935 return flags;
936 }
937
938 static bool
soflow_nstat_provider_request_vals(nstat_provider_context ctx,u_int32_t * ifflagsp,nstat_counts * countsp,void * metadatap)939 soflow_nstat_provider_request_vals(nstat_provider_context ctx,
940 u_int32_t *ifflagsp,
941 nstat_counts *countsp,
942 void *metadatap)
943 {
944 struct soflow_hash_entry *hash_entry = (struct soflow_hash_entry *) ctx;
945 struct socket *so = (hash_entry && hash_entry->soflow_db) ? hash_entry->soflow_db->soflow_db_so : NULL;
946 struct inpcb *inp = so ? sotoinpcb(so) : NULL;
947 char local[MAX_IPv6_STR_LEN + 6] = { 0 };
948 char remote[MAX_IPv6_STR_LEN + 6] = { 0 };
949 const void *addr = NULL;
950
951 if (hash_entry == NULL || so == NULL || inp == NULL) {
952 return false;
953 }
954
955 if (ifflagsp) {
956 if (hash_entry->soflow_outifindex) {
957 struct ifnet *ifp = ifindex2ifnet[hash_entry->soflow_outifindex];
958 *ifflagsp = ifnet_to_flags(ifp, so);
959 }
960 if ((countsp == NULL) && (metadatap == NULL)) {
961 SOFLOW_LOG(LOG_DEBUG, so, hash_entry->soflow_debug, "ifflagsp set to 0x%X", *ifflagsp);
962 goto done;
963 }
964 }
965
966 if (countsp) {
967 bzero(countsp, sizeof(*countsp));
968 countsp->nstat_rxpackets = hash_entry->soflow_rxpackets;
969 countsp->nstat_rxbytes = hash_entry->soflow_rxbytes;
970 countsp->nstat_txpackets = hash_entry->soflow_txpackets;
971 countsp->nstat_txbytes = hash_entry->soflow_txbytes;
972
973 SOFLOW_LOG(LOG_DEBUG, so, hash_entry->soflow_debug,
974 "Collected NSTAT counts: rxpackets %llu rxbytes %llu txpackets %llu txbytes %llu",
975 countsp->nstat_rxpackets, countsp->nstat_rxbytes, countsp->nstat_txpackets, countsp->nstat_txbytes);
976 }
977
978 if (metadatap) {
979 nstat_udp_descriptor *desc = (nstat_udp_descriptor *)metadatap;
980 bzero(desc, sizeof(*desc));
981
982 if (so->so_flags & SOF_DELEGATED) {
983 desc->eupid = so->e_upid;
984 desc->epid = so->e_pid;
985 uuid_copy(desc->euuid, so->e_uuid);
986 } else {
987 desc->eupid = so->last_upid;
988 desc->epid = so->last_pid;
989 uuid_copy(desc->euuid, so->last_uuid);
990 }
991
992 uuid_copy(desc->vuuid, so->so_vuuid);
993 uuid_copy(desc->fuuid, hash_entry->soflow_uuid);
994
995 if (hash_entry->soflow_family == AF_INET6) {
996 in6_ip6_to_sockaddr(&hash_entry->soflow_laddr.addr6, hash_entry->soflow_lport, hash_entry->soflow_laddr6_ifscope,
997 &desc->local.v6, sizeof(desc->local.v6));
998 in6_ip6_to_sockaddr(&hash_entry->soflow_faddr.addr6, hash_entry->soflow_fport, hash_entry->soflow_faddr6_ifscope,
999 &desc->remote.v6, sizeof(desc->remote.v6));
1000 } else if (hash_entry->soflow_family == AF_INET) {
1001 desc->local.v4.sin_family = AF_INET;
1002 desc->local.v4.sin_len = sizeof(struct sockaddr_in);
1003 desc->local.v4.sin_port = hash_entry->soflow_lport;
1004 desc->local.v4.sin_addr = hash_entry->soflow_laddr.addr46.ia46_addr4;
1005
1006 desc->remote.v4.sin_family = AF_INET;
1007 desc->remote.v4.sin_len = sizeof(struct sockaddr_in);
1008 desc->remote.v4.sin_port = hash_entry->soflow_fport;
1009 desc->remote.v4.sin_addr = hash_entry->soflow_faddr.addr46.ia46_addr4;
1010 }
1011
1012 desc->ifindex = hash_entry->soflow_outifindex;
1013 if (hash_entry->soflow_outifindex) {
1014 struct ifnet *ifp = ifindex2ifnet[hash_entry->soflow_outifindex];
1015 desc->ifnet_properties = (uint16_t)ifnet_to_flags(ifp, so);
1016 }
1017
1018 desc->rcvbufsize = so->so_rcv.sb_hiwat;
1019 desc->rcvbufused = so->so_rcv.sb_cc;
1020 desc->traffic_class = so->so_traffic_class;
1021 inp_get_activity_bitmap(inp, &desc->activity_bitmap);
1022
1023 if (hash_entry->soflow_debug) {
1024 switch (hash_entry->soflow_family) {
1025 case AF_INET6:
1026 addr = &desc->local.v6;
1027 inet_ntop(AF_INET6, addr, local, sizeof(local));
1028 addr = &desc->remote.v6;
1029 inet_ntop(AF_INET6, addr, remote, sizeof(local));
1030 break;
1031 case AF_INET:
1032 addr = &desc->local.v4.sin_addr;
1033 inet_ntop(AF_INET, addr, local, sizeof(local));
1034 addr = &desc->remote.v4.sin_addr;
1035 inet_ntop(AF_INET, addr, remote, sizeof(local));
1036 break;
1037 default:
1038 break;
1039 }
1040
1041 uint8_t *ptr = (uint8_t *)&desc->euuid;
1042
1043 SOFLOW_LOG(LOG_DEBUG, so, hash_entry->soflow_debug,
1044 "Collected NSTAT metadata: eupid %llu epid %d euuid %x%x%x%x-%x%x%x%x-%x%x%x%x-%x%x%x%x "
1045 "outifp %d properties 0x%X lport %d fport %d laddr %s faddr %s "
1046 "rcvbufsize %u rcvbufused %u traffic_class %u",
1047 desc->eupid, desc->epid,
1048 ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5], ptr[6], ptr[7],
1049 ptr[8], ptr[9], ptr[10], ptr[11], ptr[12], ptr[13], ptr[14], ptr[15],
1050 desc->ifindex, desc->ifnet_properties,
1051 ntohs(desc->local.v4.sin_port), ntohs(desc->remote.v4.sin_port), local, remote,
1052 desc->rcvbufsize, desc->rcvbufused, desc->traffic_class);
1053 }
1054 }
1055 done:
1056 return true;
1057 }
1058
1059 static size_t
soflow_nstat_provider_request_extensions(nstat_provider_context ctx,int requested_extension,void * buf,size_t buf_size)1060 soflow_nstat_provider_request_extensions(nstat_provider_context ctx,
1061 int requested_extension,
1062 void *buf,
1063 size_t buf_size)
1064 {
1065 struct soflow_hash_entry *hash_entry = (struct soflow_hash_entry *) ctx;
1066 struct socket *so = (hash_entry && hash_entry->soflow_db) ? hash_entry->soflow_db->soflow_db_so : NULL;
1067 struct inpcb *inp = so ? sotoinpcb(so) : NULL;
1068 struct nstat_domain_info *domain_info = NULL;
1069 size_t size = 0;
1070
1071 if (hash_entry == NULL || so == NULL || inp == NULL) {
1072 return 0;
1073 }
1074
1075 if (buf == NULL) {
1076 switch (requested_extension) {
1077 case NSTAT_EXTENDED_UPDATE_TYPE_DOMAIN:
1078 return sizeof(nstat_domain_info);
1079 default:
1080 return 0;
1081 }
1082 }
1083
1084 if (buf_size < sizeof(nstat_domain_info)) {
1085 return 0;
1086 }
1087
1088 switch (requested_extension) {
1089 case NSTAT_EXTENDED_UPDATE_TYPE_DOMAIN:
1090
1091 domain_info = (struct nstat_domain_info *)buf;
1092 necp_copy_inp_domain_info(inp, so, domain_info);
1093
1094 if (hash_entry->soflow_debug) {
1095 SOFLOW_LOG(LOG_DEBUG, so, hash_entry->soflow_debug, "Collected NSTAT domain_info:pid %d domain <%s> owner <%s> "
1096 "ctxt <%s> bundle id <%s> is_tracker %d is_non_app_initiated %d is_silent %d",
1097 so->so_flags & SOF_DELEGATED ? so->e_pid : so->last_pid,
1098 domain_info->domain_name,
1099 domain_info->domain_owner,
1100 domain_info->domain_tracker_ctxt,
1101 domain_info->domain_attributed_bundle_id,
1102 domain_info->is_tracker,
1103 domain_info->is_non_app_initiated,
1104 domain_info->is_silent);
1105 }
1106 size = sizeof(nstat_domain_info);
1107
1108 default:
1109 break;
1110 }
1111
1112 return size;
1113 }
1114 #endif
1115
1116 static void
soflow_update_flow_stats(struct soflow_hash_entry * hash_entry,size_t data_size,bool outgoing)1117 soflow_update_flow_stats(struct soflow_hash_entry *hash_entry, size_t data_size, bool outgoing)
1118 {
1119 struct socket *so = (hash_entry && hash_entry->soflow_db) ? hash_entry->soflow_db->soflow_db_so : NULL;
1120
1121 if (hash_entry != NULL) {
1122 if (outgoing) {
1123 hash_entry->soflow_txbytes += data_size;
1124 hash_entry->soflow_txpackets++;
1125 SOFLOW_ENTRY_LOG(LOG_DEBUG, so, hash_entry, hash_entry->soflow_debug, "Stats update - Outgoing");
1126 } else {
1127 hash_entry->soflow_rxbytes += data_size;
1128 hash_entry->soflow_rxpackets++;
1129 SOFLOW_ENTRY_LOG(LOG_DEBUG, so, hash_entry, hash_entry->soflow_debug, "Stats update - Incoming");
1130 }
1131 }
1132 }
1133
1134 struct soflow_hash_entry *
soflow_get_flow(struct socket * so,struct sockaddr * local,struct sockaddr * remote,struct mbuf * control,size_t data_size,bool outgoing,uint16_t rcv_ifindex)1135 soflow_get_flow(struct socket *so, struct sockaddr *local, struct sockaddr *remote, struct mbuf *control,
1136 size_t data_size, bool outgoing, uint16_t rcv_ifindex)
1137 {
1138 struct soflow_hash_entry *hash_entry = NULL;
1139 struct inpcb *inp = sotoinpcb(so);
1140
1141 // Check if feature is disabled
1142 if (soflow_disable) {
1143 return NULL;
1144 }
1145
1146 socket_lock_assert_owned(so);
1147
1148 if (so->so_flow_db != NULL) {
1149 // Take refcount of db before use.
1150 // Abort if db is already being freed.
1151 if (os_ref_retain_try(&so->so_flow_db->soflow_db_ref_count) == false) {
1152 return NULL;
1153 }
1154
1155 // DB already exists, check if this is existing flow
1156 hash_entry = soflow_db_lookup_entry(so->so_flow_db, local, remote, false);
1157 if (hash_entry == NULL) {
1158 // No match with both local and remote, try match with remote only
1159 hash_entry = soflow_db_lookup_entry(so->so_flow_db, local, remote, true);
1160 }
1161 if (hash_entry != NULL) {
1162 // Take refcount of entry before use.
1163 // Abort if entry is already being freed.
1164 if (os_ref_retain_try(&hash_entry->soflow_ref_count) == false) {
1165 SOFLOW_DB_FREE(so->so_flow_db);
1166 return NULL;
1167 }
1168
1169 // Try to update flow info from socket and/or control mbufs if necessary
1170 if (hash_entry->soflow_outifindex == 0 ||
1171 soflow_entry_local_address_needs_update(hash_entry) || soflow_entry_local_port_needs_update(so, hash_entry)) {
1172 soflow_entry_update_local(so->so_flow_db, hash_entry, local, control, rcv_ifindex);
1173 }
1174 hash_entry->soflow_lastused = net_uptime();
1175 soflow_update_flow_stats(hash_entry, data_size, outgoing);
1176
1177 SOFLOW_DB_FREE(so->so_flow_db);
1178 return hash_entry;
1179 }
1180
1181 SOFLOW_DB_FREE(so->so_flow_db);
1182 } else {
1183 // If new socket, allocate cfil db
1184 if (soflow_db_init(so) != 0) {
1185 return NULL;
1186 }
1187 }
1188
1189 hash_entry = soflow_db_add_entry(so->so_flow_db, local, remote);
1190 if (hash_entry == NULL) {
1191 SOFLOW_LOG(LOG_ERR, so, true, "Failed to add entry");
1192 return NULL;
1193 }
1194
1195 // Take refcount of entry before use.
1196 // Abort if entry is already being freed.
1197 if (os_ref_retain_try(&hash_entry->soflow_ref_count) == false) {
1198 return NULL;
1199 }
1200
1201 if (inp && (inp->inp_last_outifp != NULL || rcv_ifindex != 0)) {
1202 hash_entry->soflow_outifindex = inp->inp_last_outifp ? inp->inp_last_outifp->if_index : rcv_ifindex;
1203 }
1204
1205 // Check if we can update the new flow's local address from control mbufs
1206 if (control != NULL) {
1207 soflow_entry_update_local(so->so_flow_db, hash_entry, local, control, rcv_ifindex);
1208 }
1209 hash_entry->soflow_outgoing = outgoing;
1210 soflow_update_flow_stats(hash_entry, data_size, outgoing);
1211
1212 // Only report flow to NSTAT if unconnected UDP
1213 if (!soflow_nstat_disable && SOFLOW_IS_UDP(so) && !(so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING))) {
1214 #if defined(NSTAT_EXTENSION_FILTER_DOMAIN_INFO)
1215 // Take refcount of entry before handing it to nstat. Abort if fail.
1216 if (os_ref_retain_try(&hash_entry->soflow_ref_count) == false) {
1217 return NULL;
1218 }
1219 uuid_generate_random(hash_entry->soflow_uuid);
1220 hash_entry->soflow_nstat_context = nstat_provider_stats_open((nstat_provider_context) hash_entry,
1221 NSTAT_PROVIDER_UDP_SUBFLOW, 0,
1222 soflow_nstat_provider_request_vals,
1223 soflow_nstat_provider_request_extensions);
1224 SOFLOW_LOG(LOG_INFO, so, hash_entry->soflow_debug, "<Open nstat> - context %lX", (unsigned long)hash_entry->soflow_nstat_context);
1225 #endif
1226 }
1227
1228 SOFLOW_LOCK_EXCLUSIVE;
1229 if (soflow_initialized == 0) {
1230 soflow_init();
1231 }
1232 TAILQ_INSERT_TAIL(&soflow_entry_head, hash_entry, soflow_entry_list_link);
1233 if (soflow_attached_count == 0) {
1234 thread_wakeup((caddr_t)&soflow_attached_count);
1235 }
1236 soflow_attached_count++;
1237 if (soflow_attached_high_water_mark < soflow_attached_count) {
1238 soflow_attached_high_water_mark = soflow_attached_count;
1239 }
1240 SOFLOW_UNLOCK_EXCLUSIVE;
1241
1242 SOFLOW_ENTRY_LOG(LOG_INFO, so, hash_entry, hash_entry->soflow_debug, "Added entry");
1243 return hash_entry;
1244 }
1245
1246 void
soflow_free_flow(struct soflow_hash_entry * entry)1247 soflow_free_flow(struct soflow_hash_entry *entry)
1248 {
1249 SOFLOW_ENTRY_FREE(entry);
1250 }
1251
1252 static bool
soflow_socket_safe_lock(struct inpcb * inp,struct inpcbinfo * pcbinfo)1253 soflow_socket_safe_lock(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1254 {
1255 struct socket *so = NULL;
1256
1257 VERIFY(pcbinfo != NULL);
1258
1259 if (in_pcb_checkstate(inp, WNT_ACQUIRE, 0) != WNT_STOPUSING) {
1260 // Safeguarded the inp state, unlock pcbinfo before locking socket.
1261 lck_rw_done(&pcbinfo->ipi_lock);
1262
1263 so = inp->inp_socket;
1264 socket_lock(so, 1);
1265 if (in_pcb_checkstate(inp, WNT_RELEASE, 1) != WNT_STOPUSING) {
1266 return true;
1267 }
1268 } else {
1269 // Failed to safeguarded the inp state, unlock pcbinfo and abort.
1270 lck_rw_done(&pcbinfo->ipi_lock);
1271 }
1272
1273 if (so) {
1274 socket_unlock(so, 1);
1275 }
1276 return false;
1277 }
1278
1279 static struct socket *
soflow_validate_dgram_socket(struct socket * so)1280 soflow_validate_dgram_socket(struct socket *so)
1281 {
1282 struct inpcb *inp = NULL;
1283 struct inpcbinfo *pcbinfo = NULL;
1284 struct socket *locked = NULL;
1285
1286 pcbinfo = &udbinfo;
1287 lck_rw_lock_shared(&pcbinfo->ipi_lock);
1288 LIST_FOREACH(inp, pcbinfo->ipi_listhead, inp_list) {
1289 if (inp->inp_state != INPCB_STATE_DEAD && inp->inp_socket == so) {
1290 if (soflow_socket_safe_lock(inp, pcbinfo)) {
1291 locked = inp->inp_socket;
1292 }
1293 /* pcbinfo is already unlocked, we are done. */
1294 goto done;
1295 }
1296 }
1297 lck_rw_done(&pcbinfo->ipi_lock);
1298 if (locked != NULL) {
1299 goto done;
1300 }
1301
1302 pcbinfo = &ripcbinfo;
1303 lck_rw_lock_shared(&pcbinfo->ipi_lock);
1304 LIST_FOREACH(inp, pcbinfo->ipi_listhead, inp_list) {
1305 if (inp->inp_state != INPCB_STATE_DEAD && inp->inp_socket == so) {
1306 if (soflow_socket_safe_lock(inp, pcbinfo)) {
1307 locked = inp->inp_socket;
1308 }
1309 /* pcbinfo is already unlocked, we are done. */
1310 goto done;
1311 }
1312 }
1313 lck_rw_done(&pcbinfo->ipi_lock);
1314
1315 done:
1316 return locked;
1317 }
1318
1319 static void
soflow_gc_thread_sleep(bool forever)1320 soflow_gc_thread_sleep(bool forever)
1321 {
1322 if (forever) {
1323 (void) assert_wait((event_t) &soflow_attached_count,
1324 THREAD_INTERRUPTIBLE);
1325 } else {
1326 uint64_t deadline = 0;
1327 nanoseconds_to_absolutetime(SOFLOW_GC_RUN_INTERVAL_NSEC, &deadline);
1328 clock_absolutetime_interval_to_deadline(deadline, &deadline);
1329
1330 (void) assert_wait_deadline(&soflow_attached_count,
1331 THREAD_INTERRUPTIBLE, deadline);
1332 }
1333 }
1334
1335 static void
soflow_gc_thread_func(void * v,wait_result_t w)1336 soflow_gc_thread_func(void *v, wait_result_t w)
1337 {
1338 #pragma unused(v, w)
1339
1340 ASSERT(soflow_gc_thread == current_thread());
1341 thread_set_thread_name(current_thread(), "SOFLOW_GC");
1342
1343 // Kick off gc shortly
1344 soflow_gc_thread_sleep(false);
1345 thread_block_parameter((thread_continue_t) soflow_gc_expire, NULL);
1346 /* NOTREACHED */
1347 }
1348
1349 static bool
soflow_gc_idle_timed_out(struct soflow_hash_entry * hash_entry,int timeout,u_int64_t current_time)1350 soflow_gc_idle_timed_out(struct soflow_hash_entry *hash_entry, int timeout, u_int64_t current_time)
1351 {
1352 struct socket *so = (hash_entry && hash_entry->soflow_db) ? hash_entry->soflow_db->soflow_db_so : NULL;
1353
1354 if (hash_entry && (current_time - hash_entry->soflow_lastused >= (u_int64_t)timeout)) {
1355 SOFLOW_ENTRY_LOG(LOG_INFO, so, hash_entry, hash_entry->soflow_debug, "GC Idle Timeout detected");
1356 return true;
1357 }
1358 return false;
1359 }
1360
1361 static int
soflow_gc_cleanup(struct socket * so)1362 soflow_gc_cleanup(struct socket *so)
1363 {
1364 struct soflow_hash_entry *entry = NULL;
1365 struct soflow_hash_entry *temp_entry = NULL;
1366 struct soflow_hash_head *flowhash = NULL;
1367 struct soflow_db *db = NULL;
1368 int cleaned = 0;
1369
1370 if (so == NULL || so->so_flow_db == NULL) {
1371 return 0;
1372 }
1373 db = so->so_flow_db;
1374
1375 socket_lock_assert_owned(so);
1376
1377 // Take refcount of db before use.
1378 // Abort if db is already being freed.
1379 if (os_ref_retain_try(&db->soflow_db_ref_count) == false) {
1380 return 0;
1381 }
1382
1383 for (int i = 0; i < SOFLOW_HASH_SIZE; i++) {
1384 flowhash = &db->soflow_db_hashbase[i];
1385 LIST_FOREACH_SAFE(entry, flowhash, soflow_entry_link, temp_entry) {
1386 if (entry->soflow_gc || entry->soflow_feat_gc) {
1387 if (entry->soflow_feat_ctxt != NULL && soflow_feat_gc_perform_func_ptr != NULL) {
1388 soflow_feat_gc_perform_func_ptr(so, entry);
1389 entry->soflow_feat_ctxt = NULL;
1390 entry->soflow_feat_ctxt_id = 0;
1391 }
1392 entry->soflow_feat_gc = 0;
1393
1394 if (entry->soflow_gc) {
1395 SOFLOW_ENTRY_LOG(LOG_INFO, so, entry, entry->soflow_debug, "GC cleanup entry");
1396 entry->soflow_gc = 0;
1397 soflow_db_remove_entry(db, entry);
1398 cleaned++;
1399 }
1400 }
1401 }
1402 }
1403
1404 SOFLOW_DB_FREE(db);
1405 return cleaned;
1406 }
1407
1408 static void
soflow_gc_expire(void * v,wait_result_t w)1409 soflow_gc_expire(void *v, wait_result_t w)
1410 {
1411 #pragma unused(v, w)
1412
1413 static struct socket *socket_array[SOFLOW_GC_MAX_COUNT];
1414 struct soflow_hash_entry *hash_entry = NULL;
1415 struct socket *so = NULL;
1416 u_int64_t current_time = net_uptime();
1417 uint32_t socket_count = 0;
1418 uint32_t cleaned_count = 0;
1419 bool recorded = false;
1420
1421 // Collect a list of socket with expired flows
1422
1423 SOFLOW_LOCK_SHARED;
1424
1425 if (soflow_attached_count == 0) {
1426 SOFLOW_UNLOCK_SHARED;
1427 goto go_sleep;
1428 }
1429
1430 // Go thorough all flows in the flow list and record any socket with expired flows.
1431 TAILQ_FOREACH(hash_entry, &soflow_entry_head, soflow_entry_list_link) {
1432 if (socket_count >= SOFLOW_GC_MAX_COUNT) {
1433 break;
1434 }
1435 so = hash_entry->soflow_db ? hash_entry->soflow_db->soflow_db_so : NULL;
1436
1437 // Check if we need to perform cleanup due to idle time or feature specified rules
1438 hash_entry->soflow_gc = soflow_gc_idle_timed_out(hash_entry, SOFLOW_GC_IDLE_TO, current_time);
1439 hash_entry->soflow_feat_gc = (soflow_feat_gc_needed_func_ptr != NULL && soflow_feat_gc_needed_func_ptr(so, hash_entry, current_time));
1440
1441 if (hash_entry->soflow_gc || hash_entry->soflow_feat_gc) {
1442 if (so != NULL) {
1443 recorded = false;
1444 for (int i = 0; i < socket_count; i++) {
1445 if (socket_array[socket_count] == so) {
1446 recorded = true;
1447 break;
1448 }
1449 }
1450 if (recorded == false) {
1451 socket_array[socket_count] = so;
1452 socket_count++;
1453 }
1454 }
1455 }
1456 }
1457 SOFLOW_UNLOCK_SHARED;
1458
1459 if (socket_count == 0) {
1460 goto go_sleep;
1461 }
1462
1463 for (uint32_t i = 0; i < socket_count; i++) {
1464 // Validate socket and lock it
1465 so = soflow_validate_dgram_socket(socket_array[i]);
1466 if (so == NULL) {
1467 continue;
1468 }
1469 cleaned_count += soflow_gc_cleanup(so);
1470 socket_unlock(so, 1);
1471 }
1472
1473 so = NULL;
1474 SOFLOW_LOG(LOG_INFO, so, true, "<GC cleaned %d flows>", cleaned_count);
1475
1476 go_sleep:
1477
1478 // Sleep forever (until waken up) if no more UDP flow to clean
1479 SOFLOW_LOCK_SHARED;
1480 soflow_gc_thread_sleep(soflow_attached_count == 0 ? true : false);
1481 SOFLOW_UNLOCK_SHARED;
1482 thread_block_parameter((thread_continue_t)soflow_gc_expire, NULL);
1483 /* NOTREACHED */
1484 }
1485
1486 void
soflow_feat_set_functions(soflow_feat_gc_needed_func gc_needed_fn,soflow_feat_gc_perform_func gc_perform_fn,soflow_feat_detach_entry_func feat_detach_entry_fn,soflow_feat_detach_db_func feat_detach_db_fn)1487 soflow_feat_set_functions(soflow_feat_gc_needed_func gc_needed_fn,
1488 soflow_feat_gc_perform_func gc_perform_fn,
1489 soflow_feat_detach_entry_func feat_detach_entry_fn,
1490 soflow_feat_detach_db_func feat_detach_db_fn)
1491 {
1492 soflow_feat_gc_needed_func_ptr = gc_needed_fn;
1493 soflow_feat_gc_perform_func_ptr = gc_perform_fn;
1494 soflow_feat_detach_entry_func_ptr = feat_detach_entry_fn;
1495 soflow_feat_detach_db_func_ptr = feat_detach_db_fn;
1496 }
1497
1498 bool
soflow_db_apply(struct soflow_db * db,soflow_entry_apply_func entry_apply_fn,void * context)1499 soflow_db_apply(struct soflow_db *db, soflow_entry_apply_func entry_apply_fn, void *context)
1500 {
1501 struct soflow_hash_entry *entry = NULL;
1502 struct soflow_hash_entry *temp_entry = NULL;
1503 struct soflow_hash_head *flowhash = NULL;
1504
1505 if (db == NULL || db->soflow_db_so == NULL || entry_apply_fn == NULL) {
1506 return false;
1507 }
1508
1509 socket_lock_assert_owned(db->soflow_db_so);
1510
1511 // Take refcount of db before use.
1512 // Abort if db is already being freed.
1513 if (os_ref_retain_try(&db->soflow_db_ref_count) == false) {
1514 return false;
1515 }
1516
1517 for (int i = 0; i < SOFLOW_HASH_SIZE; i++) {
1518 flowhash = &db->soflow_db_hashbase[i];
1519 LIST_FOREACH_SAFE(entry, flowhash, soflow_entry_link, temp_entry) {
1520 if (entry_apply_fn(db->soflow_db_so, entry, context) == false) {
1521 goto done;
1522 }
1523 }
1524 }
1525
1526 done:
1527 SOFLOW_DB_FREE(db);
1528 return true;
1529 }
1530