1 /*
2 * Copyright (c) 2012-2021 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 <kern/locks.h>
30 #include <kern/policy_internal.h>
31 #include <kern/zalloc.h>
32
33 #include <mach/sdt.h>
34
35 #include <sys/domain.h>
36 #include <sys/kdebug.h>
37 #include <sys/kern_control.h>
38 #include <sys/kernel.h>
39 #include <sys/mbuf.h>
40 #include <sys/mcache.h>
41 #include <sys/param.h>
42 #include <sys/proc.h>
43 #include <sys/protosw.h>
44 #include <sys/resourcevar.h>
45 #include <sys/socket.h>
46 #include <sys/socketvar.h>
47 #include <sys/sysctl.h>
48 #include <sys/syslog.h>
49 #include <sys/systm.h>
50
51 #include <net/content_filter.h>
52 #include <net/if.h>
53 #include <net/if_var.h>
54 #include <netinet/in.h>
55 #include <netinet/in_pcb.h>
56 #include <netinet/in_var.h>
57 #include <netinet/tcp.h>
58 #include <netinet/tcp_cache.h>
59 #include <netinet/tcp_fsm.h>
60 #include <netinet/tcp_seq.h>
61 #include <netinet/tcp_var.h>
62 #include <netinet/mptcp_var.h>
63 #include <netinet/mptcp.h>
64 #include <netinet/mptcp_opt.h>
65 #include <netinet/mptcp_seq.h>
66 #include <netinet/mptcp_timer.h>
67 #include <libkern/crypto/sha1.h>
68 #include <libkern/crypto/sha2.h>
69 #include <netinet6/in6_pcb.h>
70 #include <netinet6/ip6protosw.h>
71 #include <dev/random/randomdev.h>
72 #include <net/sockaddr_utils.h>
73
74 /*
75 * Notes on MPTCP implementation.
76 *
77 * MPTCP is implemented as <SOCK_STREAM,IPPROTO_TCP> protocol in PF_MULTIPATH
78 * communication domain. The structure mtcbinfo describes the MPTCP instance
79 * of a Multipath protocol in that domain. It is used to keep track of all
80 * MPTCP PCB instances in the system, and is protected by the global lock
81 * mppi_lock.
82 *
83 * An MPTCP socket is opened by calling socket(PF_MULTIPATH, SOCK_STREAM,
84 * IPPROTO_TCP). Upon success, a Multipath PCB gets allocated and along with
85 * it comes an MPTCP Session and an MPTCP PCB. All three structures are
86 * allocated from the same memory block, and each structure has a pointer
87 * to the adjacent ones. The layout is defined by the mpp_mtp structure.
88 * The socket lock (mpp_lock) is used to protect accesses to the Multipath
89 * PCB (mppcb) as well as the MPTCP Session (mptses).
90 *
91 * The MPTCP Session is an MPTCP-specific extension to the Multipath PCB;
92 *
93 * A functioning MPTCP Session consists of one or more subflow sockets. Each
94 * subflow socket is essentially a regular PF_INET/PF_INET6 TCP socket, and is
95 * represented by the mptsub structure. Because each subflow requires access
96 * to the MPTCP Session, the MPTCP socket's so_usecount is bumped up for each
97 * subflow. This gets decremented prior to the subflow's destruction.
98 *
99 * To handle events (read, write, control) from the subflows, we do direct
100 * upcalls into the specific function.
101 *
102 * The whole MPTCP connection is protected by a single lock, the MPTCP socket's
103 * lock. Incoming data on a subflow also ends up taking this single lock. To
104 * achieve the latter, tcp_lock/unlock has been changed to rather use the lock
105 * of the MPTCP-socket.
106 *
107 * An MPTCP socket will be destroyed when its so_usecount drops to zero; this
108 * work is done by the MPTCP garbage collector which is invoked on demand by
109 * the PF_MULTIPATH garbage collector. This process will take place once all
110 * of the subflows have been destroyed.
111 */
112
113 static void mptcp_subflow_abort(struct mptsub *, int);
114
115 static void mptcp_send_dfin(struct socket *so);
116 static void mptcp_set_cellicon(struct mptses *mpte, struct mptsub *mpts);
117 static int mptcp_freeq(struct mptcb *mp_tp);
118
119 /*
120 * Possible return values for subflow event handlers. Note that success
121 * values must be greater or equal than MPTS_EVRET_OK. Values less than that
122 * indicate errors or actions which require immediate attention; they will
123 * prevent the rest of the handlers from processing their respective events
124 * until the next round of events processing.
125 */
126 typedef enum {
127 MPTS_EVRET_DELETE = 1, /* delete this subflow */
128 MPTS_EVRET_OK = 2, /* OK */
129 MPTS_EVRET_CONNECT_PENDING = 3, /* resume pended connects */
130 MPTS_EVRET_DISCONNECT_FALLBACK = 4, /* abort all but preferred */
131 } ev_ret_t;
132
133 static void mptcp_do_sha1(mptcp_key_t *, char sha_digest[SHA1_RESULTLEN]);
134 static void mptcp_do_sha256(mptcp_key_t *, char sha_digest[SHA256_DIGEST_LENGTH]);
135
136 static void mptcp_init_local_parms(struct mptses *, struct sockaddr *);
137
138 static KALLOC_TYPE_DEFINE(mptsub_zone, struct mptsub, NET_KT_DEFAULT);
139 static KALLOC_TYPE_DEFINE(mptopt_zone, struct mptopt, NET_KT_DEFAULT);
140 static KALLOC_TYPE_DEFINE(mpt_subauth_zone, struct mptcp_subf_auth_entry,
141 NET_KT_DEFAULT);
142
143 struct mppcbinfo mtcbinfo;
144
145 SYSCTL_DECL(_net_inet);
146
147 SYSCTL_NODE(_net_inet, OID_AUTO, mptcp, CTLFLAG_RW | CTLFLAG_LOCKED, 0, "MPTCP");
148
149 SYSCTL_UINT(_net_inet_mptcp, OID_AUTO, pcbcount, CTLFLAG_RD | CTLFLAG_LOCKED,
150 &mtcbinfo.mppi_count, 0, "Number of active PCBs");
151
152
153 static int mptcp_alternate_port = 0;
154 SYSCTL_INT(_net_inet_mptcp, OID_AUTO, alternate_port, CTLFLAG_RW | CTLFLAG_LOCKED,
155 &mptcp_alternate_port, 0, "Set alternate port for MPTCP connections");
156
157 static struct protosw mptcp_subflow_protosw;
158 static struct pr_usrreqs mptcp_subflow_usrreqs;
159 static struct ip6protosw mptcp_subflow_protosw6;
160 static struct pr_usrreqs mptcp_subflow_usrreqs6;
161
162 static uint8_t mptcp_create_subflows_scheduled;
163
164 /* Using Symptoms Advisory to detect poor WiFi or poor Cell */
165 static kern_ctl_ref mptcp_kern_ctrl_ref = NULL;
166 static uint32_t mptcp_kern_skt_inuse = 0;
167 static uint32_t mptcp_kern_skt_unit;
168 static symptoms_advisory_t mptcp_advisory;
169
170 uint32_t mptcp_cellicon_refcount = 0;
171
172 os_log_t mptcp_log_handle;
173
174 int
mptcpstats_get_index_by_ifindex(struct mptcp_itf_stats * stats __counted_by (stats_count),uint16_t stats_count,u_short ifindex,boolean_t create)175 mptcpstats_get_index_by_ifindex(struct mptcp_itf_stats *stats __counted_by(stats_count), uint16_t stats_count, u_short ifindex, boolean_t create)
176 {
177 int i, index = -1;
178
179 VERIFY(stats_count <= MPTCP_ITFSTATS_SIZE);
180
181 for (i = 0; i < MPTCP_ITFSTATS_SIZE; i++) {
182 if (create && stats[i].ifindex == IFSCOPE_NONE) {
183 if (index < 0) {
184 index = i;
185 }
186 continue;
187 }
188
189 if (stats[i].ifindex == ifindex) {
190 index = i;
191 return index;
192 }
193 }
194
195 if (index != -1) {
196 stats[index].ifindex = ifindex;
197 }
198
199 return index;
200 }
201
202 static int
mptcpstats_get_index(struct mptcp_itf_stats * stats __counted_by (stats_count),uint16_t stats_count,const struct mptsub * mpts)203 mptcpstats_get_index(struct mptcp_itf_stats *stats __counted_by(stats_count), uint16_t stats_count, const struct mptsub *mpts)
204 {
205 const struct ifnet *ifp = sotoinpcb(mpts->mpts_socket)->inp_last_outifp;
206 int index;
207
208 VERIFY(stats_count <= MPTCP_ITFSTATS_SIZE);
209
210 if (ifp == NULL) {
211 os_log_error(mptcp_log_handle, "%s - %lx: no ifp on subflow, state %u flags %#x\n",
212 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpts->mpts_mpte),
213 sototcpcb(mpts->mpts_socket)->t_state, mpts->mpts_flags);
214 return -1;
215 }
216
217 index = mptcpstats_get_index_by_ifindex(stats, MPTCP_ITFSTATS_SIZE, ifp->if_index, true);
218
219 if (index != -1) {
220 if (stats[index].is_expensive == 0) {
221 stats[index].is_expensive = IFNET_IS_CELLULAR(ifp);
222 }
223 }
224
225 return index;
226 }
227
228 void
mptcpstats_inc_switch(struct mptses * mpte,const struct mptsub * mpts)229 mptcpstats_inc_switch(struct mptses *mpte, const struct mptsub *mpts)
230 {
231 int index;
232
233 tcpstat.tcps_mp_switches++;
234 mpte->mpte_subflow_switches++;
235
236 index = mptcpstats_get_index(mpte->mpte_itfstats, MPTCP_ITFSTATS_SIZE, mpts);
237
238 if (index != -1) {
239 mpte->mpte_itfstats[index].switches++;
240 }
241 }
242
243 /*
244 * Flushes all recorded socket options from an MP socket.
245 */
246 static void
mptcp_flush_sopts(struct mptses * mpte)247 mptcp_flush_sopts(struct mptses *mpte)
248 {
249 struct mptopt *mpo, *tmpo;
250
251 TAILQ_FOREACH_SAFE(mpo, &mpte->mpte_sopts, mpo_entry, tmpo) {
252 mptcp_sopt_remove(mpte, mpo);
253 mptcp_sopt_free(mpo);
254 }
255 VERIFY(TAILQ_EMPTY(&mpte->mpte_sopts));
256 }
257
258 /*
259 * Create an MPTCP session, called as a result of opening a MPTCP socket.
260 */
261 int
mptcp_session_create(struct mppcb * mpp)262 mptcp_session_create(struct mppcb *mpp)
263 {
264 struct mpp_mtp *mtp;
265 struct mppcbinfo *mppi;
266 struct mptses *mpte;
267 struct mptcb *mp_tp;
268
269 VERIFY(mpp != NULL);
270 mppi = mpp->mpp_pcbinfo;
271 VERIFY(mppi != NULL);
272
273 mtp = __container_of(mpp, struct mpp_mtp, mpp);
274 mpte = &mtp->mpp_ses;
275 mp_tp = &mtp->mtcb;
276
277 /* MPTCP Multipath PCB Extension */
278 bzero(mpte, sizeof(*mpte));
279 VERIFY(mpp->mpp_pcbe == NULL);
280 mpp->mpp_pcbe = mpte;
281 mpte->mpte_mppcb = mpp;
282 mpte->mpte_mptcb = mp_tp;
283
284 TAILQ_INIT(&mpte->mpte_sopts);
285 TAILQ_INIT(&mpte->mpte_subflows);
286 mpte->mpte_associd = SAE_ASSOCID_ANY;
287 mpte->mpte_connid_last = SAE_CONNID_ANY;
288
289 mptcp_init_urgency_timer(mpte);
290
291 mpte->mpte_itfinfo = &mpte->_mpte_itfinfo[0];
292 mpte->mpte_itfinfo_size = MPTE_ITFINFO_SIZE;
293
294 if (mptcp_alternate_port > 0 && mptcp_alternate_port < UINT16_MAX) {
295 mpte->mpte_alternate_port = htons((uint16_t)mptcp_alternate_port);
296 }
297
298 mpte->mpte_last_cellicon_set = tcp_now;
299
300 /* MPTCP Protocol Control Block */
301 bzero(mp_tp, sizeof(*mp_tp));
302 mp_tp->mpt_mpte = mpte;
303 mp_tp->mpt_state = MPTCPS_CLOSED;
304
305 DTRACE_MPTCP1(session__create, struct mppcb *, mpp);
306
307 return 0;
308 }
309
310 struct sockaddr *
mptcp_get_session_dst(struct mptses * mpte,boolean_t ipv6,boolean_t ipv4)311 mptcp_get_session_dst(struct mptses *mpte, boolean_t ipv6, boolean_t ipv4)
312 {
313 if (ipv6 && mpte->mpte_sub_dst_v6.sin6_family == AF_INET6) {
314 return SA(&mpte->mpte_sub_dst_v6);
315 }
316
317 if (ipv4 && mpte->mpte_sub_dst_v4.sin_family == AF_INET) {
318 return SA(&mpte->mpte_sub_dst_v4);
319 }
320
321 /* The interface has neither IPv4 nor IPv6 routes. Give our best guess,
322 * meaning we prefer IPv6 over IPv4.
323 */
324 if (mpte->mpte_sub_dst_v6.sin6_family == AF_INET6) {
325 return SA(&mpte->mpte_sub_dst_v6);
326 }
327
328 if (mpte->mpte_sub_dst_v4.sin_family == AF_INET) {
329 return SA(&mpte->mpte_sub_dst_v4);
330 }
331
332 /* We don't yet have a unicast IP */
333 return NULL;
334 }
335
336 static void
mptcpstats_get_bytes(struct mptses * mpte,boolean_t initial_cell,uint64_t * cellbytes,uint64_t * allbytes)337 mptcpstats_get_bytes(struct mptses *mpte, boolean_t initial_cell,
338 uint64_t *cellbytes, uint64_t *allbytes)
339 {
340 int64_t mycellbytes = 0;
341 uint64_t myallbytes = 0;
342 int i;
343
344 for (i = 0; i < MPTCP_ITFSTATS_SIZE; i++) {
345 if (mpte->mpte_itfstats[i].is_expensive) {
346 mycellbytes += mpte->mpte_itfstats[i].mpis_txbytes;
347 mycellbytes += mpte->mpte_itfstats[i].mpis_rxbytes;
348 }
349
350 myallbytes += mpte->mpte_itfstats[i].mpis_txbytes;
351 myallbytes += mpte->mpte_itfstats[i].mpis_rxbytes;
352 }
353
354 if (initial_cell) {
355 mycellbytes -= mpte->mpte_init_txbytes;
356 mycellbytes -= mpte->mpte_init_rxbytes;
357 }
358
359 if (mycellbytes < 0) {
360 os_log_error(mptcp_log_handle, "%s - %lx: cellbytes is %lld\n",
361 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), mycellbytes);
362 *cellbytes = 0;
363 *allbytes = 0;
364 } else {
365 *cellbytes = mycellbytes;
366 *allbytes = myallbytes;
367 }
368 }
369
370 static void
mptcpstats_session_wrapup(struct mptses * mpte)371 mptcpstats_session_wrapup(struct mptses *mpte)
372 {
373 boolean_t cell = mpte->mpte_initial_cell;
374
375 switch (mpte->mpte_svctype) {
376 case MPTCP_SVCTYPE_HANDOVER:
377 if (mpte->mpte_flags & MPTE_FIRSTPARTY) {
378 tcpstat.tcps_mptcp_fp_handover_attempt++;
379
380 if (cell && mpte->mpte_handshake_success) {
381 tcpstat.tcps_mptcp_fp_handover_success_cell++;
382
383 if (mpte->mpte_used_wifi) {
384 tcpstat.tcps_mptcp_handover_wifi_from_cell++;
385 }
386 } else if (mpte->mpte_handshake_success) {
387 tcpstat.tcps_mptcp_fp_handover_success_wifi++;
388
389 if (mpte->mpte_used_cell) {
390 tcpstat.tcps_mptcp_handover_cell_from_wifi++;
391 }
392 }
393 } else {
394 tcpstat.tcps_mptcp_handover_attempt++;
395
396 if (cell && mpte->mpte_handshake_success) {
397 tcpstat.tcps_mptcp_handover_success_cell++;
398
399 if (mpte->mpte_used_wifi) {
400 tcpstat.tcps_mptcp_handover_wifi_from_cell++;
401 }
402 } else if (mpte->mpte_handshake_success) {
403 tcpstat.tcps_mptcp_handover_success_wifi++;
404
405 if (mpte->mpte_used_cell) {
406 tcpstat.tcps_mptcp_handover_cell_from_wifi++;
407 }
408 }
409 }
410
411 if (mpte->mpte_handshake_success) {
412 uint64_t cellbytes;
413 uint64_t allbytes;
414
415 mptcpstats_get_bytes(mpte, cell, &cellbytes, &allbytes);
416
417 tcpstat.tcps_mptcp_handover_cell_bytes += cellbytes;
418 tcpstat.tcps_mptcp_handover_all_bytes += allbytes;
419 }
420 break;
421 case MPTCP_SVCTYPE_INTERACTIVE:
422 if (mpte->mpte_flags & MPTE_FIRSTPARTY) {
423 tcpstat.tcps_mptcp_fp_interactive_attempt++;
424
425 if (mpte->mpte_handshake_success) {
426 tcpstat.tcps_mptcp_fp_interactive_success++;
427
428 if (!cell && mpte->mpte_used_cell) {
429 tcpstat.tcps_mptcp_interactive_cell_from_wifi++;
430 }
431 }
432 } else {
433 tcpstat.tcps_mptcp_interactive_attempt++;
434
435 if (mpte->mpte_handshake_success) {
436 tcpstat.tcps_mptcp_interactive_success++;
437
438 if (!cell && mpte->mpte_used_cell) {
439 tcpstat.tcps_mptcp_interactive_cell_from_wifi++;
440 }
441 }
442 }
443
444 if (mpte->mpte_handshake_success) {
445 uint64_t cellbytes;
446 uint64_t allbytes;
447
448 mptcpstats_get_bytes(mpte, cell, &cellbytes, &allbytes);
449
450 tcpstat.tcps_mptcp_interactive_cell_bytes += cellbytes;
451 tcpstat.tcps_mptcp_interactive_all_bytes += allbytes;
452 }
453 break;
454 case MPTCP_SVCTYPE_AGGREGATE:
455 if (mpte->mpte_flags & MPTE_FIRSTPARTY) {
456 tcpstat.tcps_mptcp_fp_aggregate_attempt++;
457
458 if (mpte->mpte_handshake_success) {
459 tcpstat.tcps_mptcp_fp_aggregate_success++;
460 }
461 } else {
462 tcpstat.tcps_mptcp_aggregate_attempt++;
463
464 if (mpte->mpte_handshake_success) {
465 tcpstat.tcps_mptcp_aggregate_success++;
466 }
467 }
468
469 if (mpte->mpte_handshake_success) {
470 uint64_t cellbytes;
471 uint64_t allbytes;
472
473 mptcpstats_get_bytes(mpte, cell, &cellbytes, &allbytes);
474
475 tcpstat.tcps_mptcp_aggregate_cell_bytes += cellbytes;
476 tcpstat.tcps_mptcp_aggregate_all_bytes += allbytes;
477 }
478 break;
479 }
480
481 if (cell && mpte->mpte_handshake_success && mpte->mpte_used_wifi) {
482 tcpstat.tcps_mptcp_back_to_wifi++;
483 }
484
485 if (mpte->mpte_triggered_cell) {
486 tcpstat.tcps_mptcp_triggered_cell++;
487 }
488 }
489
490 /*
491 * Destroy an MPTCP session.
492 */
493 static void
mptcp_session_destroy(struct mptses * mpte)494 mptcp_session_destroy(struct mptses *mpte)
495 {
496 struct mptcb *mp_tp = mpte->mpte_mptcb;
497
498 VERIFY(mp_tp != NULL);
499 VERIFY(TAILQ_EMPTY(&mpte->mpte_subflows) && mpte->mpte_numflows == 0);
500
501 mptcpstats_session_wrapup(mpte);
502 mptcp_unset_cellicon(mpte, NULL, mpte->mpte_cellicon_increments);
503 mptcp_flush_sopts(mpte);
504
505 if (mpte->mpte_itfinfo_size > MPTE_ITFINFO_SIZE) {
506 kfree_data_counted_by(mpte->mpte_itfinfo, mpte->mpte_itfinfo_size);
507 }
508 mpte->mpte_itfinfo = NULL;
509 mpte->mpte_itfinfo_size = 0;
510
511 mptcp_freeq(mp_tp);
512 m_freem_list(mpte->mpte_reinjectq);
513
514 os_log(mptcp_log_handle, "%s - %lx: Destroying session\n",
515 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte));
516 }
517
518 boolean_t
mptcp_ok_to_create_subflows(struct mptcb * mp_tp)519 mptcp_ok_to_create_subflows(struct mptcb *mp_tp)
520 {
521 return mp_tp->mpt_state >= MPTCPS_ESTABLISHED &&
522 mp_tp->mpt_state < MPTCPS_FIN_WAIT_1 &&
523 !(mp_tp->mpt_flags & MPTCPF_FALLBACK_TO_TCP);
524 }
525
526 static int
mptcp_synthesize_nat64(struct in6_addr * addr0,uint32_t len,const struct in_addr * addrv4_0)527 mptcp_synthesize_nat64(struct in6_addr *addr0, uint32_t len,
528 const struct in_addr *addrv4_0)
529 {
530 static const struct in6_addr well_known_prefix = {
531 .__u6_addr.__u6_addr8 = {0x00, 0x64, 0xff, 0x9b, 0x00, 0x00,
532 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
533 0x00, 0x00, 0x00, 0x00},
534 };
535 struct in6_addr *addr = addr0;
536 char *ptr = (char *)addr;
537 const struct in_addr *addrv4 = addrv4_0;
538 const char *ptrv4 = (const char *)addrv4;
539
540 if (IN_ZERONET(ntohl(addrv4->s_addr)) || // 0.0.0.0/8 Source hosts on local network
541 IN_LOOPBACK(ntohl(addrv4->s_addr)) || // 127.0.0.0/8 Loopback
542 IN_LINKLOCAL(ntohl(addrv4->s_addr)) || // 169.254.0.0/16 Link Local
543 IN_DS_LITE(ntohl(addrv4->s_addr)) || // 192.0.0.0/29 DS-Lite
544 IN_6TO4_RELAY_ANYCAST(ntohl(addrv4->s_addr)) || // 192.88.99.0/24 6to4 Relay Anycast
545 IN_MULTICAST(ntohl(addrv4->s_addr)) || // 224.0.0.0/4 Multicast
546 INADDR_BROADCAST == addrv4->s_addr) { // 255.255.255.255/32 Limited Broadcast
547 return -1;
548 }
549
550 /* Check for the well-known prefix */
551 if (len == NAT64_PREFIX_LEN_96 &&
552 IN6_ARE_ADDR_EQUAL(addr, &well_known_prefix)) {
553 if (IN_PRIVATE(ntohl(addrv4->s_addr)) || // 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 Private-Use
554 IN_SHARED_ADDRESS_SPACE(ntohl(addrv4->s_addr))) { // 100.64.0.0/10 Shared Address Space
555 return -1;
556 }
557 }
558
559 switch (len) {
560 case NAT64_PREFIX_LEN_96:
561 memcpy(ptr + 12, ptrv4, 4);
562 break;
563 case NAT64_PREFIX_LEN_64:
564 memcpy(ptr + 9, ptrv4, 4);
565 break;
566 case NAT64_PREFIX_LEN_56:
567 memcpy(ptr + 7, ptrv4, 1);
568 memcpy(ptr + 9, ptrv4 + 1, 3);
569 break;
570 case NAT64_PREFIX_LEN_48:
571 memcpy(ptr + 6, ptrv4, 2);
572 memcpy(ptr + 9, ptrv4 + 2, 2);
573 break;
574 case NAT64_PREFIX_LEN_40:
575 memcpy(ptr + 5, ptrv4, 3);
576 memcpy(ptr + 9, ptrv4 + 3, 1);
577 break;
578 case NAT64_PREFIX_LEN_32:
579 memcpy(ptr + 4, ptrv4, 4);
580 break;
581 default:
582 panic("NAT64-prefix len is wrong: %u", len);
583 }
584
585 return 0;
586 }
587
588 static void
mptcp_trigger_cell_bringup(struct mptses * mpte)589 mptcp_trigger_cell_bringup(struct mptses *mpte)
590 {
591 struct socket *mp_so = mptetoso(mpte);
592
593 if (!uuid_is_null(mpsotomppcb(mp_so)->necp_client_uuid)) {
594 uuid_string_t uuidstr;
595 int err;
596
597 socket_unlock(mp_so, 0);
598 err = necp_client_assert_bb_radio_manager(mpsotomppcb(mp_so)->necp_client_uuid,
599 TRUE);
600 socket_lock(mp_so, 0);
601
602 if (err == 0) {
603 mpte->mpte_triggered_cell = 1;
604 }
605
606 uuid_unparse_upper(mpsotomppcb(mp_so)->necp_client_uuid, uuidstr);
607 os_log_info(mptcp_log_handle, "%s - %lx: asked irat to bringup cell for uuid %s, err %d\n",
608 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), uuidstr, err);
609 } else {
610 os_log_info(mptcp_log_handle, "%s - %lx: UUID is already null\n",
611 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte));
612 }
613 }
614
615 static boolean_t
mptcp_subflow_disconnecting(struct mptsub * mpts)616 mptcp_subflow_disconnecting(struct mptsub *mpts)
617 {
618 if (mpts->mpts_socket->so_state & SS_ISDISCONNECTED) {
619 return true;
620 }
621
622 if (mpts->mpts_flags & (MPTSF_DISCONNECTING | MPTSF_DISCONNECTED | MPTSF_CLOSE_REQD)) {
623 return true;
624 }
625
626 if (sototcpcb(mpts->mpts_socket)->t_state == TCPS_CLOSED) {
627 return true;
628 }
629
630 return false;
631 }
632
633 /*
634 * In Handover mode, only create cell subflow if
635 * - Symptoms marked WiFi as weak:
636 * Here, if we are sending data, then we can check the RTO-state. That is a
637 * stronger signal of WiFi quality than the Symptoms indicator.
638 * If however we are not sending any data, the only thing we can do is guess
639 * and thus bring up Cell.
640 *
641 * - Symptoms marked WiFi as unknown:
642 * In this state we don't know what the situation is and thus remain
643 * conservative, only bringing up cell if there are retransmissions going on.
644 */
645 static boolean_t
mptcp_handover_use_cellular(struct mptses * mpte,struct tcpcb * tp)646 mptcp_handover_use_cellular(struct mptses *mpte, struct tcpcb *tp)
647 {
648 mptcp_wifi_quality_t wifi_quality = mptcp_wifi_quality_for_session(mpte);
649
650 if (wifi_quality == MPTCP_WIFI_QUALITY_GOOD) {
651 /* WiFi is good - don't use cell */
652 return false;
653 }
654
655 if (wifi_quality == MPTCP_WIFI_QUALITY_UNSURE) {
656 /*
657 * We are in unknown state, only use Cell if we have confirmed
658 * that WiFi is bad.
659 */
660 if (mptetoso(mpte)->so_snd.sb_cc != 0 && tp->t_rxtshift >= mptcp_fail_thresh * 2) {
661 return true;
662 } else {
663 return false;
664 }
665 }
666
667 if (wifi_quality == MPTCP_WIFI_QUALITY_BAD) {
668 /*
669 * WiFi is confirmed to be bad from Symptoms-Framework.
670 * If we are sending data, check the RTOs.
671 * Otherwise, be pessimistic and use Cell.
672 */
673 if (mptetoso(mpte)->so_snd.sb_cc != 0) {
674 if (tp->t_rxtshift >= mptcp_fail_thresh * 2) {
675 return true;
676 } else {
677 return false;
678 }
679 } else {
680 return true;
681 }
682 }
683
684 return false;
685 }
686
687 void
mptcp_check_subflows_and_add(struct mptses * mpte)688 mptcp_check_subflows_and_add(struct mptses *mpte)
689 {
690 struct mptcb *mp_tp = mpte->mpte_mptcb;
691 boolean_t cellular_viable = FALSE;
692 boolean_t want_cellular = TRUE;
693 uint32_t i;
694
695 if (!mptcp_ok_to_create_subflows(mp_tp)) {
696 os_log_debug(mptcp_log_handle, "%s - %lx: not a good time for subflows, state %u flags %#x",
697 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), mp_tp->mpt_state, mp_tp->mpt_flags);
698 return;
699 }
700
701 /* Just to see if we have an IP-address available */
702 if (mptcp_get_session_dst(mpte, false, false) == NULL) {
703 return;
704 }
705
706 for (i = 0; i < mpte->mpte_itfinfo_size; i++) {
707 boolean_t need_to_ask_symptoms = FALSE, found = FALSE;
708 struct mpt_itf_info *info;
709 struct sockaddr_in6 nat64pre;
710 struct sockaddr *dst;
711 struct mptsub *mpts;
712 struct ifnet *ifp;
713 uint32_t ifindex;
714
715 info = &mpte->mpte_itfinfo[i];
716
717 ifindex = info->ifindex;
718 if (ifindex == IFSCOPE_NONE) {
719 continue;
720 }
721
722 os_log(mptcp_log_handle, "%s - %lx: itf %u no support %u hasv4 %u has v6 %u hasnat64 %u\n",
723 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), info->ifindex, info->no_mptcp_support,
724 info->has_v4_conn, info->has_v6_conn, info->has_nat64_conn);
725
726 if (info->no_mptcp_support) {
727 continue;
728 }
729
730 ifnet_head_lock_shared();
731 ifp = ifindex2ifnet[ifindex];
732 ifnet_head_done();
733
734 if (ifp == NULL) {
735 continue;
736 }
737
738 if (IFNET_IS_CELLULAR(ifp)) {
739 cellular_viable = TRUE;
740
741 if (mpte->mpte_svctype == MPTCP_SVCTYPE_HANDOVER ||
742 mpte->mpte_svctype == MPTCP_SVCTYPE_PURE_HANDOVER) {
743 if (mptcp_wifi_quality_for_session(mpte) == MPTCP_WIFI_QUALITY_GOOD) {
744 continue;
745 }
746 }
747 }
748
749 TAILQ_FOREACH(mpts, &mpte->mpte_subflows, mpts_entry) {
750 const struct ifnet *subifp = sotoinpcb(mpts->mpts_socket)->inp_last_outifp;
751 struct tcpcb *tp = sototcpcb(mpts->mpts_socket);
752
753 if (subifp == NULL) {
754 continue;
755 }
756
757 /*
758 * If there is at least one functioning subflow on WiFi
759 * and we are checking for the cell interface, then
760 * we always need to ask symptoms for permission as
761 * cell is triggered even if WiFi is available.
762 */
763 if (!IFNET_IS_CELLULAR(subifp) &&
764 !mptcp_subflow_disconnecting(mpts) &&
765 IFNET_IS_CELLULAR(ifp)) {
766 need_to_ask_symptoms = TRUE;
767 }
768
769 if (mpte->mpte_svctype == MPTCP_SVCTYPE_HANDOVER || mpte->mpte_svctype == MPTCP_SVCTYPE_PURE_HANDOVER) {
770 os_log(mptcp_log_handle,
771 "%s - %lx: %s: cell %u wifi-state %d flags %#x rxt %u first-party %u sb_cc %u ifindex %u this %u rtt %u rttvar %u rto %u\n",
772 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte),
773 mpte->mpte_svctype == MPTCP_SVCTYPE_HANDOVER ? "handover" : "pure-handover",
774 IFNET_IS_CELLULAR(subifp),
775 mptcp_wifi_quality_for_session(mpte),
776 mpts->mpts_flags,
777 tp->t_rxtshift,
778 !!(mpte->mpte_flags & MPTE_FIRSTPARTY),
779 mptetoso(mpte)->so_snd.sb_cc,
780 ifindex, subifp->if_index,
781 tp->t_srtt >> TCP_RTT_SHIFT,
782 tp->t_rttvar >> TCP_RTTVAR_SHIFT,
783 tp->t_rxtcur);
784
785 if (!IFNET_IS_CELLULAR(subifp) &&
786 !mptcp_subflow_disconnecting(mpts) &&
787 (mpts->mpts_flags & MPTSF_CONNECTED) &&
788 !mptcp_handover_use_cellular(mpte, tp)) {
789 found = TRUE;
790
791 /* We found a proper subflow on WiFi - no need for cell */
792 want_cellular = FALSE;
793 break;
794 }
795 } else if (mpte->mpte_svctype == MPTCP_SVCTYPE_TARGET_BASED) {
796 uint64_t time_now = mach_continuous_time();
797
798 os_log(mptcp_log_handle,
799 "%s - %lx: target-based: %llu now %llu wifi quality %d cell %u sostat %#x mpts_flags %#x tcp-state %u\n",
800 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), mpte->mpte_time_target,
801 time_now, mptcp_wifi_quality_for_session(mpte),
802 IFNET_IS_CELLULAR(subifp), mpts->mpts_socket->so_state,
803 mpts->mpts_flags, sototcpcb(mpts->mpts_socket)->t_state);
804
805 if (!IFNET_IS_CELLULAR(subifp) &&
806 !mptcp_subflow_disconnecting(mpts) &&
807 (mpte->mpte_time_target == 0 ||
808 (int64_t)(mpte->mpte_time_target - time_now) > 0 ||
809 mptcp_wifi_quality_for_session(mpte) == MPTCP_WIFI_QUALITY_GOOD)) {
810 found = TRUE;
811
812 want_cellular = FALSE;
813 break;
814 }
815 }
816
817 if (subifp->if_index == ifindex &&
818 !mptcp_subflow_disconnecting(mpts)) {
819 /*
820 * We found a subflow on this interface.
821 * No need to create a new one.
822 */
823 found = TRUE;
824 break;
825 }
826 }
827
828 if (found) {
829 continue;
830 }
831
832 if (need_to_ask_symptoms &&
833 !(mpte->mpte_flags & MPTE_FIRSTPARTY) &&
834 !(mpte->mpte_flags & MPTE_ACCESS_GRANTED) &&
835 mptcp_developer_mode == 0) {
836 mptcp_ask_symptoms(mpte);
837 return;
838 }
839
840 dst = mptcp_get_session_dst(mpte, info->has_v6_conn, info->has_v4_conn);
841
842 if (dst->sa_family == AF_INET &&
843 !info->has_v4_conn && info->has_nat64_conn) {
844 struct ipv6_prefix nat64prefixes[NAT64_MAX_NUM_PREFIXES];
845 int error, j;
846
847 SOCKADDR_ZERO(&nat64pre, sizeof(struct sockaddr_in6));
848
849 error = ifnet_get_nat64prefix(ifp, nat64prefixes);
850 if (error) {
851 os_log_error(mptcp_log_handle, "%s - %lx: no NAT64-prefix on itf %s, error %d\n",
852 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), ifp->if_name, error);
853 continue;
854 }
855
856 for (j = 0; j < NAT64_MAX_NUM_PREFIXES; j++) {
857 if (nat64prefixes[j].prefix_len != 0) {
858 break;
859 }
860 }
861
862 VERIFY(j < NAT64_MAX_NUM_PREFIXES);
863
864 error = mptcp_synthesize_nat64(&nat64prefixes[j].ipv6_prefix,
865 nat64prefixes[j].prefix_len,
866 &SIN(dst)->sin_addr);
867 if (error != 0) {
868 os_log_error(mptcp_log_handle, "%s - %lx: cannot synthesize this addr\n",
869 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte));
870 continue;
871 }
872
873 memcpy(&nat64pre.sin6_addr,
874 &nat64prefixes[j].ipv6_prefix,
875 sizeof(nat64pre.sin6_addr));
876 nat64pre.sin6_len = sizeof(struct sockaddr_in6);
877 nat64pre.sin6_family = AF_INET6;
878 nat64pre.sin6_port = SIN(dst)->sin_port;
879 nat64pre.sin6_flowinfo = 0;
880 nat64pre.sin6_scope_id = 0;
881
882 dst = SA(&nat64pre);
883 }
884
885 if (dst->sa_family == AF_INET && !info->has_v4_conn) {
886 continue;
887 }
888 if (dst->sa_family == AF_INET6 && !info->has_v6_conn) {
889 continue;
890 }
891
892 mptcp_subflow_add(mpte, NULL, dst, ifindex, NULL);
893 }
894
895 if (!cellular_viable && want_cellular) {
896 /* Trigger Cell Bringup */
897 mptcp_trigger_cell_bringup(mpte);
898 }
899 }
900
901 static void
mptcp_remove_cell_subflows(struct mptses * mpte)902 mptcp_remove_cell_subflows(struct mptses *mpte)
903 {
904 struct mptsub *mpts, *tmpts;
905
906 TAILQ_FOREACH_SAFE(mpts, &mpte->mpte_subflows, mpts_entry, tmpts) {
907 const struct ifnet *ifp = sotoinpcb(mpts->mpts_socket)->inp_last_outifp;
908
909 if (ifp == NULL || !IFNET_IS_CELLULAR(ifp)) {
910 continue;
911 }
912
913 os_log(mptcp_log_handle, "%s - %lx: removing cell subflow\n",
914 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte));
915
916 soevent(mpts->mpts_socket, SO_FILT_HINT_LOCKED | SO_FILT_HINT_MUSTRST);
917 }
918
919 return;
920 }
921
922 static void
mptcp_remove_wifi_subflows(struct mptses * mpte)923 mptcp_remove_wifi_subflows(struct mptses *mpte)
924 {
925 struct mptsub *mpts, *tmpts;
926
927 TAILQ_FOREACH_SAFE(mpts, &mpte->mpte_subflows, mpts_entry, tmpts) {
928 const struct ifnet *ifp = sotoinpcb(mpts->mpts_socket)->inp_last_outifp;
929
930 if (ifp == NULL || IFNET_IS_CELLULAR(ifp)) {
931 continue;
932 }
933
934 os_log(mptcp_log_handle, "%s - %lx: removing wifi subflow\n",
935 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte));
936
937 soevent(mpts->mpts_socket, SO_FILT_HINT_LOCKED | SO_FILT_HINT_MUSTRST);
938 }
939
940 return;
941 }
942
943 static void
mptcp_pure_handover_subflows_remove(struct mptses * mpte)944 mptcp_pure_handover_subflows_remove(struct mptses *mpte)
945 {
946 mptcp_wifi_quality_t wifi_quality = mptcp_wifi_quality_for_session(mpte);
947 boolean_t found_working_wifi_subflow = false;
948 boolean_t found_working_cell_subflow = false;
949
950 struct mptsub *mpts;
951
952 /*
953 * Look for a subflow that is on a non-cellular interface in connected
954 * state.
955 *
956 * In that case, remove all cellular subflows.
957 *
958 * If however there is no connected subflow
959 */
960 TAILQ_FOREACH(mpts, &mpte->mpte_subflows, mpts_entry) {
961 const struct ifnet *ifp = sotoinpcb(mpts->mpts_socket)->inp_last_outifp;
962 struct socket *so;
963 struct tcpcb *tp;
964
965 if (ifp == NULL) {
966 continue;
967 }
968
969 so = mpts->mpts_socket;
970 tp = sototcpcb(so);
971
972 if (!(mpts->mpts_flags & MPTSF_CONNECTED) ||
973 tp->t_state != TCPS_ESTABLISHED ||
974 mptcp_subflow_disconnecting(mpts)) {
975 continue;
976 }
977
978 if (IFNET_IS_CELLULAR(ifp)) {
979 found_working_cell_subflow = true;
980 } else {
981 os_log_debug(mptcp_log_handle, "%s - %lx: rxt %u sb_cc %u wifi quality %d\n",
982 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), tp->t_rxtshift, mptetoso(mpte)->so_snd.sb_cc, wifi_quality);
983 if (!mptcp_handover_use_cellular(mpte, tp)) {
984 found_working_wifi_subflow = true;
985 }
986 }
987 }
988
989 /*
990 * Couldn't find a working subflow, let's not remove those on a cellular
991 * interface.
992 */
993 os_log_debug(mptcp_log_handle, "%s - %lx: Found Wi-Fi: %u Found Cellular %u",
994 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte),
995 found_working_wifi_subflow, found_working_cell_subflow);
996 if (!found_working_wifi_subflow && wifi_quality != MPTCP_WIFI_QUALITY_GOOD) {
997 if (found_working_cell_subflow) {
998 mptcp_remove_wifi_subflows(mpte);
999 }
1000 return;
1001 }
1002
1003 mptcp_remove_cell_subflows(mpte);
1004 }
1005
1006 static void
mptcp_handover_subflows_remove(struct mptses * mpte)1007 mptcp_handover_subflows_remove(struct mptses *mpte)
1008 {
1009 mptcp_wifi_quality_t wifi_quality = mptcp_wifi_quality_for_session(mpte);
1010 boolean_t found_working_subflow = false;
1011 struct mptsub *mpts;
1012
1013 /*
1014 * Look for a subflow that is on a non-cellular interface
1015 * and actually works (aka, no retransmission timeout).
1016 */
1017 TAILQ_FOREACH(mpts, &mpte->mpte_subflows, mpts_entry) {
1018 const struct ifnet *ifp = sotoinpcb(mpts->mpts_socket)->inp_last_outifp;
1019 struct socket *so;
1020 struct tcpcb *tp;
1021
1022 if (ifp == NULL || IFNET_IS_CELLULAR(ifp)) {
1023 continue;
1024 }
1025
1026 so = mpts->mpts_socket;
1027 tp = sototcpcb(so);
1028
1029 if (!(mpts->mpts_flags & MPTSF_CONNECTED) ||
1030 tp->t_state != TCPS_ESTABLISHED) {
1031 continue;
1032 }
1033
1034 os_log_debug(mptcp_log_handle, "%s - %lx: rxt %u sb_cc %u wifi quality %d\n",
1035 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), tp->t_rxtshift, mptetoso(mpte)->so_snd.sb_cc, wifi_quality);
1036
1037 if (!mptcp_handover_use_cellular(mpte, tp)) {
1038 found_working_subflow = true;
1039 break;
1040 }
1041 }
1042
1043 /*
1044 * Couldn't find a working subflow, let's not remove those on a cellular
1045 * interface.
1046 */
1047 if (!found_working_subflow) {
1048 return;
1049 }
1050
1051 mptcp_remove_cell_subflows(mpte);
1052 }
1053
1054 static void
mptcp_targetbased_subflows_remove(struct mptses * mpte)1055 mptcp_targetbased_subflows_remove(struct mptses *mpte)
1056 {
1057 uint64_t time_now = mach_continuous_time();
1058 struct mptsub *mpts;
1059
1060 if (mpte->mpte_time_target != 0 &&
1061 (int64_t)(mpte->mpte_time_target - time_now) <= 0 &&
1062 mptcp_wifi_quality_for_session(mpte) != MPTCP_WIFI_QUALITY_GOOD) {
1063 /* WiFi is bad and we are below the target - don't remove any subflows */
1064 return;
1065 }
1066
1067 TAILQ_FOREACH(mpts, &mpte->mpte_subflows, mpts_entry) {
1068 const struct ifnet *ifp = sotoinpcb(mpts->mpts_socket)->inp_last_outifp;
1069
1070 if (ifp == NULL || IFNET_IS_CELLULAR(ifp)) {
1071 continue;
1072 }
1073
1074 /* We have a functioning subflow on WiFi. No need for cell! */
1075 if (mpts->mpts_flags & MPTSF_CONNECTED &&
1076 !mptcp_subflow_disconnecting(mpts)) {
1077 mptcp_remove_cell_subflows(mpte);
1078 break;
1079 }
1080 }
1081 }
1082
1083 /*
1084 * Based on the MPTCP Service-type and the state of the subflows, we
1085 * will destroy subflows here.
1086 */
1087 void
mptcp_check_subflows_and_remove(struct mptses * mpte)1088 mptcp_check_subflows_and_remove(struct mptses *mpte)
1089 {
1090 if (!mptcp_ok_to_create_subflows(mpte->mpte_mptcb)) {
1091 return;
1092 }
1093
1094 socket_lock_assert_owned(mptetoso(mpte));
1095
1096 if (mpte->mpte_svctype == MPTCP_SVCTYPE_PURE_HANDOVER) {
1097 mptcp_pure_handover_subflows_remove(mpte);
1098 }
1099
1100 if (mpte->mpte_svctype == MPTCP_SVCTYPE_HANDOVER) {
1101 mptcp_handover_subflows_remove(mpte);
1102 }
1103
1104 if (mpte->mpte_svctype == MPTCP_SVCTYPE_TARGET_BASED) {
1105 mptcp_targetbased_subflows_remove(mpte);
1106 }
1107 }
1108
1109 static void
mptcp_remove_subflows(struct mptses * mpte)1110 mptcp_remove_subflows(struct mptses *mpte)
1111 {
1112 struct mptsub *mpts, *tmpts;
1113
1114 if (!mptcp_ok_to_create_subflows(mpte->mpte_mptcb)) {
1115 return;
1116 }
1117
1118 TAILQ_FOREACH_SAFE(mpts, &mpte->mpte_subflows, mpts_entry, tmpts) {
1119 const struct ifnet *ifp = sotoinpcb(mpts->mpts_socket)->inp_last_outifp;
1120 boolean_t found = false;
1121 uint32_t ifindex;
1122 uint32_t i;
1123
1124 if (mpts->mpts_flags & MPTSF_CLOSE_REQD) {
1125 mpts->mpts_flags &= ~MPTSF_CLOSE_REQD;
1126
1127 os_log(mptcp_log_handle, "%s - %lx: itf %u close_reqd last itf %d\n",
1128 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), mpts->mpts_ifscope,
1129 ifp ? ifp->if_index : -1);
1130 soevent(mpts->mpts_socket,
1131 SO_FILT_HINT_LOCKED | SO_FILT_HINT_NOSRCADDR);
1132
1133 continue;
1134 }
1135
1136 if (ifp == NULL && mpts->mpts_ifscope == IFSCOPE_NONE) {
1137 continue;
1138 }
1139
1140 if (ifp) {
1141 ifindex = ifp->if_index;
1142 } else {
1143 ifindex = mpts->mpts_ifscope;
1144 }
1145
1146 for (i = 0; i < mpte->mpte_itfinfo_size; i++) {
1147 if (mpte->mpte_itfinfo[i].ifindex == IFSCOPE_NONE) {
1148 continue;
1149 }
1150
1151 if (mpte->mpte_itfinfo[i].ifindex == ifindex) {
1152 if (mpts->mpts_dst.sa_family == AF_INET6 &&
1153 (mpte->mpte_itfinfo[i].has_v6_conn || mpte->mpte_itfinfo[i].has_nat64_conn)) {
1154 found = true;
1155 break;
1156 }
1157
1158 if (mpts->mpts_dst.sa_family == AF_INET &&
1159 mpte->mpte_itfinfo[i].has_v4_conn) {
1160 found = true;
1161 break;
1162 }
1163 }
1164 }
1165
1166 if (!found) {
1167 os_log(mptcp_log_handle, "%s - %lx: itf %u killing %#x\n",
1168 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte),
1169 ifindex, mpts->mpts_flags);
1170
1171 soevent(mpts->mpts_socket,
1172 SO_FILT_HINT_LOCKED | SO_FILT_HINT_NOSRCADDR);
1173 }
1174 }
1175 }
1176
1177 static void
mptcp_create_subflows(__unused void * arg)1178 mptcp_create_subflows(__unused void *arg)
1179 {
1180 struct mppcb *mpp;
1181
1182 /*
1183 * Start with clearing, because we might be processing connections
1184 * while a new event comes in.
1185 */
1186 if (OSTestAndClear(0x01, &mptcp_create_subflows_scheduled)) {
1187 os_log_error(mptcp_log_handle, "%s: bit was already cleared!\n", __func__);
1188 }
1189
1190 /* Iterate over all MPTCP connections */
1191
1192 lck_mtx_lock(&mtcbinfo.mppi_lock);
1193
1194 TAILQ_FOREACH(mpp, &mtcbinfo.mppi_pcbs, mpp_entry) {
1195 struct socket *mp_so = mpp->mpp_socket;
1196 struct mptses *mpte = mpp->mpp_pcbe;
1197
1198 socket_lock(mp_so, 1);
1199 if (!(mpp->mpp_flags & MPP_CREATE_SUBFLOWS) ||
1200 !(mpte->mpte_flags & MPTE_ITFINFO_INIT)) {
1201 socket_unlock(mp_so, 1);
1202 continue;
1203 }
1204
1205 VERIFY(mp_so->so_usecount > 0);
1206
1207 mpp->mpp_flags &= ~MPP_CREATE_SUBFLOWS;
1208
1209 mptcp_check_subflows_and_add(mpte);
1210 mptcp_remove_subflows(mpte);
1211
1212 mp_so->so_usecount--; /* See mptcp_sched_create_subflows */
1213 socket_unlock(mp_so, 1);
1214 }
1215
1216 lck_mtx_unlock(&mtcbinfo.mppi_lock);
1217 }
1218
1219 /*
1220 * We need this because we are coming from an NECP-event. This event gets posted
1221 * while holding NECP-locks. The creation of the subflow however leads us back
1222 * into NECP (e.g., to add the necp_cb and also from tcp_connect).
1223 * So, we would deadlock there as we already hold the NECP-lock.
1224 *
1225 * So, let's schedule this separately. It also gives NECP the chance to make
1226 * progress, without having to wait for MPTCP to finish its subflow creation.
1227 */
1228 void
mptcp_sched_create_subflows(struct mptses * mpte)1229 mptcp_sched_create_subflows(struct mptses *mpte)
1230 {
1231 struct mppcb *mpp = mpte->mpte_mppcb;
1232 struct mptcb *mp_tp = mpte->mpte_mptcb;
1233 struct socket *mp_so = mpp->mpp_socket;
1234
1235 if (!mptcp_ok_to_create_subflows(mp_tp)) {
1236 os_log_debug(mptcp_log_handle, "%s - %lx: not a good time for subflows, state %u flags %#x",
1237 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), mp_tp->mpt_state, mp_tp->mpt_flags);
1238 return;
1239 }
1240
1241 if (!(mpp->mpp_flags & MPP_CREATE_SUBFLOWS)) {
1242 mp_so->so_usecount++; /* To prevent it from being free'd in-between */
1243 mpp->mpp_flags |= MPP_CREATE_SUBFLOWS;
1244 }
1245
1246 if (OSTestAndSet(0x01, &mptcp_create_subflows_scheduled)) {
1247 return;
1248 }
1249
1250 /* Do the call in 100ms to allow NECP to schedule it on all sockets */
1251 timeout(mptcp_create_subflows, NULL, hz / 10);
1252 }
1253
1254 /*
1255 * Allocate an MPTCP socket option structure.
1256 */
1257 struct mptopt *
mptcp_sopt_alloc(void)1258 mptcp_sopt_alloc(void)
1259 {
1260 return zalloc_flags(mptopt_zone, Z_WAITOK | Z_ZERO);
1261 }
1262
1263 /*
1264 * Free an MPTCP socket option structure.
1265 */
1266 void
mptcp_sopt_free(struct mptopt * mpo)1267 mptcp_sopt_free(struct mptopt *mpo)
1268 {
1269 VERIFY(!(mpo->mpo_flags & MPOF_ATTACHED));
1270
1271 zfree(mptopt_zone, mpo);
1272 }
1273
1274 /*
1275 * Add a socket option to the MPTCP socket option list.
1276 */
1277 void
mptcp_sopt_insert(struct mptses * mpte,struct mptopt * mpo)1278 mptcp_sopt_insert(struct mptses *mpte, struct mptopt *mpo)
1279 {
1280 socket_lock_assert_owned(mptetoso(mpte));
1281 mpo->mpo_flags |= MPOF_ATTACHED;
1282 TAILQ_INSERT_TAIL(&mpte->mpte_sopts, mpo, mpo_entry);
1283 }
1284
1285 /*
1286 * Remove a socket option from the MPTCP socket option list.
1287 */
1288 void
mptcp_sopt_remove(struct mptses * mpte,struct mptopt * mpo)1289 mptcp_sopt_remove(struct mptses *mpte, struct mptopt *mpo)
1290 {
1291 socket_lock_assert_owned(mptetoso(mpte));
1292 VERIFY(mpo->mpo_flags & MPOF_ATTACHED);
1293 mpo->mpo_flags &= ~MPOF_ATTACHED;
1294 TAILQ_REMOVE(&mpte->mpte_sopts, mpo, mpo_entry);
1295 }
1296
1297 /*
1298 * Search for an existing <sopt_level,sopt_name> socket option.
1299 */
1300 struct mptopt *
mptcp_sopt_find(struct mptses * mpte,struct sockopt * sopt)1301 mptcp_sopt_find(struct mptses *mpte, struct sockopt *sopt)
1302 {
1303 struct mptopt *mpo;
1304
1305 socket_lock_assert_owned(mptetoso(mpte));
1306
1307 TAILQ_FOREACH(mpo, &mpte->mpte_sopts, mpo_entry) {
1308 if (mpo->mpo_level == sopt->sopt_level &&
1309 mpo->mpo_name == sopt->sopt_name) {
1310 break;
1311 }
1312 }
1313 return mpo;
1314 }
1315
1316 /*
1317 * Allocate a MPTCP subflow structure.
1318 */
1319 static struct mptsub *
mptcp_subflow_alloc(void)1320 mptcp_subflow_alloc(void)
1321 {
1322 return zalloc_flags(mptsub_zone, Z_WAITOK | Z_ZERO);
1323 }
1324
1325 /*
1326 * Deallocate a subflow structure, called when all of the references held
1327 * on it have been released. This implies that the subflow has been deleted.
1328 */
1329 static void
mptcp_subflow_free(struct mptsub * mpts)1330 mptcp_subflow_free(struct mptsub *mpts)
1331 {
1332 VERIFY(mpts->mpts_refcnt == 0);
1333 VERIFY(mpts->mpts_mpte == NULL);
1334 VERIFY(mpts->mpts_socket == NULL);
1335
1336 free_sockaddr(mpts->mpts_src);
1337
1338 zfree(mptsub_zone, mpts);
1339 }
1340
1341 static void
mptcp_subflow_addref(struct mptsub * mpts)1342 mptcp_subflow_addref(struct mptsub *mpts)
1343 {
1344 if (++mpts->mpts_refcnt == 0) {
1345 panic("%s: mpts %p wraparound refcnt", __func__, mpts);
1346 }
1347 /* NOTREACHED */
1348 }
1349
1350 static void
mptcp_subflow_remref(struct mptsub * mpts)1351 mptcp_subflow_remref(struct mptsub *mpts)
1352 {
1353 if (mpts->mpts_refcnt == 0) {
1354 panic("%s: mpts %p negative refcnt", __func__, mpts);
1355 /* NOTREACHED */
1356 }
1357 if (--mpts->mpts_refcnt > 0) {
1358 return;
1359 }
1360
1361 /* callee will unlock and destroy lock */
1362 mptcp_subflow_free(mpts);
1363 }
1364
1365 static void
mptcp_subflow_attach(struct mptses * mpte,struct mptsub * mpts,struct socket * so)1366 mptcp_subflow_attach(struct mptses *mpte, struct mptsub *mpts, struct socket *so)
1367 {
1368 struct socket *mp_so = mpte->mpte_mppcb->mpp_socket;
1369 struct tcpcb *tp = sototcpcb(so);
1370
1371 /*
1372 * From this moment on, the subflow is linked to the MPTCP-connection.
1373 * Locking,... happens now at the MPTCP-layer
1374 */
1375 tp->t_mptcb = mpte->mpte_mptcb;
1376 so->so_flags |= SOF_MP_SUBFLOW;
1377 mp_so->so_usecount++;
1378
1379 /*
1380 * Insert the subflow into the list, and associate the MPTCP PCB
1381 * as well as the the subflow socket. From this point on, removing
1382 * the subflow needs to be done via mptcp_subflow_del().
1383 */
1384 TAILQ_INSERT_TAIL(&mpte->mpte_subflows, mpts, mpts_entry);
1385 mpte->mpte_numflows++;
1386
1387 mpts->mpts_mpte = mpte;
1388 mpts->mpts_socket = so;
1389 tp->t_mpsub = mpts;
1390 mptcp_subflow_addref(mpts); /* for being in MPTCP subflow list */
1391 mptcp_subflow_addref(mpts); /* for subflow socket */
1392 }
1393
1394 static void
mptcp_subflow_necp_cb(void * handle,__unused int action,__unused uint32_t interface_index,uint32_t necp_flags,bool * viable)1395 mptcp_subflow_necp_cb(void *handle, __unused int action,
1396 __unused uint32_t interface_index,
1397 uint32_t necp_flags, bool *viable)
1398 {
1399 boolean_t low_power = !!(necp_flags & NECP_CLIENT_RESULT_FLAG_INTERFACE_LOW_POWER);
1400 struct inpcb *inp = (struct inpcb *)handle;
1401 struct socket *so = inp->inp_socket;
1402 struct mptsub *mpts;
1403 struct mptses *mpte;
1404
1405 if (low_power) {
1406 action = NECP_CLIENT_CBACTION_NONVIABLE;
1407 }
1408
1409 if (action != NECP_CLIENT_CBACTION_NONVIABLE) {
1410 return;
1411 }
1412
1413 /*
1414 * The socket is being garbage-collected. There is nothing to be done
1415 * here.
1416 */
1417 if (in_pcb_checkstate(inp, WNT_ACQUIRE, 0) == WNT_STOPUSING) {
1418 return;
1419 }
1420
1421 socket_lock(so, 1);
1422
1423 /* Check again after we acquired the lock. */
1424 if (in_pcb_checkstate(inp, WNT_RELEASE, 1) == WNT_STOPUSING) {
1425 goto out;
1426 }
1427
1428 mpte = tptomptp(sototcpcb(so))->mpt_mpte;
1429 mpts = sototcpcb(so)->t_mpsub;
1430
1431 os_log_debug(mptcp_log_handle, "%s - %lx: Subflow on itf %u became non-viable, power %u",
1432 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), mpts->mpts_ifscope, low_power);
1433
1434 mpts->mpts_flags |= MPTSF_CLOSE_REQD;
1435
1436 mptcp_sched_create_subflows(mpte);
1437
1438 if ((mpte->mpte_svctype == MPTCP_SVCTYPE_HANDOVER ||
1439 mpte->mpte_svctype == MPTCP_SVCTYPE_PURE_HANDOVER ||
1440 mpte->mpte_svctype == MPTCP_SVCTYPE_TARGET_BASED) &&
1441 viable != NULL) {
1442 *viable = 1;
1443 }
1444
1445 out:
1446 socket_unlock(so, 1);
1447 }
1448
1449 /*
1450 * Create an MPTCP subflow socket.
1451 */
1452 static int
mptcp_subflow_socreate(struct mptses * mpte,struct mptsub * mpts,int dom,struct socket ** so)1453 mptcp_subflow_socreate(struct mptses *mpte, struct mptsub *mpts, int dom,
1454 struct socket **so)
1455 {
1456 lck_mtx_t *subflow_mtx;
1457 struct mptopt smpo, *mpo, *tmpo;
1458 struct proc *p;
1459 struct socket *mp_so;
1460 struct mppcb *mpp;
1461 int error;
1462
1463 *so = NULL;
1464
1465 mp_so = mptetoso(mpte);
1466 mpp = mpsotomppcb(mp_so);
1467
1468 p = proc_find(mp_so->last_pid);
1469 if (p == PROC_NULL) {
1470 os_log_error(mptcp_log_handle, "%s - %lx: Couldn't find proc for pid %u\n",
1471 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), mp_so->last_pid);
1472
1473 mptcp_subflow_free(mpts);
1474 return ESRCH;
1475 }
1476
1477 /*
1478 * Create the subflow socket (multipath subflow, non-blocking.)
1479 *
1480 * This will cause SOF_MP_SUBFLOW socket flag to be set on the subflow
1481 * socket; it will be cleared when the socket is peeled off or closed.
1482 * It also indicates to the underlying TCP to handle MPTCP options.
1483 * A multipath subflow socket implies SS_NOFDREF state.
1484 */
1485
1486 /*
1487 * Unlock, because tcp_usr_attach ends up in in_pcballoc, which takes
1488 * the ipi-lock. We cannot hold the socket-lock at that point.
1489 */
1490 socket_unlock(mp_so, 0);
1491 error = socreate_internal(dom, so, SOCK_STREAM, IPPROTO_TCP, p,
1492 SOCF_MPTCP, PROC_NULL);
1493 socket_lock(mp_so, 0);
1494 if (error) {
1495 os_log_error(mptcp_log_handle, "%s - %lx: unable to create subflow socket error %d\n",
1496 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), error);
1497
1498 proc_rele(p);
1499
1500 mptcp_subflow_free(mpts);
1501 return error;
1502 }
1503
1504 /*
1505 * We need to protect the setting of SOF_MP_SUBFLOW with a lock, because
1506 * this marks the moment of lock-switch from the TCP-lock to the MPTCP-lock.
1507 * Which is why we also need to get the lock with pr_getlock, as after
1508 * setting the flag, socket_unlock will work on the MPTCP-level lock.
1509 */
1510 subflow_mtx = ((*so)->so_proto->pr_getlock)(*so, 0);
1511 lck_mtx_lock(subflow_mtx);
1512
1513 /*
1514 * Must be the first thing we do, to make sure all pointers for this
1515 * subflow are set.
1516 */
1517 mptcp_subflow_attach(mpte, mpts, *so);
1518
1519 /*
1520 * A multipath subflow socket is used internally in the kernel,
1521 * therefore it does not have a file desciptor associated by
1522 * default.
1523 */
1524 (*so)->so_state |= SS_NOFDREF;
1525
1526 lck_mtx_unlock(subflow_mtx);
1527
1528 /* prevent the socket buffers from being compressed */
1529 (*so)->so_rcv.sb_flags |= SB_NOCOMPRESS;
1530 (*so)->so_snd.sb_flags |= SB_NOCOMPRESS;
1531
1532 /* Inherit preconnect and TFO data flags */
1533 if (mp_so->so_flags1 & SOF1_PRECONNECT_DATA) {
1534 (*so)->so_flags1 |= SOF1_PRECONNECT_DATA;
1535 }
1536 if (mp_so->so_flags1 & SOF1_DATA_IDEMPOTENT) {
1537 (*so)->so_flags1 |= SOF1_DATA_IDEMPOTENT;
1538 }
1539 if (mp_so->so_flags1 & SOF1_DATA_AUTHENTICATED) {
1540 (*so)->so_flags1 |= SOF1_DATA_AUTHENTICATED;
1541 }
1542
1543 /* Inherit uuid and create the related flow. */
1544 if (!uuid_is_null(mpp->necp_client_uuid)) {
1545 struct mptcb *mp_tp = mpte->mpte_mptcb;
1546
1547 sotoinpcb(*so)->necp_cb = mptcp_subflow_necp_cb;
1548
1549 /*
1550 * A note on the unlock: With MPTCP, we do multiple times a
1551 * necp_client_register_socket_flow. This is problematic,
1552 * because now the lock-ordering guarantee (first necp-locks,
1553 * then socket-locks) is no more respected. So, we need to
1554 * unlock here.
1555 */
1556 socket_unlock(mp_so, 0);
1557 error = necp_client_register_socket_flow(mp_so->last_pid,
1558 mpp->necp_client_uuid, sotoinpcb(*so));
1559 socket_lock(mp_so, 0);
1560
1561 if (error) {
1562 os_log_error(mptcp_log_handle, "%s - %lx: necp_client_register_socket_flow failed with error %d\n",
1563 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), error);
1564
1565 goto out_err;
1566 }
1567
1568 /* Possible state-change during the unlock above */
1569 if (mp_tp->mpt_state >= MPTCPS_TIME_WAIT ||
1570 (mp_tp->mpt_flags & MPTCPF_FALLBACK_TO_TCP)) {
1571 os_log_error(mptcp_log_handle, "%s - %lx: state changed during unlock: %u flags %#x\n",
1572 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte),
1573 mp_tp->mpt_state, mp_tp->mpt_flags);
1574
1575 error = EINVAL;
1576 goto out_err;
1577 }
1578
1579 uuid_copy(sotoinpcb(*so)->necp_client_uuid, mpp->necp_client_uuid);
1580 }
1581
1582 if (mpp->inp_necp_attributes.inp_domain != NULL) {
1583 char *buffer = NULL;
1584 size_t string_size = strlen(mpp->inp_necp_attributes.inp_domain);
1585 buffer = kalloc_data(string_size + 1, Z_WAITOK | Z_ZERO);
1586 if (buffer != NULL) {
1587 sotoinpcb(*so)->inp_necp_attributes.inp_domain = strlcpy_ret(buffer, mpp->inp_necp_attributes.inp_domain, string_size + 1);
1588 } else {
1589 sotoinpcb(*so)->inp_necp_attributes.inp_domain = NULL;
1590 }
1591 }
1592 if (mpp->inp_necp_attributes.inp_account != NULL) {
1593 char *buffer = NULL;
1594 size_t string_size = strlen(mpp->inp_necp_attributes.inp_account);
1595 buffer = kalloc_data(string_size + 1, Z_WAITOK | Z_ZERO);
1596 if (buffer != NULL) {
1597 sotoinpcb(*so)->inp_necp_attributes.inp_account = strlcpy_ret(buffer, mpp->inp_necp_attributes.inp_account, string_size + 1);
1598 } else {
1599 sotoinpcb(*so)->inp_necp_attributes.inp_account = NULL;
1600 }
1601 }
1602
1603 if (mpp->inp_necp_attributes.inp_domain_owner != NULL) {
1604 char *buffer = NULL;
1605 size_t string_size = strlen(mpp->inp_necp_attributes.inp_domain_owner);
1606 buffer = kalloc_data(string_size + 1, Z_WAITOK | Z_ZERO);
1607 if (buffer != NULL) {
1608 sotoinpcb(*so)->inp_necp_attributes.inp_domain_owner = strlcpy_ret(buffer, mpp->inp_necp_attributes.inp_domain_owner, string_size + 1);
1609 } else {
1610 sotoinpcb(*so)->inp_necp_attributes.inp_domain_owner = NULL;
1611 }
1612 }
1613
1614 if (mpp->inp_necp_attributes.inp_tracker_domain != NULL) {
1615 char *buffer = NULL;
1616 size_t string_size = strlen(mpp->inp_necp_attributes.inp_tracker_domain);
1617 buffer = kalloc_data(string_size + 1, Z_WAITOK | Z_ZERO);
1618 if (buffer != NULL) {
1619 sotoinpcb(*so)->inp_necp_attributes.inp_tracker_domain = strlcpy_ret(buffer, mpp->inp_necp_attributes.inp_tracker_domain, string_size + 1);
1620 } else {
1621 sotoinpcb(*so)->inp_necp_attributes.inp_tracker_domain = NULL;
1622 }
1623 }
1624
1625 /* Needs to happen prior to the delegation! */
1626 (*so)->last_pid = mp_so->last_pid;
1627
1628 if (mp_so->so_flags & SOF_DELEGATED) {
1629 if (mpte->mpte_epid) {
1630 error = so_set_effective_pid(*so, mpte->mpte_epid, p, false);
1631 if (error) {
1632 os_log_error(mptcp_log_handle, "%s - %lx: so_set_effective_pid failed with error %d\n",
1633 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), error);
1634 goto out_err;
1635 }
1636 }
1637 if (!uuid_is_null(mpte->mpte_euuid)) {
1638 error = so_set_effective_uuid(*so, mpte->mpte_euuid, p, false);
1639 if (error) {
1640 os_log_error(mptcp_log_handle, "%s - %lx: so_set_effective_uuid failed with error %d\n",
1641 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), error);
1642 goto out_err;
1643 }
1644 }
1645 }
1646
1647 /* inherit the other socket options */
1648 bzero(&smpo, sizeof(smpo));
1649 smpo.mpo_flags |= MPOF_SUBFLOW_OK;
1650 smpo.mpo_level = SOL_SOCKET;
1651 smpo.mpo_intval = 1;
1652
1653 /* disable SIGPIPE */
1654 smpo.mpo_name = SO_NOSIGPIPE;
1655 if ((error = mptcp_subflow_sosetopt(mpte, mpts, &smpo)) != 0) {
1656 goto out_err;
1657 }
1658
1659 /* find out if the subflow's source address goes away */
1660 smpo.mpo_name = SO_NOADDRERR;
1661 if ((error = mptcp_subflow_sosetopt(mpte, mpts, &smpo)) != 0) {
1662 goto out_err;
1663 }
1664
1665 if (mpte->mpte_mptcb->mpt_state >= MPTCPS_ESTABLISHED) {
1666 /*
1667 * On secondary subflows we might need to set the cell-fallback
1668 * flag (see conditions in mptcp_subflow_sosetopt).
1669 */
1670 smpo.mpo_level = SOL_SOCKET;
1671 smpo.mpo_name = SO_MARK_CELLFALLBACK;
1672 smpo.mpo_intval = 1;
1673 if ((error = mptcp_subflow_sosetopt(mpte, mpts, &smpo)) != 0) {
1674 goto out_err;
1675 }
1676 }
1677
1678 /* replay setsockopt(2) on the subflow sockets for eligible options */
1679 TAILQ_FOREACH_SAFE(mpo, &mpte->mpte_sopts, mpo_entry, tmpo) {
1680 int interim;
1681
1682 if (!(mpo->mpo_flags & MPOF_SUBFLOW_OK)) {
1683 continue;
1684 }
1685
1686 /*
1687 * Skip those that are handled internally; these options
1688 * should not have been recorded and marked with the
1689 * MPOF_SUBFLOW_OK by mptcp_setopt(), but just in case.
1690 */
1691 if (mpo->mpo_level == SOL_SOCKET &&
1692 (mpo->mpo_name == SO_NOSIGPIPE ||
1693 mpo->mpo_name == SO_NOADDRERR ||
1694 mpo->mpo_name == SO_KEEPALIVE)) {
1695 continue;
1696 }
1697
1698 interim = (mpo->mpo_flags & MPOF_INTERIM);
1699 if (mptcp_subflow_sosetopt(mpte, mpts, mpo) != 0 && interim) {
1700 os_log_error(mptcp_log_handle, "%s - %lx: sopt %s val %d interim record removed\n",
1701 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte),
1702 mptcp_sopt2str(mpo->mpo_level, mpo->mpo_name),
1703 mpo->mpo_intval);
1704 mptcp_sopt_remove(mpte, mpo);
1705 mptcp_sopt_free(mpo);
1706 continue;
1707 }
1708 }
1709
1710 /*
1711 * We need to receive everything that the subflow socket has,
1712 * so use a customized socket receive function. We will undo
1713 * this when the socket is peeled off or closed.
1714 */
1715 switch (dom) {
1716 case PF_INET:
1717 (*so)->so_proto = &mptcp_subflow_protosw;
1718 break;
1719 case PF_INET6:
1720 (*so)->so_proto = (struct protosw *)&mptcp_subflow_protosw6;
1721 break;
1722 default:
1723 VERIFY(0);
1724 /* NOTREACHED */
1725 }
1726
1727 proc_rele(p);
1728
1729 DTRACE_MPTCP3(subflow__create, struct mptses *, mpte,
1730 int, dom, int, error);
1731
1732 return 0;
1733
1734 out_err:
1735 mptcp_subflow_abort(mpts, error);
1736
1737 proc_rele(p);
1738
1739 return error;
1740 }
1741
1742 /*
1743 * Close an MPTCP subflow socket.
1744 *
1745 * Note that this may be called on an embryonic subflow, and the only
1746 * thing that is guaranteed valid is the protocol-user request.
1747 */
1748 static void
mptcp_subflow_soclose(struct mptsub * mpts)1749 mptcp_subflow_soclose(struct mptsub *mpts)
1750 {
1751 struct socket *so = mpts->mpts_socket;
1752
1753 if (mpts->mpts_flags & MPTSF_CLOSED) {
1754 return;
1755 }
1756
1757 VERIFY(so != NULL);
1758 VERIFY(so->so_flags & SOF_MP_SUBFLOW);
1759 VERIFY((so->so_state & (SS_NBIO | SS_NOFDREF)) == (SS_NBIO | SS_NOFDREF));
1760
1761 DTRACE_MPTCP5(subflow__close, struct mptsub *, mpts,
1762 struct socket *, so,
1763 struct sockbuf *, &so->so_rcv,
1764 struct sockbuf *, &so->so_snd,
1765 struct mptses *, mpts->mpts_mpte);
1766
1767 mpts->mpts_flags |= MPTSF_CLOSED;
1768
1769 if (so->so_retaincnt == 0) {
1770 soclose_locked(so);
1771
1772 return;
1773 } else {
1774 VERIFY(so->so_usecount > 0);
1775 so->so_usecount--;
1776 }
1777
1778 return;
1779 }
1780
1781 static void
mptcp_attach_to_subf(struct socket * so,struct mptcb * mp_tp,uint8_t addr_id)1782 mptcp_attach_to_subf(struct socket *so, struct mptcb *mp_tp, uint8_t addr_id)
1783 {
1784 struct tcpcb *tp = sototcpcb(so);
1785 struct mptcp_subf_auth_entry *sauth_entry;
1786
1787 /*
1788 * The address ID of the first flow is implicitly 0.
1789 */
1790 if (mp_tp->mpt_state == MPTCPS_CLOSED) {
1791 tp->t_local_aid = 0;
1792 } else {
1793 tp->t_local_aid = addr_id;
1794 tp->t_mpflags |= (TMPF_PREESTABLISHED | TMPF_JOINED_FLOW);
1795 so->so_flags |= SOF_MP_SEC_SUBFLOW;
1796 }
1797 sauth_entry = zalloc(mpt_subauth_zone);
1798 sauth_entry->msae_laddr_id = tp->t_local_aid;
1799 sauth_entry->msae_raddr_id = 0;
1800 sauth_entry->msae_raddr_rand = 0;
1801 try_again:
1802 sauth_entry->msae_laddr_rand = RandomULong();
1803 if (sauth_entry->msae_laddr_rand == 0) {
1804 goto try_again;
1805 }
1806 LIST_INSERT_HEAD(&mp_tp->mpt_subauth_list, sauth_entry, msae_next);
1807 }
1808
1809 static void
mptcp_detach_mptcb_from_subf(struct mptcb * mp_tp,struct socket * so)1810 mptcp_detach_mptcb_from_subf(struct mptcb *mp_tp, struct socket *so)
1811 {
1812 struct mptcp_subf_auth_entry *sauth_entry;
1813 struct tcpcb *tp = NULL;
1814 int found = 0;
1815
1816 tp = sototcpcb(so);
1817 if (tp == NULL) {
1818 return;
1819 }
1820
1821 LIST_FOREACH(sauth_entry, &mp_tp->mpt_subauth_list, msae_next) {
1822 if (sauth_entry->msae_laddr_id == tp->t_local_aid) {
1823 found = 1;
1824 break;
1825 }
1826 }
1827 if (found) {
1828 LIST_REMOVE(sauth_entry, msae_next);
1829 }
1830
1831 if (found) {
1832 zfree(mpt_subauth_zone, sauth_entry);
1833 }
1834 }
1835
1836 /*
1837 * Connect an MPTCP subflow socket.
1838 *
1839 * Note that in the pending connect case, the subflow socket may have been
1840 * bound to an interface and/or a source IP address which may no longer be
1841 * around by the time this routine is called; in that case the connect attempt
1842 * will most likely fail.
1843 */
1844 static int
mptcp_subflow_soconnectx(struct mptses * mpte,struct mptsub * mpts)1845 mptcp_subflow_soconnectx(struct mptses *mpte, struct mptsub *mpts)
1846 {
1847 char dbuf[MAX_IPv6_STR_LEN];
1848 struct socket *mp_so, *so;
1849 struct mptcb *mp_tp;
1850 struct sockaddr *dst;
1851 struct proc *p;
1852 int af, error, dport;
1853
1854 mp_so = mptetoso(mpte);
1855 mp_tp = mpte->mpte_mptcb;
1856 so = mpts->mpts_socket;
1857 af = mpts->mpts_dst.sa_family;
1858 dst = &mpts->mpts_dst;
1859
1860 VERIFY((mpts->mpts_flags & (MPTSF_CONNECTING | MPTSF_CONNECTED)) == MPTSF_CONNECTING);
1861 VERIFY(mpts->mpts_socket != NULL);
1862 VERIFY(af == AF_INET || af == AF_INET6);
1863
1864 if (af == AF_INET) {
1865 inet_ntop(af, &SIN(dst)->sin_addr.s_addr, dbuf, sizeof(dbuf));
1866 dport = ntohs(SIN(dst)->sin_port);
1867 } else {
1868 inet_ntop(af, &SIN6(dst)->sin6_addr, dbuf, sizeof(dbuf));
1869 dport = ntohs(SIN6(dst)->sin6_port);
1870 }
1871
1872 os_log(mptcp_log_handle,
1873 "%s - %lx: ifindex %u dst %s:%d pended %u\n", __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte),
1874 mpts->mpts_ifscope, dbuf, dport, !!(mpts->mpts_flags & MPTSF_CONNECT_PENDING));
1875
1876 p = proc_find(mp_so->last_pid);
1877 if (p == PROC_NULL) {
1878 os_log_error(mptcp_log_handle, "%s - %lx: Couldn't find proc for pid %u\n",
1879 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), mp_so->last_pid);
1880
1881 return ESRCH;
1882 }
1883
1884 mpts->mpts_flags &= ~MPTSF_CONNECT_PENDING;
1885
1886 mptcp_attach_to_subf(so, mpte->mpte_mptcb, mpte->mpte_addrid_last);
1887
1888 /* connect the subflow socket */
1889 error = soconnectxlocked(so, mpts->mpts_src, &mpts->mpts_dst,
1890 p, mpts->mpts_ifscope,
1891 mpte->mpte_associd, NULL, 0, NULL, 0, NULL, NULL);
1892
1893 mpts->mpts_iss = sototcpcb(so)->iss;
1894
1895 /* See tcp_connect_complete */
1896 if (mp_tp->mpt_state < MPTCPS_ESTABLISHED &&
1897 (mp_so->so_flags1 & SOF1_PRECONNECT_DATA)) {
1898 mp_tp->mpt_sndwnd = sototcpcb(so)->snd_wnd;
1899 }
1900
1901 /* Allocate a unique address id per subflow */
1902 mpte->mpte_addrid_last++;
1903 if (mpte->mpte_addrid_last == 0) {
1904 mpte->mpte_addrid_last++;
1905 }
1906
1907 proc_rele(p);
1908
1909 DTRACE_MPTCP3(subflow__connect, struct mptses *, mpte,
1910 struct mptsub *, mpts, int, error);
1911 if (error) {
1912 os_log_error(mptcp_log_handle, "%s - %lx: connectx failed with error %d ifscope %u\n",
1913 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), error, mpts->mpts_ifscope);
1914 }
1915
1916 return error;
1917 }
1918
1919 static int
mptcp_adj_rmap(struct socket * so,struct mbuf * m,int off,uint64_t dsn,uint32_t rseq,uint16_t dlen,uint8_t dfin)1920 mptcp_adj_rmap(struct socket *so, struct mbuf *m, int off, uint64_t dsn,
1921 uint32_t rseq, uint16_t dlen, uint8_t dfin)
1922 {
1923 struct mptsub *mpts = sototcpcb(so)->t_mpsub;
1924
1925 if (m_pktlen(m) == 0) {
1926 return 0;
1927 }
1928
1929 if (!(m->m_flags & M_PKTHDR)) {
1930 return 0;
1931 }
1932
1933 if (m->m_pkthdr.pkt_flags & PKTF_MPTCP) {
1934 if (off && (dsn != m->m_pkthdr.mp_dsn ||
1935 rseq != m->m_pkthdr.mp_rseq ||
1936 dlen != m->m_pkthdr.mp_rlen ||
1937 dfin != !!(m->m_pkthdr.pkt_flags & PKTF_MPTCP_DFIN))) {
1938 os_log_error(mptcp_log_handle, "%s - %lx: Received incorrect second mapping: DSN: %u - %u , SSN: %u - %u, DLEN: %u - %u, DFIN: %u - %u\n",
1939 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpts->mpts_mpte),
1940 (uint32_t)dsn, (uint32_t)m->m_pkthdr.mp_dsn,
1941 rseq, m->m_pkthdr.mp_rseq,
1942 dlen, m->m_pkthdr.mp_rlen,
1943 dfin, !!(m->m_pkthdr.pkt_flags & PKTF_MPTCP_DFIN));
1944
1945 soevent(mpts->mpts_socket, SO_FILT_HINT_LOCKED | SO_FILT_HINT_MUSTRST);
1946 return -1;
1947 }
1948 }
1949
1950 /* If mbuf is beyond right edge of the mapping, we need to split */
1951 if (m_pktlen(m) > dlen - dfin - off) {
1952 struct mbuf *new = m_split(m, dlen - dfin - off, M_DONTWAIT);
1953 if (new == NULL) {
1954 os_log_error(mptcp_log_handle, "%s - %lx: m_split failed dlen %u dfin %u off %d pktlen %d, killing subflow %d",
1955 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpts->mpts_mpte),
1956 dlen, dfin, off, m_pktlen(m),
1957 mpts->mpts_connid);
1958
1959 soevent(mpts->mpts_socket, SO_FILT_HINT_LOCKED | SO_FILT_HINT_MUSTRST);
1960 return -1;
1961 }
1962
1963 m->m_next = new;
1964 sballoc(&so->so_rcv, new);
1965 /* Undo, as sballoc will add to it as well */
1966 so->so_rcv.sb_cc -= new->m_len;
1967
1968 if (so->so_rcv.sb_mbtail == m) {
1969 so->so_rcv.sb_mbtail = new;
1970 }
1971 }
1972
1973 m->m_pkthdr.pkt_flags |= PKTF_MPTCP;
1974 m->m_pkthdr.mp_dsn = dsn + off;
1975 m->m_pkthdr.mp_rseq = rseq + off;
1976 VERIFY(m_pktlen(m) < UINT16_MAX);
1977 m->m_pkthdr.mp_rlen = (uint16_t)m_pktlen(m);
1978
1979 /* Only put the DATA_FIN-flag on the last mbuf of this mapping */
1980 if (dfin) {
1981 if (m->m_pkthdr.mp_dsn + m->m_pkthdr.mp_rlen < dsn + dlen - dfin) {
1982 m->m_pkthdr.pkt_flags &= ~PKTF_MPTCP_DFIN;
1983 } else {
1984 m->m_pkthdr.pkt_flags |= PKTF_MPTCP_DFIN;
1985 }
1986 }
1987
1988
1989 mpts->mpts_flags |= MPTSF_FULLY_ESTABLISHED;
1990
1991 return 0;
1992 }
1993
1994 /*
1995 * Update the pid, upid, uuid of the subflow so, based on parent so
1996 */
1997 static void
mptcp_update_last_owner(struct socket * so,struct socket * mp_so)1998 mptcp_update_last_owner(struct socket *so, struct socket *mp_so)
1999 {
2000 if (so->last_pid != mp_so->last_pid ||
2001 so->last_upid != mp_so->last_upid) {
2002 so->last_upid = mp_so->last_upid;
2003 so->last_pid = mp_so->last_pid;
2004 uuid_copy(so->last_uuid, mp_so->last_uuid);
2005 }
2006 so_update_policy(so);
2007 }
2008
2009 /*
2010 * MPTCP subflow socket receive routine, derived from soreceive().
2011 */
2012 static int
mptcp_subflow_soreceive(struct socket * so,struct sockaddr ** psa,struct uio * uio,struct mbuf ** mp0,struct mbuf ** controlp,int * flagsp)2013 mptcp_subflow_soreceive(struct socket *so, struct sockaddr **psa,
2014 struct uio *uio, struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2015 {
2016 #pragma unused(uio)
2017 struct socket *mp_so;
2018 struct mptses *mpte;
2019 struct mptcb *mp_tp;
2020 int flags, error = 0;
2021 struct mbuf *m, **mp = mp0;
2022 struct tcpcb *tp = sototcpcb(so);
2023
2024 mpte = tptomptp(sototcpcb(so))->mpt_mpte;
2025 mp_so = mptetoso(mpte);
2026 mp_tp = mpte->mpte_mptcb;
2027
2028 VERIFY(so->so_proto->pr_flags & PR_CONNREQUIRED);
2029
2030 #ifdef MORE_LOCKING_DEBUG
2031 if (so->so_usecount == 1) {
2032 panic("%s: so=%x no other reference on socket", __func__, so);
2033 /* NOTREACHED */
2034 }
2035 #endif
2036 /*
2037 * We return all that is there in the subflow's socket receive buffer
2038 * to the MPTCP layer, so we require that the caller passes in the
2039 * expected parameters.
2040 */
2041 if (mp == NULL || controlp != NULL) {
2042 return EINVAL;
2043 }
2044
2045 *mp = NULL;
2046 if (psa != NULL) {
2047 *psa = NULL;
2048 }
2049 if (flagsp != NULL) {
2050 flags = *flagsp & ~MSG_EOR;
2051 } else {
2052 flags = 0;
2053 }
2054
2055 if (flags & (MSG_PEEK | MSG_OOB | MSG_NEEDSA | MSG_WAITALL | MSG_WAITSTREAM)) {
2056 return EOPNOTSUPP;
2057 }
2058
2059 flags |= (MSG_DONTWAIT | MSG_NBIO);
2060
2061 /*
2062 * If a recv attempt is made on a previously-accepted socket
2063 * that has been marked as inactive (disconnected), reject
2064 * the request.
2065 */
2066 if (so->so_flags & SOF_DEFUNCT) {
2067 struct sockbuf *sb = &so->so_rcv;
2068
2069 error = ENOTCONN;
2070 /*
2071 * This socket should have been disconnected and flushed
2072 * prior to being returned from sodefunct(); there should
2073 * be no data on its receive list, so panic otherwise.
2074 */
2075 if (so->so_state & SS_DEFUNCT) {
2076 sb_empty_assert(sb, __func__);
2077 }
2078 return error;
2079 }
2080
2081 /*
2082 * See if the socket has been closed (SS_NOFDREF|SS_CANTRCVMORE)
2083 * and if so just return to the caller. This could happen when
2084 * soreceive() is called by a socket upcall function during the
2085 * time the socket is freed. The socket buffer would have been
2086 * locked across the upcall, therefore we cannot put this thread
2087 * to sleep (else we will deadlock) or return EWOULDBLOCK (else
2088 * we may livelock), because the lock on the socket buffer will
2089 * only be released when the upcall routine returns to its caller.
2090 * Because the socket has been officially closed, there can be
2091 * no further read on it.
2092 *
2093 * A multipath subflow socket would have its SS_NOFDREF set by
2094 * default, so check for SOF_MP_SUBFLOW socket flag; when the
2095 * socket is closed for real, SOF_MP_SUBFLOW would be cleared.
2096 */
2097 if ((so->so_state & (SS_NOFDREF | SS_CANTRCVMORE)) ==
2098 (SS_NOFDREF | SS_CANTRCVMORE) && !(so->so_flags & SOF_MP_SUBFLOW)) {
2099 return 0;
2100 }
2101
2102 /*
2103 * For consistency with soreceive() semantics, we need to obey
2104 * SB_LOCK in case some other code path has locked the buffer.
2105 */
2106 error = sblock(&so->so_rcv, 0);
2107 if (error != 0) {
2108 return error;
2109 }
2110
2111 m = so->so_rcv.sb_mb;
2112 if (m == NULL) {
2113 /*
2114 * Panic if we notice inconsistencies in the socket's
2115 * receive list; both sb_mb and sb_cc should correctly
2116 * reflect the contents of the list, otherwise we may
2117 * end up with false positives during select() or poll()
2118 * which could put the application in a bad state.
2119 */
2120 SB_MB_CHECK(&so->so_rcv);
2121
2122 if (so->so_error != 0) {
2123 error = so->so_error;
2124 so->so_error = 0;
2125 goto release;
2126 }
2127
2128 if (so->so_state & SS_CANTRCVMORE) {
2129 goto release;
2130 }
2131
2132 if (!(so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING))) {
2133 error = ENOTCONN;
2134 goto release;
2135 }
2136
2137 /*
2138 * MSG_DONTWAIT is implicitly defined and this routine will
2139 * never block, so return EWOULDBLOCK when there is nothing.
2140 */
2141 error = EWOULDBLOCK;
2142 goto release;
2143 }
2144
2145 mptcp_update_last_owner(so, mp_so);
2146
2147 SBLASTRECORDCHK(&so->so_rcv, "mptcp_subflow_soreceive 1");
2148 SBLASTMBUFCHK(&so->so_rcv, "mptcp_subflow_soreceive 1");
2149
2150 while (m != NULL) {
2151 int dlen = 0, error_out = 0, off = 0;
2152 uint8_t dfin = 0;
2153 struct mbuf *start = m;
2154 uint64_t dsn;
2155 uint32_t sseq;
2156 uint16_t orig_dlen;
2157 uint16_t csum;
2158
2159 VERIFY(m->m_nextpkt == NULL);
2160
2161 if (mp_tp->mpt_flags & MPTCPF_FALLBACK_TO_TCP) {
2162 fallback:
2163 /* Just move mbuf to MPTCP-level */
2164
2165 sbfree(&so->so_rcv, m);
2166
2167 if (mp != NULL) {
2168 *mp = m;
2169 mp = &m->m_next;
2170 so->so_rcv.sb_mb = m = m->m_next;
2171 *mp = NULL;
2172 }
2173
2174 if (m != NULL) {
2175 so->so_rcv.sb_lastrecord = m;
2176 } else {
2177 SB_EMPTY_FIXUP(&so->so_rcv);
2178 }
2179
2180 continue;
2181 } else if (!(m->m_flags & M_PKTHDR) || !(m->m_pkthdr.pkt_flags & PKTF_MPTCP)) {
2182 struct mptsub *mpts = sototcpcb(so)->t_mpsub;
2183 boolean_t found_mapping = false;
2184 int parsed_length = 0;
2185 struct mbuf *m_iter;
2186
2187 /*
2188 * No MPTCP-option in the header. Either fallback or
2189 * wait for additional mappings.
2190 */
2191 if (!(mpts->mpts_flags & MPTSF_FULLY_ESTABLISHED)) {
2192 /* data arrived without a DSS option mapping */
2193
2194 /* initial subflow can fallback right after SYN handshake */
2195 if (mpts->mpts_flags & MPTSF_INITIAL_SUB) {
2196 mptcp_notify_mpfail(so);
2197
2198 goto fallback;
2199 } else {
2200 os_log_error(mptcp_log_handle, "%s - %lx: No DSS on secondary subflow. Killing %d\n",
2201 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte),
2202 mpts->mpts_connid);
2203 soevent(mpts->mpts_socket, SO_FILT_HINT_LOCKED | SO_FILT_HINT_MUSTRST);
2204
2205 error = EIO;
2206 *mp0 = NULL;
2207 goto release;
2208 }
2209 }
2210
2211 /* Thus, let's look for an mbuf with the mapping */
2212 m_iter = m->m_next;
2213 parsed_length = m->m_len;
2214 while (m_iter != NULL && parsed_length < UINT16_MAX) {
2215 if (!(m_iter->m_flags & M_PKTHDR) || !(m_iter->m_pkthdr.pkt_flags & PKTF_MPTCP)) {
2216 parsed_length += m_iter->m_len;
2217 m_iter = m_iter->m_next;
2218 continue;
2219 }
2220
2221 found_mapping = true;
2222
2223 /* Found an mbuf with a DSS-mapping */
2224 orig_dlen = dlen = m_iter->m_pkthdr.mp_rlen;
2225 dsn = m_iter->m_pkthdr.mp_dsn;
2226 sseq = m_iter->m_pkthdr.mp_rseq;
2227 csum = m_iter->m_pkthdr.mp_csum;
2228
2229 if (m_iter->m_pkthdr.pkt_flags & PKTF_MPTCP_DFIN) {
2230 dfin = 1;
2231 dlen--;
2232 }
2233
2234 break;
2235 }
2236
2237 if (!found_mapping && parsed_length < UINT16_MAX) {
2238 /* Mapping not yet present, we can wait! */
2239 if (*mp0 == NULL) {
2240 error = EWOULDBLOCK;
2241 }
2242 goto release;
2243 } else if (!found_mapping && parsed_length >= UINT16_MAX) {
2244 os_log_error(mptcp_log_handle, "%s - %lx: Received more than 64KB without DSS mapping. Killing %d\n",
2245 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte),
2246 mpts->mpts_connid);
2247 /* Received 64KB without DSS-mapping. We should kill the subflow */
2248 soevent(mpts->mpts_socket, SO_FILT_HINT_LOCKED | SO_FILT_HINT_MUSTRST);
2249
2250 error = EIO;
2251 *mp0 = NULL;
2252 goto release;
2253 }
2254 } else {
2255 orig_dlen = dlen = m->m_pkthdr.mp_rlen;
2256 dsn = m->m_pkthdr.mp_dsn;
2257 sseq = m->m_pkthdr.mp_rseq;
2258 csum = m->m_pkthdr.mp_csum;
2259
2260 if (m->m_pkthdr.pkt_flags & PKTF_MPTCP_DFIN) {
2261 dfin = 1;
2262 dlen--;
2263 }
2264 }
2265
2266 /* Now, see if we need to remove previous packets */
2267 if (SEQ_GT(sseq + tp->irs, tp->rcv_nxt - so->so_rcv.sb_cc)) {
2268 /* Ok, there is data in there that we don't need - let's throw it away! */
2269 int totrim = (int)sseq + tp->irs - (tp->rcv_nxt - so->so_rcv.sb_cc);
2270
2271 sbdrop(&so->so_rcv, totrim);
2272
2273 m = so->so_rcv.sb_mb;
2274 }
2275
2276 /*
2277 * Check if the full mapping is now present
2278 */
2279 if ((int)so->so_rcv.sb_cc < dlen) {
2280 if (*mp0 == NULL) {
2281 error = EWOULDBLOCK;
2282 }
2283 goto release;
2284 }
2285
2286 /* Now, get the full mapping */
2287 off = 0;
2288 while (dlen > 0) {
2289 if (mptcp_adj_rmap(so, m, off, dsn, sseq, orig_dlen, dfin)) {
2290 error_out = 1;
2291 error = EIO;
2292 dlen = 0;
2293 *mp0 = NULL;
2294 break;
2295 }
2296
2297 dlen -= m->m_len;
2298 off += m->m_len;
2299 sbfree(&so->so_rcv, m);
2300
2301 if (mp != NULL) {
2302 *mp = m;
2303 mp = &m->m_next;
2304 so->so_rcv.sb_mb = m = m->m_next;
2305 *mp = NULL;
2306 }
2307
2308 ASSERT(dlen == 0 || m);
2309 if (dlen != 0 && m == NULL) {
2310 /* "try" to gracefully recover on customer builds */
2311 error_out = 1;
2312 error = EIO;
2313 dlen = 0;
2314
2315 *mp0 = NULL;
2316
2317 SB_EMPTY_FIXUP(&so->so_rcv);
2318 soevent(so, SO_FILT_HINT_LOCKED | SO_FILT_HINT_MUSTRST);
2319
2320 break;
2321 }
2322 }
2323
2324 ASSERT(dlen == 0);
2325 if (dlen != 0) {
2326 /* "try" to gracefully recover on customer builds */
2327 error_out = 1;
2328 error = EIO;
2329 dlen = 0;
2330
2331 *mp0 = NULL;
2332
2333 SB_EMPTY_FIXUP(&so->so_rcv);
2334 soevent(so, SO_FILT_HINT_LOCKED | SO_FILT_HINT_MUSTRST);
2335 }
2336
2337 if (m != NULL) {
2338 so->so_rcv.sb_lastrecord = m;
2339 } else {
2340 SB_EMPTY_FIXUP(&so->so_rcv);
2341 }
2342
2343 if (error_out) {
2344 goto release;
2345 }
2346
2347 if (mptcp_validate_csum(sototcpcb(so), start, dsn, sseq, orig_dlen, csum, dfin)) {
2348 error = EIO;
2349 *mp0 = NULL;
2350 goto release;
2351 }
2352
2353 SBLASTRECORDCHK(&so->so_rcv, "mptcp_subflow_soreceive 2");
2354 SBLASTMBUFCHK(&so->so_rcv, "mptcp_subflow_soreceive 2");
2355 }
2356
2357 DTRACE_MPTCP3(subflow__receive, struct socket *, so,
2358 struct sockbuf *, &so->so_rcv, struct sockbuf *, &so->so_snd);
2359
2360 if (flagsp != NULL) {
2361 *flagsp |= flags;
2362 }
2363
2364 release:
2365 sbunlock(&so->so_rcv, TRUE);
2366
2367 return error;
2368 }
2369
2370 /*
2371 * MPTCP subflow socket send routine, derived from sosend().
2372 */
2373 static int
mptcp_subflow_sosend(struct socket * so,struct sockaddr * addr,struct uio * uio,struct mbuf * top,struct mbuf * control,int flags)2374 mptcp_subflow_sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
2375 struct mbuf *top, struct mbuf *control, int flags)
2376 {
2377 struct socket *mp_so = mptetoso(tptomptp(sototcpcb(so))->mpt_mpte);
2378 boolean_t en_tracing = FALSE, proc_held = FALSE;
2379 struct proc *p = current_proc();
2380 int en_tracing_val;
2381 int sblocked = 1; /* Pretend as if it is already locked, so we won't relock it */
2382 int error;
2383
2384 VERIFY(control == NULL);
2385 VERIFY(addr == NULL);
2386 VERIFY(uio == NULL);
2387 VERIFY(flags == 0);
2388 VERIFY((so->so_flags & SOF_CONTENT_FILTER) == 0);
2389
2390 VERIFY(top->m_pkthdr.len > 0 && top->m_pkthdr.len <= UINT16_MAX);
2391 VERIFY(top->m_pkthdr.pkt_flags & PKTF_MPTCP);
2392
2393 /*
2394 * trace if tracing & network (vs. unix) sockets & and
2395 * non-loopback
2396 */
2397 if (ENTR_SHOULDTRACE &&
2398 (SOCK_CHECK_DOM(so, AF_INET) || SOCK_CHECK_DOM(so, AF_INET6))) {
2399 struct inpcb *inp = sotoinpcb(so);
2400 if (inp->inp_last_outifp != NULL &&
2401 !(inp->inp_last_outifp->if_flags & IFF_LOOPBACK)) {
2402 en_tracing = TRUE;
2403 en_tracing_val = top->m_pkthdr.len;
2404 KERNEL_ENERGYTRACE(kEnTrActKernSockWrite, DBG_FUNC_START,
2405 (unsigned long)VM_KERNEL_ADDRPERM(so),
2406 ((so->so_state & SS_NBIO) ? kEnTrFlagNonBlocking : 0),
2407 (int64_t)en_tracing_val);
2408 }
2409 }
2410
2411 mptcp_update_last_owner(so, mp_so);
2412
2413 if (mp_so->last_pid != proc_pid(p)) {
2414 p = proc_find(mp_so->last_pid);
2415 if (p == PROC_NULL) {
2416 p = current_proc();
2417 } else {
2418 proc_held = TRUE;
2419 }
2420 }
2421
2422 #if NECP
2423 inp_update_necp_policy(sotoinpcb(so), NULL, NULL, 0);
2424 #endif /* NECP */
2425
2426 error = sosendcheck(so, NULL, top->m_pkthdr.len, 0, 1, 0, &sblocked);
2427 if (error) {
2428 goto out;
2429 }
2430
2431 error = (*so->so_proto->pr_usrreqs->pru_send)(so, 0, top, NULL, NULL, p);
2432 top = NULL;
2433
2434 out:
2435 if (top != NULL) {
2436 m_freem(top);
2437 }
2438
2439 if (proc_held) {
2440 proc_rele(p);
2441 }
2442
2443 soclearfastopen(so);
2444
2445 if (en_tracing) {
2446 KERNEL_ENERGYTRACE(kEnTrActKernSockWrite, DBG_FUNC_END,
2447 (unsigned long)VM_KERNEL_ADDRPERM(so),
2448 ((error == EWOULDBLOCK) ? kEnTrFlagNoWork : 0),
2449 (int64_t)en_tracing_val);
2450 }
2451
2452 return error;
2453 }
2454
2455 /*
2456 * Subflow socket write upcall.
2457 *
2458 * Called when the associated subflow socket posted a read event.
2459 */
2460 static void
mptcp_subflow_wupcall(struct socket * so,void * arg,int waitf)2461 mptcp_subflow_wupcall(struct socket *so, void *arg, int waitf)
2462 {
2463 #pragma unused(so, waitf)
2464 struct mptsub *mpts __single = arg;
2465 struct mptses *mpte = mpts->mpts_mpte;
2466
2467 VERIFY(mpte != NULL);
2468
2469 if (mptcp_should_defer_upcall(mpte->mpte_mppcb)) {
2470 if (!(mpte->mpte_mppcb->mpp_flags & MPP_WUPCALL)) {
2471 mpte->mpte_mppcb->mpp_flags |= MPP_SHOULD_WWAKEUP;
2472 }
2473 return;
2474 }
2475
2476 mptcp_output(mpte);
2477 }
2478
2479 /*
2480 * Subflow socket control event upcall.
2481 */
2482 static void
mptcp_subflow_eupcall1(struct socket * so,void * arg,uint32_t events)2483 mptcp_subflow_eupcall1(struct socket *so, void *arg, uint32_t events)
2484 {
2485 #pragma unused(so)
2486 struct mptsub *mpts __single = arg;
2487 struct mptses *mpte = mpts->mpts_mpte;
2488
2489 socket_lock_assert_owned(mptetoso(mpte));
2490
2491 if ((mpts->mpts_evctl & events) == events) {
2492 return;
2493 }
2494
2495 mpts->mpts_evctl |= events;
2496
2497 if (mptcp_should_defer_upcall(mpte->mpte_mppcb)) {
2498 mpte->mpte_mppcb->mpp_flags |= MPP_SHOULD_WORKLOOP;
2499 return;
2500 }
2501
2502 mptcp_subflow_workloop(mpte);
2503 }
2504
2505 /*
2506 * Establish an initial MPTCP connection (if first subflow and not yet
2507 * connected), or add a subflow to an existing MPTCP connection.
2508 */
2509 int
mptcp_subflow_add(struct mptses * mpte,struct sockaddr * src,struct sockaddr * dst,uint32_t ifscope,sae_connid_t * pcid)2510 mptcp_subflow_add(struct mptses *mpte, struct sockaddr *src,
2511 struct sockaddr *dst, uint32_t ifscope, sae_connid_t *pcid)
2512 {
2513 socket_ref_t mp_so, so = NULL;
2514 struct mptcb *mp_tp;
2515 struct mptsub *mpts = NULL;
2516 int af, error = 0;
2517
2518 mp_so = mptetoso(mpte);
2519 mp_tp = mpte->mpte_mptcb;
2520
2521 socket_lock_assert_owned(mp_so);
2522
2523 if (mp_tp->mpt_state >= MPTCPS_CLOSE_WAIT) {
2524 /* If the remote end sends Data FIN, refuse subflow adds */
2525 os_log_error(mptcp_log_handle, "%s - %lx: state %u\n",
2526 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), mp_tp->mpt_state);
2527 error = ENOTCONN;
2528 goto out_err;
2529 }
2530
2531 if (mpte->mpte_numflows > MPTCP_MAX_NUM_SUBFLOWS) {
2532 error = EOVERFLOW;
2533 goto out_err;
2534 }
2535
2536 mpts = mptcp_subflow_alloc();
2537 if (mpts == NULL) {
2538 os_log_error(mptcp_log_handle, "%s - %lx: malloc subflow failed\n",
2539 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte));
2540 error = ENOMEM;
2541 goto out_err;
2542 }
2543
2544 if (src) {
2545 if (src->sa_family != AF_INET && src->sa_family != AF_INET6) {
2546 error = EAFNOSUPPORT;
2547 goto out_err;
2548 }
2549
2550 if (src->sa_family == AF_INET &&
2551 src->sa_len != sizeof(struct sockaddr_in)) {
2552 error = EINVAL;
2553 goto out_err;
2554 }
2555
2556 if (src->sa_family == AF_INET6 &&
2557 src->sa_len != sizeof(struct sockaddr_in6)) {
2558 error = EINVAL;
2559 goto out_err;
2560 }
2561
2562 mpts->mpts_src = SA(alloc_sockaddr(src->sa_len, Z_WAITOK | Z_NOFAIL));
2563
2564 SOCKADDR_COPY(src, mpts->mpts_src, src->sa_len);
2565 }
2566
2567 if (dst->sa_family != AF_INET && dst->sa_family != AF_INET6) {
2568 error = EAFNOSUPPORT;
2569 goto out_err;
2570 }
2571
2572 if (dst->sa_family == AF_INET &&
2573 dst->sa_len != sizeof(mpts->__mpts_dst_v4)) {
2574 error = EINVAL;
2575 goto out_err;
2576 }
2577
2578 if (dst->sa_family == AF_INET6 &&
2579 dst->sa_len != sizeof(mpts->__mpts_dst_v6)) {
2580 error = EINVAL;
2581 goto out_err;
2582 }
2583
2584 SOCKADDR_COPY(dst, &mpts->mpts_dst, dst->sa_len);
2585
2586 af = mpts->mpts_dst.sa_family;
2587
2588 ifnet_head_lock_shared();
2589 if ((ifscope > (unsigned)if_index)) {
2590 ifnet_head_done();
2591 error = ENXIO;
2592 goto out_err;
2593 }
2594 ifnet_head_done();
2595
2596 mpts->mpts_ifscope = ifscope;
2597
2598 /* create the subflow socket */
2599 if ((error = mptcp_subflow_socreate(mpte, mpts, af, &so)) != 0) {
2600 /*
2601 * Returning (error) and not cleaning up, because up to here
2602 * all we did is creating mpts.
2603 *
2604 * And the contract is that the call to mptcp_subflow_socreate,
2605 * moves ownership of mpts to mptcp_subflow_socreate.
2606 */
2607 return error;
2608 }
2609
2610 /*
2611 * We may be called from within the kernel. Still need to account this
2612 * one to the real app.
2613 */
2614 mptcp_update_last_owner(mpts->mpts_socket, mp_so);
2615
2616 /*
2617 * Increment the counter, while avoiding 0 (SAE_CONNID_ANY) and
2618 * -1 (SAE_CONNID_ALL).
2619 */
2620 mpte->mpte_connid_last++;
2621 if (mpte->mpte_connid_last == SAE_CONNID_ALL ||
2622 mpte->mpte_connid_last == SAE_CONNID_ANY) {
2623 mpte->mpte_connid_last++;
2624 }
2625
2626 mpts->mpts_connid = mpte->mpte_connid_last;
2627
2628 mpts->mpts_rel_seq = 1;
2629
2630 /* Allocate a unique address id per subflow */
2631 mpte->mpte_addrid_last++;
2632 if (mpte->mpte_addrid_last == 0) {
2633 mpte->mpte_addrid_last++;
2634 }
2635
2636 /* register for subflow socket read/write events */
2637 sock_setupcalls_locked(so, NULL, NULL, mptcp_subflow_wupcall, mpts, 1);
2638
2639 /* Register for subflow socket control events */
2640 sock_catchevents_locked(so, mptcp_subflow_eupcall1, mpts,
2641 SO_FILT_HINT_CONNRESET | SO_FILT_HINT_CANTRCVMORE |
2642 SO_FILT_HINT_TIMEOUT | SO_FILT_HINT_NOSRCADDR |
2643 SO_FILT_HINT_IFDENIED | SO_FILT_HINT_CONNECTED |
2644 SO_FILT_HINT_DISCONNECTED | SO_FILT_HINT_MPFAILOVER |
2645 SO_FILT_HINT_MPSTATUS | SO_FILT_HINT_MUSTRST |
2646 SO_FILT_HINT_MPCANTRCVMORE | SO_FILT_HINT_ADAPTIVE_RTIMO |
2647 SO_FILT_HINT_ADAPTIVE_WTIMO | SO_FILT_HINT_MP_SUB_ERROR);
2648
2649 /* sanity check */
2650 VERIFY(!(mpts->mpts_flags &
2651 (MPTSF_CONNECTING | MPTSF_CONNECTED | MPTSF_CONNECT_PENDING)));
2652
2653 /*
2654 * Indicate to the TCP subflow whether or not it should establish
2655 * the initial MPTCP connection, or join an existing one. Fill
2656 * in the connection request structure with additional info needed
2657 * by the underlying TCP (to be used in the TCP options, etc.)
2658 */
2659 if (mp_tp->mpt_state < MPTCPS_ESTABLISHED && mpte->mpte_numflows == 1) {
2660 mpts->mpts_flags |= MPTSF_INITIAL_SUB;
2661
2662 if (mp_tp->mpt_state == MPTCPS_CLOSED) {
2663 mptcp_init_local_parms(mpte, dst);
2664 }
2665 soisconnecting(mp_so);
2666
2667 /* If fastopen is requested, set state in mpts */
2668 if (so->so_flags1 & SOF1_PRECONNECT_DATA) {
2669 mpts->mpts_flags |= MPTSF_TFO_REQD;
2670 }
2671 } else {
2672 if (!(mp_tp->mpt_flags & MPTCPF_JOIN_READY)) {
2673 mpts->mpts_flags |= MPTSF_CONNECT_PENDING;
2674 }
2675 }
2676
2677 mpts->mpts_flags |= MPTSF_CONNECTING;
2678
2679 /* connect right away if first attempt, or if join can be done now */
2680 if (!(mpts->mpts_flags & MPTSF_CONNECT_PENDING)) {
2681 error = mptcp_subflow_soconnectx(mpte, mpts);
2682 }
2683
2684 if (error) {
2685 goto out_err_close;
2686 }
2687
2688 if (pcid) {
2689 *pcid = mpts->mpts_connid;
2690 }
2691
2692 return 0;
2693
2694 out_err_close:
2695 mptcp_subflow_abort(mpts, error);
2696
2697 return error;
2698
2699 out_err:
2700 if (mpts) {
2701 mptcp_subflow_free(mpts);
2702 }
2703
2704 return error;
2705 }
2706
2707 void
mptcpstats_update(struct mptcp_itf_stats * stats __counted_by (stats_count),uint16_t stats_count,const struct mptsub * mpts)2708 mptcpstats_update(struct mptcp_itf_stats *stats __counted_by(stats_count), uint16_t stats_count, const struct mptsub *mpts)
2709 {
2710 int index = mptcpstats_get_index(stats, stats_count, mpts);
2711
2712 if (index != -1) {
2713 struct inpcb *inp = sotoinpcb(mpts->mpts_socket);
2714
2715 stats[index].mpis_txbytes += inp->inp_stat->txbytes;
2716 stats[index].mpis_rxbytes += inp->inp_stat->rxbytes;
2717
2718 stats[index].mpis_wifi_txbytes += inp->inp_wstat->txbytes;
2719 stats[index].mpis_wifi_rxbytes += inp->inp_wstat->rxbytes;
2720
2721 stats[index].mpis_wired_txbytes += inp->inp_Wstat->txbytes;
2722 stats[index].mpis_wired_rxbytes += inp->inp_Wstat->rxbytes;
2723
2724 stats[index].mpis_cell_txbytes += inp->inp_cstat->txbytes;
2725 stats[index].mpis_cell_rxbytes += inp->inp_cstat->rxbytes;
2726 }
2727 }
2728
2729 /*
2730 * Delete/remove a subflow from an MPTCP. The underlying subflow socket
2731 * will no longer be accessible after a subflow is deleted, thus this
2732 * should occur only after the subflow socket has been disconnected.
2733 */
2734 void
mptcp_subflow_del(struct mptses * mpte,struct mptsub * mpts)2735 mptcp_subflow_del(struct mptses *mpte, struct mptsub *mpts)
2736 {
2737 struct socket *mp_so = mptetoso(mpte);
2738 struct socket *so = mpts->mpts_socket;
2739 struct tcpcb *tp = sototcpcb(so);
2740
2741 socket_lock_assert_owned(mp_so);
2742 VERIFY(mpts->mpts_mpte == mpte);
2743 VERIFY(mpte->mpte_numflows != 0);
2744 VERIFY(mp_so->so_usecount > 0);
2745
2746 mptcpstats_update(mpte->mpte_itfstats, MPTCP_ITFSTATS_SIZE, mpts);
2747
2748 mptcp_unset_cellicon(mpte, mpts, 1);
2749
2750 mpte->mpte_init_rxbytes = sotoinpcb(so)->inp_stat->rxbytes;
2751 mpte->mpte_init_txbytes = sotoinpcb(so)->inp_stat->txbytes;
2752
2753 TAILQ_REMOVE(&mpte->mpte_subflows, mpts, mpts_entry);
2754 mpte->mpte_numflows--;
2755 if (mpte->mpte_active_sub == mpts) {
2756 mpte->mpte_active_sub = NULL;
2757 }
2758
2759 /*
2760 * Drop references held by this subflow socket; there
2761 * will be no further upcalls made from this point.
2762 */
2763 sock_setupcalls_locked(so, NULL, NULL, NULL, NULL, 0);
2764 sock_catchevents_locked(so, NULL, NULL, 0);
2765
2766 mptcp_detach_mptcb_from_subf(mpte->mpte_mptcb, so);
2767
2768 mp_so->so_usecount--; /* for subflow socket */
2769 mpts->mpts_mpte = NULL;
2770 mpts->mpts_socket = NULL;
2771
2772 mptcp_subflow_remref(mpts); /* for MPTCP subflow list */
2773 mptcp_subflow_remref(mpts); /* for subflow socket */
2774
2775 so->so_flags &= ~SOF_MP_SUBFLOW;
2776 tp->t_mptcb = NULL;
2777 tp->t_mpsub = NULL;
2778 }
2779
2780 void
mptcp_subflow_shutdown(struct mptses * mpte,struct mptsub * mpts)2781 mptcp_subflow_shutdown(struct mptses *mpte, struct mptsub *mpts)
2782 {
2783 struct socket *so = mpts->mpts_socket;
2784 struct mptcb *mp_tp = mpte->mpte_mptcb;
2785 int send_dfin = 0;
2786
2787 if (mp_tp->mpt_state > MPTCPS_CLOSE_WAIT) {
2788 send_dfin = 1;
2789 }
2790
2791 if (!(so->so_state & (SS_ISDISCONNECTING | SS_ISDISCONNECTED)) &&
2792 (so->so_state & SS_ISCONNECTED)) {
2793 if (send_dfin) {
2794 mptcp_send_dfin(so);
2795 }
2796 soshutdownlock(so, SHUT_WR);
2797 }
2798 }
2799
2800 static void
mptcp_subflow_abort(struct mptsub * mpts,int error)2801 mptcp_subflow_abort(struct mptsub *mpts, int error)
2802 {
2803 struct socket *so = mpts->mpts_socket;
2804 struct tcpcb *tp = sototcpcb(so);
2805
2806 if (mpts->mpts_flags & MPTSF_DISCONNECTED) {
2807 return;
2808 }
2809
2810 if (tp->t_state != TCPS_CLOSED) {
2811 tcp_drop(tp, error);
2812 }
2813
2814 mptcp_subflow_eupcall1(so, mpts, SO_FILT_HINT_DISCONNECTED);
2815 }
2816
2817 /*
2818 * Disconnect a subflow socket.
2819 */
2820 void
mptcp_subflow_disconnect(struct mptses * mpte,struct mptsub * mpts)2821 mptcp_subflow_disconnect(struct mptses *mpte, struct mptsub *mpts)
2822 {
2823 struct socket *so, *mp_so;
2824 struct mptcb *mp_tp;
2825 int send_dfin = 0;
2826
2827 so = mpts->mpts_socket;
2828 mp_tp = mpte->mpte_mptcb;
2829 mp_so = mptetoso(mpte);
2830
2831 socket_lock_assert_owned(mp_so);
2832
2833 if (mpts->mpts_flags & (MPTSF_DISCONNECTING | MPTSF_DISCONNECTED)) {
2834 return;
2835 }
2836
2837 mptcp_unset_cellicon(mpte, mpts, 1);
2838
2839 mpts->mpts_flags |= MPTSF_DISCONNECTING;
2840
2841 if (mp_tp->mpt_state > MPTCPS_CLOSE_WAIT) {
2842 send_dfin = 1;
2843 }
2844
2845 if (mp_so->so_flags & SOF_DEFUNCT) {
2846 errno_t ret;
2847
2848 ret = sosetdefunct(NULL, so, SHUTDOWN_SOCKET_LEVEL_DISCONNECT_ALL, TRUE);
2849 if (ret == 0) {
2850 ret = sodefunct(NULL, so, SHUTDOWN_SOCKET_LEVEL_DISCONNECT_ALL);
2851
2852 if (ret != 0) {
2853 os_log_error(mptcp_log_handle, "%s - %lx: sodefunct failed with %d\n",
2854 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), ret);
2855 }
2856 } else {
2857 os_log_error(mptcp_log_handle, "%s - %lx: sosetdefunct failed with %d\n",
2858 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), ret);
2859 }
2860 }
2861
2862 if (!(so->so_state & (SS_ISDISCONNECTING | SS_ISDISCONNECTED)) &&
2863 (so->so_state & SS_ISCONNECTED)) {
2864 if (send_dfin) {
2865 mptcp_send_dfin(so);
2866 }
2867
2868 (void) soshutdownlock(so, SHUT_RD);
2869 (void) soshutdownlock(so, SHUT_WR);
2870 (void) sodisconnectlocked(so);
2871 }
2872
2873 /*
2874 * Generate a disconnect event for this subflow socket, in case
2875 * the lower layer doesn't do it; this is needed because the
2876 * subflow socket deletion relies on it.
2877 */
2878 mptcp_subflow_eupcall1(so, mpts, SO_FILT_HINT_DISCONNECTED);
2879 }
2880
2881 /*
2882 * Subflow socket input.
2883 */
2884 static void
mptcp_subflow_input(struct mptses * mpte,struct mptsub * mpts)2885 mptcp_subflow_input(struct mptses *mpte, struct mptsub *mpts)
2886 {
2887 struct socket *mp_so = mptetoso(mpte);
2888 mbuf_ref_t m = NULL;
2889 struct socket *so;
2890 int error, wakeup = 0;
2891
2892 VERIFY(!(mpte->mpte_mppcb->mpp_flags & MPP_INSIDE_INPUT));
2893 mpte->mpte_mppcb->mpp_flags |= MPP_INSIDE_INPUT;
2894
2895 DTRACE_MPTCP2(subflow__input, struct mptses *, mpte,
2896 struct mptsub *, mpts);
2897
2898 if (!(mpts->mpts_flags & MPTSF_CONNECTED)) {
2899 goto out;
2900 }
2901
2902 so = mpts->mpts_socket;
2903
2904 error = sock_receive_internal(so, NULL, &m, 0, NULL);
2905 if (error != 0 && error != EWOULDBLOCK) {
2906 os_log_error(mptcp_log_handle, "%s - %lx: cid %d error %d\n",
2907 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), mpts->mpts_connid, error);
2908 if (error == ENODATA) {
2909 /*
2910 * Don't ignore ENODATA so as to discover
2911 * nasty middleboxes.
2912 */
2913 mp_so->so_error = ENODATA;
2914
2915 wakeup = 1;
2916 goto out;
2917 }
2918 }
2919
2920 /* In fallback, make sure to accept data on all but one subflow */
2921 if (m && (mpts->mpts_flags & MPTSF_MP_DEGRADED) &&
2922 !(mpts->mpts_flags & MPTSF_ACTIVE)) {
2923 m_freem(m);
2924 goto out;
2925 }
2926
2927 if (m != NULL) {
2928 if (IFNET_IS_CELLULAR(sotoinpcb(so)->inp_last_outifp)) {
2929 mptcp_set_cellicon(mpte, mpts);
2930
2931 mpte->mpte_used_cell = 1;
2932 } else {
2933 /*
2934 * If during the past MPTCP_CELLICON_TOGGLE_RATE seconds we didn't
2935 * explicitly set the cellicon, then we unset it again.
2936 */
2937 if (TSTMP_LT(mpte->mpte_last_cellicon_set + MPTCP_CELLICON_TOGGLE_RATE, tcp_now)) {
2938 mptcp_unset_cellicon(mpte, NULL, 1);
2939 }
2940
2941 mpte->mpte_used_wifi = 1;
2942 }
2943
2944 mptcp_input(mpte, m);
2945 }
2946
2947 out:
2948 if (wakeup) {
2949 mpte->mpte_mppcb->mpp_flags |= MPP_SHOULD_RWAKEUP;
2950 }
2951
2952 mptcp_handle_deferred_upcalls(mpte->mpte_mppcb, MPP_INSIDE_INPUT);
2953 }
2954
2955 void
mptcp_handle_input(struct socket * so)2956 mptcp_handle_input(struct socket *so)
2957 {
2958 struct mptsub *mpts, *tmpts;
2959 struct mptses *mpte;
2960
2961 if (!(so->so_flags & SOF_MP_SUBFLOW)) {
2962 return;
2963 }
2964
2965 mpts = sototcpcb(so)->t_mpsub;
2966 mpte = mpts->mpts_mpte;
2967
2968 socket_lock_assert_owned(mptetoso(mpte));
2969
2970 if (mptcp_should_defer_upcall(mpte->mpte_mppcb)) {
2971 if (!(mpte->mpte_mppcb->mpp_flags & MPP_INPUT_HANDLE)) {
2972 mpte->mpte_mppcb->mpp_flags |= MPP_SHOULD_RWAKEUP;
2973 }
2974 return;
2975 }
2976
2977 mpte->mpte_mppcb->mpp_flags |= MPP_INPUT_HANDLE;
2978 TAILQ_FOREACH_SAFE(mpts, &mpte->mpte_subflows, mpts_entry, tmpts) {
2979 if (mpts->mpts_socket->so_usecount == 0) {
2980 /* Will be removed soon by tcp_garbage_collect */
2981 continue;
2982 }
2983
2984 mptcp_subflow_addref(mpts);
2985 mpts->mpts_socket->so_usecount++;
2986
2987 mptcp_subflow_input(mpte, mpts);
2988
2989 mptcp_subflow_remref(mpts); /* ours */
2990
2991 VERIFY(mpts->mpts_socket->so_usecount != 0);
2992 mpts->mpts_socket->so_usecount--;
2993 }
2994
2995 mptcp_handle_deferred_upcalls(mpte->mpte_mppcb, MPP_INPUT_HANDLE);
2996 }
2997
2998 static boolean_t
mptcp_search_seq_in_sub(struct mbuf * m,struct socket * so)2999 mptcp_search_seq_in_sub(struct mbuf *m, struct socket *so)
3000 {
3001 struct mbuf *so_m = so->so_snd.sb_mb;
3002 uint64_t dsn = m->m_pkthdr.mp_dsn;
3003
3004 while (so_m) {
3005 VERIFY(so_m->m_flags & M_PKTHDR);
3006 VERIFY(so_m->m_pkthdr.pkt_flags & PKTF_MPTCP);
3007
3008 /* Part of the segment is covered, don't reinject here */
3009 if (so_m->m_pkthdr.mp_dsn <= dsn &&
3010 so_m->m_pkthdr.mp_dsn + so_m->m_pkthdr.mp_rlen > dsn) {
3011 return TRUE;
3012 }
3013
3014 so_m = so_m->m_next;
3015 }
3016
3017 return FALSE;
3018 }
3019
3020 /*
3021 * Subflow socket output.
3022 *
3023 * Called for sending data from MPTCP to the underlying subflow socket.
3024 */
3025 int
mptcp_subflow_output(struct mptses * mpte,struct mptsub * mpts,int flags)3026 mptcp_subflow_output(struct mptses *mpte, struct mptsub *mpts, int flags)
3027 {
3028 struct mptcb *mp_tp = mpte->mpte_mptcb;
3029 struct mbuf *sb_mb, *m, *mpt_mbuf = NULL, *head = NULL, *tail = NULL;
3030 struct socket *mp_so, *so;
3031 struct tcpcb *tp;
3032 uint64_t mpt_dsn = 0, off = 0;
3033 int sb_cc = 0, error = 0, wakeup = 0;
3034 uint16_t dss_csum;
3035 uint16_t tot_sent = 0;
3036 boolean_t reinjected = FALSE;
3037
3038 mp_so = mptetoso(mpte);
3039 so = mpts->mpts_socket;
3040 tp = sototcpcb(so);
3041
3042 socket_lock_assert_owned(mp_so);
3043
3044 VERIFY(!(mpte->mpte_mppcb->mpp_flags & MPP_INSIDE_OUTPUT));
3045 mpte->mpte_mppcb->mpp_flags |= MPP_INSIDE_OUTPUT;
3046
3047 VERIFY(!INP_WAIT_FOR_IF_FEEDBACK(sotoinpcb(so)));
3048 VERIFY((mpts->mpts_flags & MPTSF_MP_CAPABLE) ||
3049 (mpts->mpts_flags & MPTSF_MP_DEGRADED) ||
3050 (mpts->mpts_flags & MPTSF_TFO_REQD));
3051 VERIFY(mptcp_subflow_cwnd_space(mpts->mpts_socket) > 0);
3052
3053 DTRACE_MPTCP2(subflow__output, struct mptses *, mpte,
3054 struct mptsub *, mpts);
3055
3056 /* Remove Addr Option is not sent reliably as per I-D */
3057 if (mpte->mpte_flags & MPTE_SND_REM_ADDR) {
3058 tp->t_rem_aid = mpte->mpte_lost_aid;
3059 tp->t_mpflags |= TMPF_SND_REM_ADDR;
3060 mpte->mpte_flags &= ~MPTE_SND_REM_ADDR;
3061 }
3062
3063 /*
3064 * The mbuf chains containing the metadata (as well as pointing to
3065 * the user data sitting at the MPTCP output queue) would then be
3066 * sent down to the subflow socket.
3067 *
3068 * Some notes on data sequencing:
3069 *
3070 * a. Each mbuf must be a M_PKTHDR.
3071 * b. MPTCP metadata is stored in the mptcp_pktinfo structure
3072 * in the mbuf pkthdr structure.
3073 * c. Each mbuf containing the MPTCP metadata must have its
3074 * pkt_flags marked with the PKTF_MPTCP flag.
3075 */
3076
3077 if (mpte->mpte_reinjectq) {
3078 sb_mb = mpte->mpte_reinjectq;
3079 } else {
3080 sb_mb = mp_so->so_snd.sb_mb;
3081 }
3082
3083 if (sb_mb == NULL) {
3084 os_log_error(mptcp_log_handle, "%s - %lx: No data in MPTCP-sendbuffer! smax %u snxt %u suna %u state %u flags %#x\n",
3085 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte),
3086 (uint32_t)mp_tp->mpt_sndmax, (uint32_t)mp_tp->mpt_sndnxt,
3087 (uint32_t)mp_tp->mpt_snduna, mp_tp->mpt_state, mp_so->so_flags1);
3088
3089 /* Fix it to prevent looping */
3090 if (MPTCP_SEQ_LT(mp_tp->mpt_sndnxt, mp_tp->mpt_snduna)) {
3091 mp_tp->mpt_sndnxt = mp_tp->mpt_snduna;
3092 }
3093 goto out;
3094 }
3095
3096 VERIFY(sb_mb->m_pkthdr.pkt_flags & PKTF_MPTCP);
3097
3098 if (sb_mb->m_pkthdr.mp_rlen == 0 &&
3099 !(so->so_state & SS_ISCONNECTED) &&
3100 (so->so_flags1 & SOF1_PRECONNECT_DATA)) {
3101 tp->t_mpflags |= TMPF_TFO_REQUEST;
3102
3103 /* Opting to call pru_send as no mbuf at subflow level */
3104 error = (*so->so_proto->pr_usrreqs->pru_send)(so, 0, NULL, NULL,
3105 NULL, current_proc());
3106
3107 goto done_sending;
3108 }
3109
3110 mpt_dsn = sb_mb->m_pkthdr.mp_dsn;
3111
3112 /* First, drop acknowledged data */
3113 if (MPTCP_SEQ_LT(mpt_dsn, mp_tp->mpt_snduna)) {
3114 os_log_error(mptcp_log_handle, "%s - %lx: dropping data, should have been done earlier "
3115 "dsn %u suna %u reinject? %u\n",
3116 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), (uint32_t)mpt_dsn,
3117 (uint32_t)mp_tp->mpt_snduna, !!mpte->mpte_reinjectq);
3118 if (mpte->mpte_reinjectq) {
3119 mptcp_clean_reinjectq(mpte);
3120 } else {
3121 uint64_t len = 0;
3122 len = mp_tp->mpt_snduna - mpt_dsn;
3123 sbdrop(&mp_so->so_snd, (int)len);
3124 wakeup = 1;
3125 }
3126 }
3127
3128 /* Check again because of above sbdrop */
3129 if (mp_so->so_snd.sb_mb == NULL && mpte->mpte_reinjectq == NULL) {
3130 os_log_error(mptcp_log_handle, "%s - $%lx: send-buffer is empty\n",
3131 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte));
3132 goto out;
3133 }
3134
3135 /*
3136 * In degraded mode, we don't receive data acks, so force free
3137 * mbufs less than snd_nxt
3138 */
3139 if ((mpts->mpts_flags & MPTSF_MP_DEGRADED) &&
3140 (mp_tp->mpt_flags & MPTCPF_POST_FALLBACK_SYNC) &&
3141 mp_so->so_snd.sb_mb) {
3142 mpt_dsn = mp_so->so_snd.sb_mb->m_pkthdr.mp_dsn;
3143 if (MPTCP_SEQ_LT(mpt_dsn, mp_tp->mpt_snduna)) {
3144 uint64_t len = 0;
3145 len = mp_tp->mpt_snduna - mpt_dsn;
3146 sbdrop(&mp_so->so_snd, (int)len);
3147 wakeup = 1;
3148
3149 os_log_error(mptcp_log_handle, "%s - %lx: dropping data in degraded mode, should have been done earlier dsn %u sndnxt %u suna %u\n",
3150 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte),
3151 (uint32_t)mpt_dsn, (uint32_t)mp_tp->mpt_sndnxt, (uint32_t)mp_tp->mpt_snduna);
3152 }
3153 }
3154
3155 if ((mpts->mpts_flags & MPTSF_MP_DEGRADED) &&
3156 !(mp_tp->mpt_flags & MPTCPF_POST_FALLBACK_SYNC)) {
3157 mp_tp->mpt_flags |= MPTCPF_POST_FALLBACK_SYNC;
3158 so->so_flags1 |= SOF1_POST_FALLBACK_SYNC;
3159 }
3160
3161 /*
3162 * Adjust the top level notion of next byte used for retransmissions
3163 * and sending FINs.
3164 */
3165 if (MPTCP_SEQ_LT(mp_tp->mpt_sndnxt, mp_tp->mpt_snduna)) {
3166 mp_tp->mpt_sndnxt = mp_tp->mpt_snduna;
3167 }
3168
3169 /* Now determine the offset from which to start transmitting data */
3170 if (mpte->mpte_reinjectq) {
3171 sb_mb = mpte->mpte_reinjectq;
3172 } else {
3173 dont_reinject:
3174 sb_mb = mp_so->so_snd.sb_mb;
3175 }
3176 if (sb_mb == NULL) {
3177 os_log_error(mptcp_log_handle, "%s - %lx: send-buffer is still empty\n", __func__,
3178 (unsigned long)VM_KERNEL_ADDRPERM(mpte));
3179 goto out;
3180 }
3181
3182 if (sb_mb == mpte->mpte_reinjectq) {
3183 sb_cc = sb_mb->m_pkthdr.mp_rlen;
3184 off = 0;
3185
3186 if (mptcp_search_seq_in_sub(sb_mb, so)) {
3187 if (mptcp_can_send_more(mp_tp, TRUE)) {
3188 goto dont_reinject;
3189 }
3190
3191 error = ECANCELED;
3192 goto out;
3193 }
3194
3195 reinjected = TRUE;
3196 } else if (flags & MPTCP_SUBOUT_PROBING) {
3197 sb_cc = sb_mb->m_pkthdr.mp_rlen;
3198 off = 0;
3199 } else {
3200 sb_cc = min(mp_so->so_snd.sb_cc, mp_tp->mpt_sndwnd);
3201
3202 /*
3203 * With TFO, there might be no data at all, thus still go into this
3204 * code-path here.
3205 */
3206 if ((mp_so->so_flags1 & SOF1_PRECONNECT_DATA) ||
3207 MPTCP_SEQ_LT(mp_tp->mpt_sndnxt, mp_tp->mpt_sndmax)) {
3208 off = mp_tp->mpt_sndnxt - mp_tp->mpt_snduna;
3209 sb_cc -= off;
3210 } else {
3211 os_log_error(mptcp_log_handle, "%s - %lx: this should not happen: sndnxt %u sndmax %u\n",
3212 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), (uint32_t)mp_tp->mpt_sndnxt,
3213 (uint32_t)mp_tp->mpt_sndmax);
3214
3215 goto out;
3216 }
3217 }
3218
3219 sb_cc = min(sb_cc, mptcp_subflow_cwnd_space(so));
3220 if (sb_cc <= 0) {
3221 os_log_error(mptcp_log_handle, "%s - %lx: sb_cc is %d, mp_so->sb_cc %u, sndwnd %u,sndnxt %u sndmax %u cwnd %u\n",
3222 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), sb_cc, mp_so->so_snd.sb_cc, mp_tp->mpt_sndwnd,
3223 (uint32_t)mp_tp->mpt_sndnxt, (uint32_t)mp_tp->mpt_sndmax,
3224 mptcp_subflow_cwnd_space(so));
3225 }
3226
3227 sb_cc = min(sb_cc, UINT16_MAX);
3228
3229 /*
3230 * Create a DSN mapping for the data we are about to send. It all
3231 * has the same mapping.
3232 */
3233 if (reinjected) {
3234 mpt_dsn = sb_mb->m_pkthdr.mp_dsn;
3235 } else {
3236 mpt_dsn = mp_tp->mpt_snduna + off;
3237 }
3238
3239 mpt_mbuf = sb_mb;
3240 while (mpt_mbuf && reinjected == FALSE &&
3241 (mpt_mbuf->m_pkthdr.mp_rlen == 0 ||
3242 mpt_mbuf->m_pkthdr.mp_rlen <= (uint32_t)off)) {
3243 off -= mpt_mbuf->m_pkthdr.mp_rlen;
3244 mpt_mbuf = mpt_mbuf->m_next;
3245 }
3246 VERIFY((mpt_mbuf == NULL) || (mpt_mbuf->m_pkthdr.pkt_flags & PKTF_MPTCP));
3247
3248 head = tail = NULL;
3249
3250 while (tot_sent < sb_cc) {
3251 int32_t mlen;
3252
3253 mlen = mpt_mbuf->m_len;
3254 mlen -= off;
3255 mlen = MIN(mlen, sb_cc - tot_sent);
3256
3257 if (mlen < 0) {
3258 os_log_error(mptcp_log_handle, "%s - %lx: mlen %d mp_rlen %u off %u sb_cc %u tot_sent %u\n",
3259 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), mlen, mpt_mbuf->m_pkthdr.mp_rlen,
3260 (uint32_t)off, sb_cc, tot_sent);
3261 goto out;
3262 }
3263
3264 if (mlen == 0) {
3265 goto next;
3266 }
3267
3268 m = m_copym_mode(mpt_mbuf, (int)off, mlen, M_DONTWAIT, NULL, NULL,
3269 M_COPYM_MUST_COPY_HDR);
3270 if (m == NULL) {
3271 os_log_error(mptcp_log_handle, "%s - %lx: m_copym_mode failed\n", __func__,
3272 (unsigned long)VM_KERNEL_ADDRPERM(mpte));
3273 error = ENOBUFS;
3274 break;
3275 }
3276
3277 /* Create a DSN mapping for the data (m_copym does it) */
3278 VERIFY(m->m_flags & M_PKTHDR);
3279 VERIFY(m->m_next == NULL);
3280
3281 m->m_pkthdr.pkt_flags |= PKTF_MPTCP;
3282 m->m_pkthdr.pkt_flags &= ~PKTF_MPSO;
3283 m->m_pkthdr.mp_dsn = mpt_dsn;
3284 m->m_pkthdr.mp_rseq = mpts->mpts_rel_seq;
3285 m->m_pkthdr.len = mlen;
3286
3287 if (head == NULL) {
3288 head = tail = m;
3289 } else {
3290 tail->m_next = m;
3291 tail = m;
3292 }
3293
3294 tot_sent += mlen;
3295 off = 0;
3296 next:
3297 mpt_mbuf = mpt_mbuf->m_next;
3298 }
3299
3300 if (reinjected) {
3301 if (sb_cc < sb_mb->m_pkthdr.mp_rlen) {
3302 struct mbuf *n = sb_mb;
3303
3304 while (n) {
3305 n->m_pkthdr.mp_dsn += sb_cc;
3306 n->m_pkthdr.mp_rlen -= sb_cc;
3307 n = n->m_next;
3308 }
3309 m_adj(sb_mb, sb_cc);
3310 } else {
3311 mpte->mpte_reinjectq = sb_mb->m_nextpkt;
3312 m_freem(sb_mb);
3313 }
3314 }
3315
3316 if (head && (mp_tp->mpt_flags & MPTCPF_CHECKSUM)) {
3317 dss_csum = mptcp_output_csum(head, mpt_dsn, mpts->mpts_rel_seq,
3318 tot_sent);
3319 }
3320
3321 /* Now, let's update rel-seq and the data-level length */
3322 mpts->mpts_rel_seq += tot_sent;
3323 m = head;
3324 while (m) {
3325 if (mp_tp->mpt_flags & MPTCPF_CHECKSUM) {
3326 m->m_pkthdr.mp_csum = dss_csum;
3327 }
3328 m->m_pkthdr.mp_rlen = tot_sent;
3329 m = m->m_next;
3330 }
3331
3332 if (head != NULL) {
3333 if ((mpts->mpts_flags & MPTSF_TFO_REQD) &&
3334 (tp->t_tfo_stats == 0)) {
3335 tp->t_mpflags |= TMPF_TFO_REQUEST;
3336 }
3337
3338 error = so->so_proto->pr_usrreqs->pru_sosend(so, NULL, NULL, head, NULL, 0);
3339 head = NULL;
3340 }
3341
3342 done_sending:
3343 if (error == 0 ||
3344 (error == EWOULDBLOCK && (tp->t_mpflags & TMPF_TFO_REQUEST))) {
3345 uint64_t new_sndnxt = mp_tp->mpt_sndnxt + tot_sent;
3346
3347 if (mpts->mpts_probesoon && mpts->mpts_maxseg && tot_sent) {
3348 tcpstat.tcps_mp_num_probes++;
3349 if ((uint32_t)tot_sent < mpts->mpts_maxseg) {
3350 mpts->mpts_probecnt += 1;
3351 } else {
3352 mpts->mpts_probecnt +=
3353 tot_sent / mpts->mpts_maxseg;
3354 }
3355 }
3356
3357 if (!reinjected && !(flags & MPTCP_SUBOUT_PROBING)) {
3358 if (MPTCP_DATASEQ_HIGH32(new_sndnxt) >
3359 MPTCP_DATASEQ_HIGH32(mp_tp->mpt_sndnxt)) {
3360 mp_tp->mpt_flags |= MPTCPF_SND_64BITDSN;
3361 }
3362 mp_tp->mpt_sndnxt = new_sndnxt;
3363 }
3364
3365 mptcp_cancel_timer(mp_tp, MPTT_REXMT);
3366
3367 /* Must be here as mptcp_can_send_more() checks for this */
3368 soclearfastopen(mp_so);
3369
3370 if (IFNET_IS_CELLULAR(sotoinpcb(so)->inp_last_outifp)) {
3371 mptcp_set_cellicon(mpte, mpts);
3372
3373 mpte->mpte_used_cell = 1;
3374 } else {
3375 /*
3376 * If during the past MPTCP_CELLICON_TOGGLE_RATE seconds we didn't
3377 * explicitly set the cellicon, then we unset it again.
3378 */
3379 if (TSTMP_LT(mpte->mpte_last_cellicon_set + MPTCP_CELLICON_TOGGLE_RATE, tcp_now)) {
3380 mptcp_unset_cellicon(mpte, NULL, 1);
3381 }
3382
3383 mpte->mpte_used_wifi = 1;
3384 }
3385
3386 /*
3387 * Don't propagate EWOULDBLOCK - it's already taken care of
3388 * in mptcp_usr_send for TFO.
3389 */
3390 error = 0;
3391 } else {
3392 /* We need to revert our change to mpts_rel_seq */
3393 mpts->mpts_rel_seq -= tot_sent;
3394
3395 os_log_error(mptcp_log_handle, "%s - %lx: %u error %d len %d subflags %#x sostate %#x soerror %u hiwat %u lowat %u\n",
3396 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), mpts->mpts_connid, error, tot_sent, so->so_flags, so->so_state, so->so_error, so->so_snd.sb_hiwat, so->so_snd.sb_lowat);
3397 }
3398 out:
3399
3400 if (head != NULL) {
3401 m_freem(head);
3402 }
3403
3404 if (wakeup) {
3405 mpte->mpte_mppcb->mpp_flags |= MPP_SHOULD_WWAKEUP;
3406 }
3407
3408 mptcp_handle_deferred_upcalls(mpte->mpte_mppcb, MPP_INSIDE_OUTPUT);
3409 return error;
3410 }
3411
3412 static void
mptcp_add_reinjectq(struct mptses * mpte,struct mbuf * m)3413 mptcp_add_reinjectq(struct mptses *mpte, struct mbuf *m)
3414 {
3415 struct mbuf *n, *prev = NULL;
3416
3417 n = mpte->mpte_reinjectq;
3418
3419 /* First, look for an mbuf n, whose data-sequence-number is bigger or
3420 * equal than m's sequence number.
3421 */
3422 while (n) {
3423 if (MPTCP_SEQ_GEQ(n->m_pkthdr.mp_dsn, m->m_pkthdr.mp_dsn)) {
3424 break;
3425 }
3426
3427 prev = n;
3428
3429 n = n->m_nextpkt;
3430 }
3431
3432 if (n) {
3433 /* m is already fully covered by the next mbuf in the queue */
3434 if (n->m_pkthdr.mp_dsn == m->m_pkthdr.mp_dsn &&
3435 n->m_pkthdr.mp_rlen >= m->m_pkthdr.mp_rlen) {
3436 os_log(mptcp_log_handle, "%s - %lx: dsn %u dlen %u rseq %u fully covered with len %u\n",
3437 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte),
3438 (uint32_t)m->m_pkthdr.mp_dsn, m->m_pkthdr.mp_rlen,
3439 m->m_pkthdr.mp_rseq, n->m_pkthdr.mp_rlen);
3440 goto dont_queue;
3441 }
3442
3443 /* m is covering the next mbuf entirely, thus we remove this guy */
3444 if (m->m_pkthdr.mp_dsn + m->m_pkthdr.mp_rlen >= n->m_pkthdr.mp_dsn + n->m_pkthdr.mp_rlen) {
3445 struct mbuf *tmp = n->m_nextpkt;
3446
3447 os_log(mptcp_log_handle, "%s - %lx: m (dsn %u len %u) is covering existing mbuf (dsn %u len %u)\n",
3448 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte),
3449 (uint32_t)m->m_pkthdr.mp_dsn, m->m_pkthdr.mp_rlen,
3450 (uint32_t)n->m_pkthdr.mp_dsn, n->m_pkthdr.mp_rlen);
3451
3452 m->m_nextpkt = NULL;
3453 if (prev == NULL) {
3454 mpte->mpte_reinjectq = tmp;
3455 } else {
3456 prev->m_nextpkt = tmp;
3457 }
3458
3459 m_freem(n);
3460 n = tmp;
3461 }
3462 }
3463
3464 if (prev) {
3465 /* m is already fully covered by the previous mbuf in the queue */
3466 if (prev->m_pkthdr.mp_dsn + prev->m_pkthdr.mp_rlen >= m->m_pkthdr.mp_dsn + m->m_pkthdr.len) {
3467 os_log(mptcp_log_handle, "%s - %lx: prev (dsn %u len %u) covers us (dsn %u len %u)\n",
3468 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte),
3469 (uint32_t)prev->m_pkthdr.mp_dsn, prev->m_pkthdr.mp_rlen,
3470 (uint32_t)m->m_pkthdr.mp_dsn, m->m_pkthdr.mp_rlen);
3471 goto dont_queue;
3472 }
3473 }
3474
3475 if (prev == NULL) {
3476 mpte->mpte_reinjectq = m;
3477 } else {
3478 prev->m_nextpkt = m;
3479 }
3480
3481 m->m_nextpkt = n;
3482
3483 return;
3484
3485 dont_queue:
3486 m_freem(m);
3487 return;
3488 }
3489
3490 static struct mbuf *
mptcp_lookup_dsn(struct mptses * mpte,uint64_t dsn)3491 mptcp_lookup_dsn(struct mptses *mpte, uint64_t dsn)
3492 {
3493 struct socket *mp_so = mptetoso(mpte);
3494 struct mbuf *m;
3495
3496 m = mp_so->so_snd.sb_mb;
3497
3498 while (m) {
3499 /* If this segment covers what we are looking for, return it. */
3500 if (MPTCP_SEQ_LEQ(m->m_pkthdr.mp_dsn, dsn) &&
3501 MPTCP_SEQ_GT(m->m_pkthdr.mp_dsn + m->m_pkthdr.mp_rlen, dsn)) {
3502 break;
3503 }
3504
3505
3506 /* Segment is no more in the queue */
3507 if (MPTCP_SEQ_GT(m->m_pkthdr.mp_dsn, dsn)) {
3508 return NULL;
3509 }
3510
3511 m = m->m_next;
3512 }
3513
3514 return m;
3515 }
3516
3517 static struct mbuf *
mptcp_copy_mbuf_list(struct mptses * mpte,struct mbuf * m,int len)3518 mptcp_copy_mbuf_list(struct mptses *mpte, struct mbuf *m, int len)
3519 {
3520 struct mbuf *top = NULL, *tail = NULL;
3521 uint64_t dsn;
3522 uint32_t dlen, rseq;
3523
3524 dsn = m->m_pkthdr.mp_dsn;
3525 dlen = m->m_pkthdr.mp_rlen;
3526 rseq = m->m_pkthdr.mp_rseq;
3527
3528 while (len > 0) {
3529 struct mbuf *n;
3530
3531 VERIFY((m->m_flags & M_PKTHDR) && (m->m_pkthdr.pkt_flags & PKTF_MPTCP));
3532
3533 n = m_copym_mode(m, 0, m->m_len, M_DONTWAIT, NULL, NULL, M_COPYM_MUST_COPY_HDR);
3534 if (n == NULL) {
3535 os_log_error(mptcp_log_handle, "%s - %lx: m_copym_mode returned NULL\n",
3536 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte));
3537 goto err;
3538 }
3539
3540 VERIFY(n->m_flags & M_PKTHDR);
3541 VERIFY(n->m_next == NULL);
3542 VERIFY(n->m_pkthdr.mp_dsn == dsn);
3543 VERIFY(n->m_pkthdr.mp_rlen == dlen);
3544 VERIFY(n->m_pkthdr.mp_rseq == rseq);
3545 VERIFY(n->m_len == m->m_len);
3546
3547 n->m_pkthdr.pkt_flags |= (PKTF_MPSO | PKTF_MPTCP);
3548
3549 if (top == NULL) {
3550 top = n;
3551 }
3552
3553 if (tail != NULL) {
3554 tail->m_next = n;
3555 }
3556
3557 tail = n;
3558
3559 len -= m->m_len;
3560 m = m->m_next;
3561 }
3562
3563 return top;
3564
3565 err:
3566 if (top) {
3567 m_freem(top);
3568 }
3569
3570 return NULL;
3571 }
3572
3573 static void
mptcp_reinject_mbufs(struct socket * so)3574 mptcp_reinject_mbufs(struct socket *so)
3575 {
3576 struct tcpcb *tp = sototcpcb(so);
3577 struct mptsub *mpts = tp->t_mpsub;
3578 struct mptcb *mp_tp = tptomptp(tp);
3579 struct mptses *mpte = mp_tp->mpt_mpte;
3580 struct sockbuf *sb = &so->so_snd;
3581 struct mbuf *m;
3582
3583 m = sb->sb_mb;
3584 while (m) {
3585 struct mbuf *n = m->m_next, *orig = m;
3586 bool set_reinject_flag = false;
3587
3588 VERIFY((m->m_flags & M_PKTHDR) && (m->m_pkthdr.pkt_flags & PKTF_MPTCP));
3589
3590 if (m->m_pkthdr.pkt_flags & PKTF_MPTCP_REINJ) {
3591 goto next;
3592 }
3593
3594 /* Has it all already been acknowledged at the data-level? */
3595 if (MPTCP_SEQ_GEQ(mp_tp->mpt_snduna, m->m_pkthdr.mp_dsn + m->m_pkthdr.mp_rlen)) {
3596 goto next;
3597 }
3598
3599 /* Part of this has already been acknowledged - lookup in the
3600 * MPTCP-socket for the segment.
3601 */
3602 if (SEQ_GT(tp->snd_una - mpts->mpts_iss, m->m_pkthdr.mp_rseq)) {
3603 m = mptcp_lookup_dsn(mpte, m->m_pkthdr.mp_dsn);
3604 if (m == NULL) {
3605 goto next;
3606 }
3607 }
3608
3609 /* Copy the mbuf with headers (aka, DSN-numbers) */
3610 m = mptcp_copy_mbuf_list(mpte, m, m->m_pkthdr.mp_rlen);
3611 if (m == NULL) {
3612 break;
3613 }
3614
3615 VERIFY(m->m_nextpkt == NULL);
3616
3617 /* Now, add to the reinject-queue, eliminating overlapping
3618 * segments
3619 */
3620 mptcp_add_reinjectq(mpte, m);
3621
3622 set_reinject_flag = true;
3623 orig->m_pkthdr.pkt_flags |= PKTF_MPTCP_REINJ;
3624
3625 next:
3626 /* mp_rlen can cover multiple mbufs, so advance to the end of it. */
3627 while (n) {
3628 VERIFY((n->m_flags & M_PKTHDR) && (n->m_pkthdr.pkt_flags & PKTF_MPTCP));
3629
3630 if (n->m_pkthdr.mp_dsn != orig->m_pkthdr.mp_dsn) {
3631 break;
3632 }
3633
3634 if (set_reinject_flag) {
3635 n->m_pkthdr.pkt_flags |= PKTF_MPTCP_REINJ;
3636 }
3637 n = n->m_next;
3638 }
3639
3640 m = n;
3641 }
3642 }
3643
3644 void
mptcp_clean_reinjectq(struct mptses * mpte)3645 mptcp_clean_reinjectq(struct mptses *mpte)
3646 {
3647 struct mptcb *mp_tp = mpte->mpte_mptcb;
3648
3649 socket_lock_assert_owned(mptetoso(mpte));
3650
3651 while (mpte->mpte_reinjectq) {
3652 struct mbuf *m = mpte->mpte_reinjectq;
3653
3654 if (MPTCP_SEQ_GEQ(m->m_pkthdr.mp_dsn, mp_tp->mpt_snduna) ||
3655 MPTCP_SEQ_GT(m->m_pkthdr.mp_dsn + m->m_pkthdr.mp_rlen, mp_tp->mpt_snduna)) {
3656 break;
3657 }
3658
3659 mpte->mpte_reinjectq = m->m_nextpkt;
3660 m->m_nextpkt = NULL;
3661 m_freem(m);
3662 }
3663 }
3664
3665 static ev_ret_t
mptcp_subflow_propagate_ev(struct mptses * mpte,struct mptsub * mpts,uint32_t * p_mpsofilt_hint,uint32_t event)3666 mptcp_subflow_propagate_ev(struct mptses *mpte, struct mptsub *mpts,
3667 uint32_t *p_mpsofilt_hint, uint32_t event)
3668 {
3669 struct socket *mp_so, *so;
3670 struct mptcb *mp_tp;
3671
3672 mp_so = mptetoso(mpte);
3673 mp_tp = mpte->mpte_mptcb;
3674 so = mpts->mpts_socket;
3675
3676 /*
3677 * We got an event for this subflow that might need to be propagated,
3678 * based on the state of the MPTCP connection.
3679 */
3680 if (mp_tp->mpt_state < MPTCPS_ESTABLISHED ||
3681 (!(mp_tp->mpt_flags & MPTCPF_JOIN_READY) && !(mpts->mpts_flags & MPTSF_MP_READY)) ||
3682 ((mp_tp->mpt_flags & MPTCPF_FALLBACK_TO_TCP) && (mpts->mpts_flags & MPTSF_ACTIVE))) {
3683 mp_so->so_error = so->so_error;
3684 *p_mpsofilt_hint |= event;
3685 }
3686
3687 return MPTS_EVRET_OK;
3688 }
3689
3690 /*
3691 * Handle SO_FILT_HINT_NOSRCADDR subflow socket event.
3692 */
3693 static ev_ret_t
mptcp_subflow_nosrcaddr_ev(struct mptses * mpte,struct mptsub * mpts,uint32_t * p_mpsofilt_hint,uint32_t event)3694 mptcp_subflow_nosrcaddr_ev(struct mptses *mpte, struct mptsub *mpts,
3695 uint32_t *p_mpsofilt_hint, uint32_t event)
3696 {
3697 struct socket *mp_so;
3698 struct tcpcb *tp;
3699
3700 mp_so = mptetoso(mpte);
3701 tp = intotcpcb(sotoinpcb(mpts->mpts_socket));
3702
3703 /*
3704 * This overwrites any previous mpte_lost_aid to avoid storing
3705 * too much state when the typical case has only two subflows.
3706 */
3707 mpte->mpte_flags |= MPTE_SND_REM_ADDR;
3708 mpte->mpte_lost_aid = tp->t_local_aid;
3709
3710 /*
3711 * The subflow connection has lost its source address.
3712 */
3713 mptcp_subflow_abort(mpts, EADDRNOTAVAIL);
3714
3715 if (mp_so->so_flags & SOF_NOADDRAVAIL) {
3716 mptcp_subflow_propagate_ev(mpte, mpts, p_mpsofilt_hint, event);
3717 }
3718
3719 return MPTS_EVRET_DELETE;
3720 }
3721
3722 static ev_ret_t
mptcp_subflow_mpsuberror_ev(struct mptses * mpte,struct mptsub * mpts,uint32_t * p_mpsofilt_hint,uint32_t event)3723 mptcp_subflow_mpsuberror_ev(struct mptses *mpte, struct mptsub *mpts,
3724 uint32_t *p_mpsofilt_hint, uint32_t event)
3725 {
3726 #pragma unused(event, p_mpsofilt_hint)
3727 struct socket *so, *mp_so;
3728
3729 so = mpts->mpts_socket;
3730
3731 if (so->so_error != ENODATA) {
3732 return MPTS_EVRET_OK;
3733 }
3734
3735
3736 mp_so = mptetoso(mpte);
3737
3738 mp_so->so_error = ENODATA;
3739
3740 sorwakeup(mp_so);
3741 sowwakeup(mp_so);
3742
3743 return MPTS_EVRET_OK;
3744 }
3745
3746
3747 /*
3748 * Handle SO_FILT_HINT_MPCANTRCVMORE subflow socket event that
3749 * indicates that the remote side sent a Data FIN
3750 */
3751 static ev_ret_t
mptcp_subflow_mpcantrcvmore_ev(struct mptses * mpte,struct mptsub * mpts,uint32_t * p_mpsofilt_hint,uint32_t event)3752 mptcp_subflow_mpcantrcvmore_ev(struct mptses *mpte, struct mptsub *mpts,
3753 uint32_t *p_mpsofilt_hint, uint32_t event)
3754 {
3755 #pragma unused(event, mpts)
3756 struct mptcb *mp_tp = mpte->mpte_mptcb;
3757
3758 /*
3759 * We got a Data FIN for the MPTCP connection.
3760 * The FIN may arrive with data. The data is handed up to the
3761 * mptcp socket and the user is notified so that it may close
3762 * the socket if needed.
3763 */
3764 if (mp_tp->mpt_state == MPTCPS_CLOSE_WAIT) {
3765 *p_mpsofilt_hint |= SO_FILT_HINT_CANTRCVMORE;
3766 }
3767
3768 return MPTS_EVRET_OK; /* keep the subflow socket around */
3769 }
3770
3771 /*
3772 * Handle SO_FILT_HINT_MPFAILOVER subflow socket event
3773 */
3774 static ev_ret_t
mptcp_subflow_failover_ev(struct mptses * mpte,struct mptsub * mpts,uint32_t * p_mpsofilt_hint,uint32_t event)3775 mptcp_subflow_failover_ev(struct mptses *mpte, struct mptsub *mpts,
3776 uint32_t *p_mpsofilt_hint, uint32_t event)
3777 {
3778 #pragma unused(event, p_mpsofilt_hint)
3779 struct mptsub *mpts_alt = NULL;
3780 struct socket *alt_so = NULL;
3781 struct socket *mp_so;
3782 int altpath_exists = 0;
3783
3784 mp_so = mptetoso(mpte);
3785 os_log_info(mptcp_log_handle, "%s - %lx\n", __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte));
3786
3787 mptcp_reinject_mbufs(mpts->mpts_socket);
3788
3789 mpts_alt = mptcp_get_subflow(mpte, NULL);
3790
3791 /* If there is no alternate eligible subflow, ignore the failover hint. */
3792 if (mpts_alt == NULL || mpts_alt == mpts) {
3793 os_log(mptcp_log_handle, "%s - %lx no alternate path\n", __func__,
3794 (unsigned long)VM_KERNEL_ADDRPERM(mpte));
3795
3796 goto done;
3797 }
3798
3799 altpath_exists = 1;
3800 alt_so = mpts_alt->mpts_socket;
3801 if (mpts_alt->mpts_flags & MPTSF_FAILINGOVER) {
3802 /* All data acknowledged and no RTT spike */
3803 if (alt_so->so_snd.sb_cc == 0 && mptcp_no_rto_spike(alt_so)) {
3804 mpts_alt->mpts_flags &= ~MPTSF_FAILINGOVER;
3805 } else {
3806 /* no alternate path available */
3807 altpath_exists = 0;
3808 }
3809 }
3810
3811 if (altpath_exists) {
3812 mpts_alt->mpts_flags |= MPTSF_ACTIVE;
3813
3814 mpte->mpte_active_sub = mpts_alt;
3815 mpts->mpts_flags |= MPTSF_FAILINGOVER;
3816 mpts->mpts_flags &= ~MPTSF_ACTIVE;
3817
3818 os_log_info(mptcp_log_handle, "%s - %lx: switched from %d to %d\n",
3819 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), mpts->mpts_connid, mpts_alt->mpts_connid);
3820
3821 mptcpstats_inc_switch(mpte, mpts);
3822
3823 sowwakeup(alt_so);
3824 } else {
3825 done:
3826 mpts->mpts_socket->so_flags &= ~SOF_MP_TRYFAILOVER;
3827 }
3828
3829 return MPTS_EVRET_OK;
3830 }
3831
3832 /*
3833 * Handle SO_FILT_HINT_IFDENIED subflow socket event.
3834 */
3835 static ev_ret_t
mptcp_subflow_ifdenied_ev(struct mptses * mpte,struct mptsub * mpts,uint32_t * p_mpsofilt_hint,uint32_t event)3836 mptcp_subflow_ifdenied_ev(struct mptses *mpte, struct mptsub *mpts,
3837 uint32_t *p_mpsofilt_hint, uint32_t event)
3838 {
3839 /*
3840 * The subflow connection cannot use the outgoing interface, let's
3841 * close this subflow.
3842 */
3843 mptcp_subflow_abort(mpts, EPERM);
3844
3845 mptcp_subflow_propagate_ev(mpte, mpts, p_mpsofilt_hint, event);
3846
3847 return MPTS_EVRET_DELETE;
3848 }
3849
3850 /*
3851 * https://tools.ietf.org/html/rfc6052#section-2
3852 * https://tools.ietf.org/html/rfc6147#section-5.2
3853 */
3854 static boolean_t
mptcp_desynthesize_ipv6_addr(struct mptses * mpte,const struct in6_addr * addr0,const struct ipv6_prefix * prefix,struct in_addr * addrv4_0)3855 mptcp_desynthesize_ipv6_addr(struct mptses *mpte, const struct in6_addr *addr0,
3856 const struct ipv6_prefix *prefix,
3857 struct in_addr *addrv4_0)
3858 {
3859 char buf[MAX_IPv4_STR_LEN];
3860 const struct in6_addr *addr = addr0;
3861 const char *ptr = (const char *)addr;
3862 struct in_addr *addrv4 = addrv4_0;
3863 char *ptrv4 = (char *)addrv4;
3864
3865 if (memcmp(ptr, &prefix->ipv6_prefix, prefix->prefix_len) != 0) {
3866 return false;
3867 }
3868
3869 switch (prefix->prefix_len) {
3870 case NAT64_PREFIX_LEN_96:
3871 memcpy(ptrv4, ptr + 12, 4);
3872 break;
3873 case NAT64_PREFIX_LEN_64:
3874 memcpy(ptrv4, ptr + 9, 4);
3875 break;
3876 case NAT64_PREFIX_LEN_56:
3877 memcpy(ptrv4, ptr + 7, 1);
3878 memcpy(ptrv4 + 1, ptr + 9, 3);
3879 break;
3880 case NAT64_PREFIX_LEN_48:
3881 memcpy(ptrv4, ptr + 6, 2);
3882 memcpy(ptrv4 + 2, ptr + 9, 2);
3883 break;
3884 case NAT64_PREFIX_LEN_40:
3885 memcpy(ptrv4, ptr + 5, 3);
3886 memcpy(ptrv4 + 3, ptr + 9, 1);
3887 break;
3888 case NAT64_PREFIX_LEN_32:
3889 memcpy(ptrv4, ptr + 4, 4);
3890 break;
3891 default:
3892 panic("NAT64-prefix len is wrong: %u",
3893 prefix->prefix_len);
3894 }
3895
3896 os_log_info(mptcp_log_handle, "%s - %lx: desynthesized to %s\n", __func__,
3897 (unsigned long)VM_KERNEL_ADDRPERM(mpte),
3898 inet_ntop(AF_INET, (void *)addrv4, buf, sizeof(buf)));
3899
3900 return true;
3901 }
3902
3903 static void
mptcp_handle_ipv6_connection(struct mptses * mpte,const struct mptsub * mpts)3904 mptcp_handle_ipv6_connection(struct mptses *mpte, const struct mptsub *mpts)
3905 {
3906 struct ipv6_prefix nat64prefixes[NAT64_MAX_NUM_PREFIXES];
3907 struct socket *so = mpts->mpts_socket;
3908 struct ifnet *ifp;
3909 int j;
3910
3911 /* Subflow IPs will be steered directly by the server - no need to
3912 * desynthesize.
3913 */
3914 if (mpte->mpte_flags & MPTE_UNICAST_IP) {
3915 return;
3916 }
3917
3918 ifp = sotoinpcb(so)->inp_last_outifp;
3919
3920 if (ifnet_get_nat64prefix(ifp, nat64prefixes) == ENOENT) {
3921 return;
3922 }
3923
3924 for (j = 0; j < NAT64_MAX_NUM_PREFIXES; j++) {
3925 int success;
3926
3927 if (nat64prefixes[j].prefix_len == 0) {
3928 continue;
3929 }
3930
3931 success = mptcp_desynthesize_ipv6_addr(mpte,
3932 &mpte->__mpte_dst_v6.sin6_addr,
3933 &nat64prefixes[j],
3934 &mpte->mpte_sub_dst_v4.sin_addr);
3935 if (success) {
3936 mpte->mpte_sub_dst_v4.sin_len = sizeof(mpte->mpte_sub_dst_v4);
3937 mpte->mpte_sub_dst_v4.sin_family = AF_INET;
3938 mpte->mpte_sub_dst_v4.sin_port = mpte->__mpte_dst_v6.sin6_port;
3939
3940 /*
3941 * We connected to a NAT64'ed address. Let's remove it
3942 * from the potential IPs to use. Whenever we are back on
3943 * that network and need to connect, we can synthesize again.
3944 *
3945 * Otherwise, on different IPv6 networks we will attempt
3946 * to connect to that NAT64 address...
3947 */
3948 memset(&mpte->mpte_sub_dst_v6, 0, sizeof(mpte->mpte_sub_dst_v6));
3949 break;
3950 }
3951 }
3952 }
3953
3954 static void
mptcp_try_alternate_port(struct mptses * mpte,struct mptsub * mpts)3955 mptcp_try_alternate_port(struct mptses *mpte, struct mptsub *mpts)
3956 {
3957 struct inpcb *inp;
3958
3959 if (!mptcp_ok_to_create_subflows(mpte->mpte_mptcb)) {
3960 return;
3961 }
3962
3963 inp = sotoinpcb(mpts->mpts_socket);
3964 if (inp == NULL) {
3965 return;
3966 }
3967
3968 /* Should we try the alternate port? */
3969 if (mpte->mpte_alternate_port &&
3970 inp->inp_fport != mpte->mpte_alternate_port) {
3971 union sockaddr_in_4_6 dst;
3972 struct sockaddr_in *dst_in = SIN(&dst);
3973
3974 SOCKADDR_COPY(&mpts->mpts_dst, &dst, mpts->mpts_dst.sa_len);
3975
3976 dst_in->sin_port = mpte->mpte_alternate_port;
3977
3978 mptcp_subflow_add(mpte, NULL, SA(&dst), mpts->mpts_ifscope, NULL);
3979 } else { /* Else, we tried all we could, mark this interface as non-MPTCP */
3980 unsigned int i;
3981
3982 if (inp->inp_last_outifp == NULL) {
3983 return;
3984 }
3985
3986 for (i = 0; i < mpte->mpte_itfinfo_size; i++) {
3987 struct mpt_itf_info *info = &mpte->mpte_itfinfo[i];
3988
3989 if (inp->inp_last_outifp->if_index == info->ifindex) {
3990 info->no_mptcp_support = 1;
3991 break;
3992 }
3993 }
3994 }
3995 }
3996
3997 /* If TFO data is succesfully acked, it must be dropped from the mptcp so */
3998 static void
mptcp_drop_tfo_data(struct mptses * mpte,struct mptsub * mpts)3999 mptcp_drop_tfo_data(struct mptses *mpte, struct mptsub *mpts)
4000 {
4001 struct socket *mp_so = mptetoso(mpte);
4002 struct socket *so = mpts->mpts_socket;
4003 struct tcpcb *tp = intotcpcb(sotoinpcb(so));
4004 struct mptcb *mp_tp = mpte->mpte_mptcb;
4005
4006 /* If data was sent with SYN, rewind state */
4007 if (tp->t_tfo_stats & TFO_S_SYN_DATA_ACKED) {
4008 u_int64_t mp_droplen = mp_tp->mpt_sndnxt - mp_tp->mpt_snduna;
4009 unsigned int tcp_droplen = tp->snd_una - tp->iss - 1;
4010
4011 VERIFY(mp_droplen <= (UINT_MAX));
4012 VERIFY(mp_droplen >= tcp_droplen);
4013
4014 mpts->mpts_flags &= ~MPTSF_TFO_REQD;
4015 mpts->mpts_iss += tcp_droplen;
4016 tp->t_mpflags &= ~TMPF_TFO_REQUEST;
4017
4018 if (mp_droplen > tcp_droplen) {
4019 /* handle partial TCP ack */
4020 mp_so->so_flags1 |= SOF1_TFO_REWIND;
4021 mp_tp->mpt_sndnxt = mp_tp->mpt_snduna + (mp_droplen - tcp_droplen);
4022 mp_droplen = tcp_droplen;
4023 } else {
4024 /* all data on SYN was acked */
4025 mpts->mpts_rel_seq = 1;
4026 mp_tp->mpt_sndnxt = mp_tp->mpt_snduna;
4027 }
4028 mp_tp->mpt_sndmax -= tcp_droplen;
4029
4030 if (mp_droplen != 0) {
4031 VERIFY(mp_so->so_snd.sb_mb != NULL);
4032 sbdrop(&mp_so->so_snd, (int)mp_droplen);
4033 }
4034 }
4035 }
4036
4037 /*
4038 * Handle SO_FILT_HINT_CONNECTED subflow socket event.
4039 */
4040 static ev_ret_t
mptcp_subflow_connected_ev(struct mptses * mpte,struct mptsub * mpts,uint32_t * p_mpsofilt_hint,uint32_t event)4041 mptcp_subflow_connected_ev(struct mptses *mpte, struct mptsub *mpts,
4042 uint32_t *p_mpsofilt_hint, uint32_t event)
4043 {
4044 #pragma unused(event, p_mpsofilt_hint)
4045 struct socket *mp_so, *so;
4046 struct inpcb *inp;
4047 struct tcpcb *tp;
4048 struct mptcb *mp_tp;
4049 int af;
4050 boolean_t mpok = FALSE;
4051
4052 mp_so = mptetoso(mpte);
4053 mp_tp = mpte->mpte_mptcb;
4054 so = mpts->mpts_socket;
4055 tp = sototcpcb(so);
4056 af = mpts->mpts_dst.sa_family;
4057
4058 if (mpts->mpts_flags & MPTSF_CONNECTED) {
4059 return MPTS_EVRET_OK;
4060 }
4061
4062 if ((mpts->mpts_flags & MPTSF_DISCONNECTED) ||
4063 (mpts->mpts_flags & MPTSF_DISCONNECTING)) {
4064 return MPTS_EVRET_OK;
4065 }
4066
4067 /*
4068 * The subflow connection has been connected. Find out whether it
4069 * is connected as a regular TCP or as a MPTCP subflow. The idea is:
4070 *
4071 * a. If MPTCP connection is not yet established, then this must be
4072 * the first subflow connection. If MPTCP failed to negotiate,
4073 * fallback to regular TCP by degrading this subflow.
4074 *
4075 * b. If MPTCP connection has been established, then this must be
4076 * one of the subsequent subflow connections. If MPTCP failed
4077 * to negotiate, disconnect the connection.
4078 *
4079 * Right now, we simply unblock any waiters at the MPTCP socket layer
4080 * if the MPTCP connection has not been established.
4081 */
4082
4083 if (so->so_state & SS_ISDISCONNECTED) {
4084 /*
4085 * With MPTCP joins, a connection is connected at the subflow
4086 * level, but the 4th ACK from the server elevates the MPTCP
4087 * subflow to connected state. So there is a small window
4088 * where the subflow could get disconnected before the
4089 * connected event is processed.
4090 */
4091 return MPTS_EVRET_OK;
4092 }
4093
4094 if (mpts->mpts_flags & MPTSF_TFO_REQD) {
4095 mptcp_drop_tfo_data(mpte, mpts);
4096 }
4097
4098 mpts->mpts_flags &= ~(MPTSF_CONNECTING | MPTSF_TFO_REQD);
4099 mpts->mpts_flags |= MPTSF_CONNECTED;
4100
4101 if (tp->t_mpflags & TMPF_MPTCP_TRUE) {
4102 mpts->mpts_flags |= MPTSF_MP_CAPABLE;
4103 }
4104
4105 tp->t_mpflags &= ~TMPF_TFO_REQUEST;
4106
4107 /* get/verify the outbound interface */
4108 inp = sotoinpcb(so);
4109
4110 mpts->mpts_maxseg = tp->t_maxseg;
4111
4112 mpok = (mpts->mpts_flags & MPTSF_MP_CAPABLE);
4113
4114 if (mp_tp->mpt_state < MPTCPS_ESTABLISHED) {
4115 mp_tp->mpt_state = MPTCPS_ESTABLISHED;
4116 mpte->mpte_associd = mpts->mpts_connid;
4117 DTRACE_MPTCP2(state__change,
4118 struct mptcb *, mp_tp,
4119 uint32_t, 0 /* event */);
4120
4121 if (SOCK_DOM(so) == AF_INET) {
4122 in_getsockaddr_s(so, &mpte->__mpte_src_v4);
4123 } else {
4124 in6_getsockaddr_s(so, &mpte->__mpte_src_v6);
4125 }
4126
4127 mpts->mpts_flags |= MPTSF_ACTIVE;
4128
4129 /* case (a) above */
4130 if (!mpok) {
4131 tcpstat.tcps_mpcap_fallback++;
4132
4133 tp->t_mpflags |= TMPF_INFIN_SENT;
4134 mptcp_notify_mpfail(so);
4135 } else {
4136 if (IFNET_IS_CELLULAR(inp->inp_last_outifp) &&
4137 mptcp_subflows_need_backup_flag(mpte)) {
4138 tp->t_mpflags |= (TMPF_BACKUP_PATH | TMPF_SND_MPPRIO);
4139 } else {
4140 mpts->mpts_flags |= MPTSF_PREFERRED;
4141 }
4142 mpts->mpts_flags |= MPTSF_MPCAP_CTRSET;
4143 mpte->mpte_nummpcapflows++;
4144
4145 if (SOCK_DOM(so) == AF_INET6) {
4146 mptcp_handle_ipv6_connection(mpte, mpts);
4147 }
4148
4149 mptcp_check_subflows_and_add(mpte);
4150
4151 if (IFNET_IS_CELLULAR(inp->inp_last_outifp)) {
4152 mpte->mpte_initial_cell = 1;
4153 }
4154
4155 mpte->mpte_handshake_success = 1;
4156 }
4157
4158 mp_tp->mpt_sndwnd = tp->snd_wnd;
4159 mp_tp->mpt_sndwl1 = mp_tp->mpt_rcvnxt;
4160 mp_tp->mpt_sndwl2 = mp_tp->mpt_snduna;
4161 soisconnected(mp_so);
4162 } else if (mpok) {
4163 /*
4164 * case (b) above
4165 * In case of additional flows, the MPTCP socket is not
4166 * MPTSF_MP_CAPABLE until an ACK is received from server
4167 * for 3-way handshake. TCP would have guaranteed that this
4168 * is an MPTCP subflow.
4169 */
4170 if (IFNET_IS_CELLULAR(inp->inp_last_outifp) &&
4171 !(tp->t_mpflags & TMPF_BACKUP_PATH) &&
4172 mptcp_subflows_need_backup_flag(mpte)) {
4173 tp->t_mpflags |= (TMPF_BACKUP_PATH | TMPF_SND_MPPRIO);
4174 mpts->mpts_flags &= ~MPTSF_PREFERRED;
4175 } else {
4176 mpts->mpts_flags |= MPTSF_PREFERRED;
4177 }
4178
4179 mpts->mpts_flags |= MPTSF_MPCAP_CTRSET;
4180 mpte->mpte_nummpcapflows++;
4181
4182 mpts->mpts_rel_seq = 1;
4183
4184 mptcp_check_subflows_and_remove(mpte);
4185 } else {
4186 mptcp_try_alternate_port(mpte, mpts);
4187
4188 tcpstat.tcps_join_fallback++;
4189 if (IFNET_IS_CELLULAR(inp->inp_last_outifp)) {
4190 tcpstat.tcps_mptcp_cell_proxy++;
4191 } else {
4192 tcpstat.tcps_mptcp_wifi_proxy++;
4193 }
4194
4195 soevent(mpts->mpts_socket, SO_FILT_HINT_LOCKED | SO_FILT_HINT_MUSTRST);
4196
4197 return MPTS_EVRET_OK;
4198 }
4199
4200 /* This call, just to "book" an entry in the stats-table for this ifindex */
4201 mptcpstats_get_index(mpte->mpte_itfstats, MPTCP_ITFSTATS_SIZE, mpts);
4202
4203 mptcp_output(mpte);
4204
4205 return MPTS_EVRET_OK; /* keep the subflow socket around */
4206 }
4207
4208 /*
4209 * Handle SO_FILT_HINT_DISCONNECTED subflow socket event.
4210 */
4211 static ev_ret_t
mptcp_subflow_disconnected_ev(struct mptses * mpte,struct mptsub * mpts,uint32_t * p_mpsofilt_hint,uint32_t event)4212 mptcp_subflow_disconnected_ev(struct mptses *mpte, struct mptsub *mpts,
4213 uint32_t *p_mpsofilt_hint, uint32_t event)
4214 {
4215 #pragma unused(event, p_mpsofilt_hint)
4216 struct socket *mp_so, *so;
4217 struct mptcb *mp_tp;
4218
4219 mp_so = mptetoso(mpte);
4220 mp_tp = mpte->mpte_mptcb;
4221 so = mpts->mpts_socket;
4222
4223 if (mpts->mpts_flags & MPTSF_DISCONNECTED) {
4224 return MPTS_EVRET_DELETE;
4225 }
4226
4227 mpts->mpts_flags |= MPTSF_DISCONNECTED;
4228
4229 /* The subflow connection has been disconnected. */
4230
4231 if (mpts->mpts_flags & MPTSF_MPCAP_CTRSET) {
4232 mpte->mpte_nummpcapflows--;
4233 if (mpte->mpte_active_sub == mpts) {
4234 mpte->mpte_active_sub = NULL;
4235 }
4236 mpts->mpts_flags &= ~MPTSF_MPCAP_CTRSET;
4237 } else {
4238 if (so->so_flags & SOF_MP_SEC_SUBFLOW &&
4239 !(mpts->mpts_flags & MPTSF_CONNECTED)) {
4240 mptcp_try_alternate_port(mpte, mpts);
4241 }
4242 }
4243
4244 if (mp_tp->mpt_state < MPTCPS_ESTABLISHED ||
4245 ((mp_tp->mpt_flags & MPTCPF_FALLBACK_TO_TCP) && (mpts->mpts_flags & MPTSF_ACTIVE))) {
4246 mptcp_drop(mpte, mp_tp, so->so_error);
4247 }
4248
4249 /*
4250 * Clear flags that are used by getconninfo to return state.
4251 * Retain like MPTSF_DELETEOK for internal purposes.
4252 */
4253 mpts->mpts_flags &= ~(MPTSF_CONNECTING | MPTSF_CONNECT_PENDING |
4254 MPTSF_CONNECTED | MPTSF_DISCONNECTING | MPTSF_PREFERRED |
4255 MPTSF_MP_CAPABLE | MPTSF_MP_READY | MPTSF_MP_DEGRADED | MPTSF_ACTIVE);
4256
4257 return MPTS_EVRET_DELETE;
4258 }
4259
4260 /*
4261 * Handle SO_FILT_HINT_MPSTATUS subflow socket event
4262 */
4263 static ev_ret_t
mptcp_subflow_mpstatus_ev(struct mptses * mpte,struct mptsub * mpts,uint32_t * p_mpsofilt_hint,uint32_t event)4264 mptcp_subflow_mpstatus_ev(struct mptses *mpte, struct mptsub *mpts,
4265 uint32_t *p_mpsofilt_hint, uint32_t event)
4266 {
4267 #pragma unused(event, p_mpsofilt_hint)
4268 ev_ret_t ret = MPTS_EVRET_OK;
4269 struct socket *mp_so, *so;
4270 struct mptcb *mp_tp;
4271
4272 mp_so = mptetoso(mpte);
4273 mp_tp = mpte->mpte_mptcb;
4274 so = mpts->mpts_socket;
4275 struct inpcb *inp = sotoinpcb(so);
4276 struct tcpcb *tp = intotcpcb(inp);
4277
4278 if (sototcpcb(so)->t_mpflags & TMPF_MPTCP_TRUE) {
4279 mpts->mpts_flags |= MPTSF_MP_CAPABLE;
4280 } else {
4281 mpts->mpts_flags &= ~MPTSF_MP_CAPABLE;
4282 }
4283
4284 if (sototcpcb(so)->t_mpflags & TMPF_TCP_FALLBACK) {
4285 if (mpts->mpts_flags & MPTSF_MP_DEGRADED) {
4286 goto done;
4287 }
4288 mpts->mpts_flags |= MPTSF_MP_DEGRADED;
4289 } else {
4290 mpts->mpts_flags &= ~MPTSF_MP_DEGRADED;
4291 }
4292
4293 if (sototcpcb(so)->t_mpflags & TMPF_MPTCP_READY) {
4294 mpts->mpts_flags |= MPTSF_MP_READY;
4295 } else {
4296 mpts->mpts_flags &= ~MPTSF_MP_READY;
4297 }
4298
4299 if (mpts->mpts_flags & MPTSF_MP_DEGRADED) {
4300 mp_tp->mpt_flags |= MPTCPF_FALLBACK_TO_TCP;
4301 mp_tp->mpt_flags &= ~MPTCPF_JOIN_READY;
4302 tcp_cache_update_mptcp_version(tp, FALSE);
4303 }
4304
4305 if (mp_tp->mpt_flags & MPTCPF_FALLBACK_TO_TCP) {
4306 ret = MPTS_EVRET_DISCONNECT_FALLBACK;
4307
4308 m_freem_list(mpte->mpte_reinjectq);
4309 mpte->mpte_reinjectq = NULL;
4310 } else if (mpts->mpts_flags & MPTSF_MP_READY) {
4311 mp_tp->mpt_flags |= MPTCPF_JOIN_READY;
4312 ret = MPTS_EVRET_CONNECT_PENDING;
4313 }
4314
4315 done:
4316 return ret;
4317 }
4318
4319 /*
4320 * Handle SO_FILT_HINT_MUSTRST subflow socket event
4321 */
4322 static ev_ret_t
mptcp_subflow_mustrst_ev(struct mptses * mpte,struct mptsub * mpts,uint32_t * p_mpsofilt_hint,uint32_t event)4323 mptcp_subflow_mustrst_ev(struct mptses *mpte, struct mptsub *mpts,
4324 uint32_t *p_mpsofilt_hint, uint32_t event)
4325 {
4326 #pragma unused(event)
4327 struct socket *mp_so, *so;
4328 struct mptcb *mp_tp;
4329 boolean_t is_fastclose;
4330
4331 mp_so = mptetoso(mpte);
4332 mp_tp = mpte->mpte_mptcb;
4333 so = mpts->mpts_socket;
4334
4335 /* We got an invalid option or a fast close */
4336 struct inpcb *inp = sotoinpcb(so);
4337 struct tcpcb *tp = NULL;
4338
4339 tp = intotcpcb(inp);
4340 so->so_error = ECONNABORTED;
4341
4342 is_fastclose = !!(tp->t_mpflags & TMPF_FASTCLOSERCV);
4343
4344 tp->t_mpflags |= TMPF_RESET;
4345
4346 if (tp->t_state != TCPS_CLOSED) {
4347 mbuf_ref_t m;
4348 struct tcptemp *t_template = tcp_maketemplate(tp, &m);
4349
4350 if (t_template) {
4351 struct tcp_respond_args tra;
4352
4353 bzero(&tra, sizeof(tra));
4354 if (inp->inp_flags & INP_BOUND_IF) {
4355 tra.ifscope = inp->inp_boundifp->if_index;
4356 } else {
4357 tra.ifscope = IFSCOPE_NONE;
4358 }
4359 tra.awdl_unrestricted = 1;
4360
4361 tcp_respond(tp, t_template->tt_ipgen, sizeof(t_template->tt_ipgen),
4362 &t_template->tt_t, (struct mbuf *)NULL,
4363 tp->rcv_nxt, tp->snd_una, TH_RST, &tra);
4364 (void) m_free(m);
4365 }
4366 }
4367
4368 if (!(mp_tp->mpt_flags & MPTCPF_FALLBACK_TO_TCP) && is_fastclose) {
4369 struct mptsub *iter, *tmp;
4370
4371 *p_mpsofilt_hint |= SO_FILT_HINT_CONNRESET;
4372
4373 mp_so->so_error = ECONNRESET;
4374
4375 TAILQ_FOREACH_SAFE(iter, &mpte->mpte_subflows, mpts_entry, tmp) {
4376 if (iter == mpts) {
4377 continue;
4378 }
4379 mptcp_subflow_abort(iter, ECONNABORTED);
4380 }
4381
4382 /*
4383 * mptcp_drop is being called after processing the events, to fully
4384 * close the MPTCP connection
4385 */
4386 mptcp_drop(mpte, mp_tp, mp_so->so_error);
4387 }
4388
4389 mptcp_subflow_abort(mpts, ECONNABORTED);
4390
4391 if (mp_tp->mpt_gc_ticks == MPT_GC_TICKS) {
4392 mp_tp->mpt_gc_ticks = MPT_GC_TICKS_FAST;
4393 }
4394
4395 return MPTS_EVRET_DELETE;
4396 }
4397
4398 static ev_ret_t
mptcp_subflow_adaptive_rtimo_ev(struct mptses * mpte,struct mptsub * mpts,uint32_t * p_mpsofilt_hint,uint32_t event)4399 mptcp_subflow_adaptive_rtimo_ev(struct mptses *mpte, struct mptsub *mpts,
4400 uint32_t *p_mpsofilt_hint, uint32_t event)
4401 {
4402 #pragma unused(event)
4403 bool found_active = false;
4404
4405 mpts->mpts_flags |= MPTSF_READ_STALL;
4406
4407 TAILQ_FOREACH(mpts, &mpte->mpte_subflows, mpts_entry) {
4408 struct tcpcb *tp = sototcpcb(mpts->mpts_socket);
4409
4410 if (!TCPS_HAVEESTABLISHED(tp->t_state) ||
4411 TCPS_HAVERCVDFIN2(tp->t_state)) {
4412 continue;
4413 }
4414
4415 if (!(mpts->mpts_flags & MPTSF_READ_STALL)) {
4416 found_active = true;
4417 break;
4418 }
4419 }
4420
4421 if (!found_active) {
4422 *p_mpsofilt_hint |= SO_FILT_HINT_ADAPTIVE_RTIMO;
4423 }
4424
4425 return MPTS_EVRET_OK;
4426 }
4427
4428 static ev_ret_t
mptcp_subflow_adaptive_wtimo_ev(struct mptses * mpte,struct mptsub * mpts,uint32_t * p_mpsofilt_hint,uint32_t event)4429 mptcp_subflow_adaptive_wtimo_ev(struct mptses *mpte, struct mptsub *mpts,
4430 uint32_t *p_mpsofilt_hint, uint32_t event)
4431 {
4432 #pragma unused(event)
4433 bool found_active = false;
4434
4435 mpts->mpts_flags |= MPTSF_WRITE_STALL;
4436
4437 TAILQ_FOREACH(mpts, &mpte->mpte_subflows, mpts_entry) {
4438 struct tcpcb *tp = sototcpcb(mpts->mpts_socket);
4439
4440 if (!TCPS_HAVEESTABLISHED(tp->t_state) ||
4441 tp->t_state > TCPS_CLOSE_WAIT) {
4442 continue;
4443 }
4444
4445 if (!(mpts->mpts_flags & MPTSF_WRITE_STALL)) {
4446 found_active = true;
4447 break;
4448 }
4449 }
4450
4451 if (!found_active) {
4452 *p_mpsofilt_hint |= SO_FILT_HINT_ADAPTIVE_WTIMO;
4453 }
4454
4455 return MPTS_EVRET_OK;
4456 }
4457
4458 /*
4459 * Issues SOPT_SET on an MPTCP subflow socket; socket must already be locked,
4460 * caller must ensure that the option can be issued on subflow sockets, via
4461 * MPOF_SUBFLOW_OK flag.
4462 */
4463 int
mptcp_subflow_sosetopt(struct mptses * mpte,struct mptsub * mpts,struct mptopt * mpo)4464 mptcp_subflow_sosetopt(struct mptses *mpte, struct mptsub *mpts, struct mptopt *mpo)
4465 {
4466 struct socket *mp_so, *so;
4467 struct sockopt sopt;
4468 int error;
4469
4470 VERIFY(mpo->mpo_flags & MPOF_SUBFLOW_OK);
4471
4472 mp_so = mptetoso(mpte);
4473 so = mpts->mpts_socket;
4474
4475 /* Don't try to apply an IP or IPv6 option on an IPv6 or IP socket */
4476 if (mpo->mpo_level == IPPROTO_IP && SOCK_CHECK_DOM(so, PF_INET6)) {
4477 return 0;
4478 }
4479 if (mpo->mpo_level == IPPROTO_IPV6 && SOCK_CHECK_DOM(so, PF_INET)) {
4480 return 0;
4481 }
4482
4483 socket_lock_assert_owned(mp_so);
4484
4485 if (mpte->mpte_mptcb->mpt_state >= MPTCPS_ESTABLISHED &&
4486 mpo->mpo_level == SOL_SOCKET &&
4487 mpo->mpo_name == SO_MARK_CELLFALLBACK) {
4488 struct ifnet *ifp = ifindex2ifnet[mpts->mpts_ifscope];
4489
4490 /*
4491 * When we open a new subflow, mark it as cell fallback, if
4492 * this subflow goes over cell.
4493 *
4494 * (except for first-party apps)
4495 */
4496
4497 if (mpte->mpte_flags & MPTE_FIRSTPARTY) {
4498 return 0;
4499 }
4500
4501 if (sotoinpcb(so)->inp_last_outifp &&
4502 !IFNET_IS_CELLULAR(sotoinpcb(so)->inp_last_outifp)) {
4503 return 0;
4504 }
4505
4506 /*
4507 * This here is an OR, because if the app is not binding to the
4508 * interface, then it definitely is not a cell-fallback
4509 * connection.
4510 */
4511 if (mpts->mpts_ifscope == IFSCOPE_NONE || ifp == NULL ||
4512 !IFNET_IS_CELLULAR(ifp)) {
4513 return 0;
4514 }
4515 }
4516
4517 mpo->mpo_flags &= ~MPOF_INTERIM;
4518
4519 bzero(&sopt, sizeof(sopt));
4520 sopt.sopt_dir = SOPT_SET;
4521 sopt.sopt_level = mpo->mpo_level;
4522 sopt.sopt_name = mpo->mpo_name;
4523 sopt.sopt_val = CAST_USER_ADDR_T(&mpo->mpo_intval);
4524 sopt.sopt_valsize = sizeof(int);
4525 sopt.sopt_p = kernproc;
4526
4527 error = sosetoptlock(so, &sopt, 0);
4528 if (error) {
4529 os_log_error(mptcp_log_handle, "%s - %lx: sopt %s "
4530 "val %d set error %d\n", __func__,
4531 (unsigned long)VM_KERNEL_ADDRPERM(mpte),
4532 mptcp_sopt2str(mpo->mpo_level, mpo->mpo_name),
4533 mpo->mpo_intval, error);
4534 }
4535 return error;
4536 }
4537
4538 /*
4539 * Issues SOPT_GET on an MPTCP subflow socket; socket must already be locked,
4540 * caller must ensure that the option can be issued on subflow sockets, via
4541 * MPOF_SUBFLOW_OK flag.
4542 */
4543 int
mptcp_subflow_sogetopt(struct mptses * mpte,struct socket * so,struct mptopt * mpo)4544 mptcp_subflow_sogetopt(struct mptses *mpte, struct socket *so,
4545 struct mptopt *mpo)
4546 {
4547 struct socket *mp_so;
4548 struct sockopt sopt;
4549 int error;
4550
4551 VERIFY(mpo->mpo_flags & MPOF_SUBFLOW_OK);
4552 mp_so = mptetoso(mpte);
4553
4554 socket_lock_assert_owned(mp_so);
4555
4556 bzero(&sopt, sizeof(sopt));
4557 sopt.sopt_dir = SOPT_GET;
4558 sopt.sopt_level = mpo->mpo_level;
4559 sopt.sopt_name = mpo->mpo_name;
4560 sopt.sopt_val = CAST_USER_ADDR_T(&mpo->mpo_intval);
4561 sopt.sopt_valsize = sizeof(int);
4562 sopt.sopt_p = kernproc;
4563
4564 error = sogetoptlock(so, &sopt, 0); /* already locked */
4565 if (error) {
4566 os_log_error(mptcp_log_handle,
4567 "%s - %lx: sopt %s get error %d\n",
4568 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte),
4569 mptcp_sopt2str(mpo->mpo_level, mpo->mpo_name), error);
4570 }
4571 return error;
4572 }
4573
4574
4575 /*
4576 * MPTCP garbage collector.
4577 *
4578 * This routine is called by the MP domain on-demand, periodic callout,
4579 * which is triggered when a MPTCP socket is closed. The callout will
4580 * repeat as long as this routine returns a non-zero value.
4581 */
4582 static uint32_t
mptcp_gc(struct mppcbinfo * mppi)4583 mptcp_gc(struct mppcbinfo *mppi)
4584 {
4585 struct mppcb *mpp, *tmpp;
4586 uint32_t active = 0;
4587
4588 LCK_MTX_ASSERT(&mppi->mppi_lock, LCK_MTX_ASSERT_OWNED);
4589
4590 TAILQ_FOREACH_SAFE(mpp, &mppi->mppi_pcbs, mpp_entry, tmpp) {
4591 struct socket *mp_so;
4592 struct mptses *mpte;
4593 struct mptcb *mp_tp;
4594
4595 mp_so = mpp->mpp_socket;
4596 mpte = mptompte(mpp);
4597 mp_tp = mpte->mpte_mptcb;
4598
4599 if (!mpp_try_lock(mpp)) {
4600 active++;
4601 continue;
4602 }
4603
4604 VERIFY(mpp->mpp_flags & MPP_ATTACHED);
4605
4606 /* check again under the lock */
4607 if (mp_so->so_usecount > 0) {
4608 boolean_t wakeup = FALSE;
4609 struct mptsub *mpts, *tmpts;
4610
4611 if (mp_tp->mpt_state >= MPTCPS_FIN_WAIT_1) {
4612 if (mp_tp->mpt_gc_ticks > 0) {
4613 mp_tp->mpt_gc_ticks--;
4614 }
4615 if (mp_tp->mpt_gc_ticks == 0) {
4616 wakeup = TRUE;
4617 }
4618 }
4619 if (wakeup) {
4620 TAILQ_FOREACH_SAFE(mpts,
4621 &mpte->mpte_subflows, mpts_entry, tmpts) {
4622 mptcp_subflow_eupcall1(mpts->mpts_socket,
4623 mpts, SO_FILT_HINT_DISCONNECTED);
4624 }
4625 }
4626 socket_unlock(mp_so, 0);
4627 active++;
4628 continue;
4629 }
4630
4631 if (mpp->mpp_state != MPPCB_STATE_DEAD) {
4632 panic("%s - %lx: skipped state "
4633 "[u=%d,r=%d,s=%d]\n", __func__,
4634 (unsigned long)VM_KERNEL_ADDRPERM(mpte),
4635 mp_so->so_usecount, mp_so->so_retaincnt,
4636 mpp->mpp_state);
4637 }
4638
4639 if (mp_tp->mpt_state == MPTCPS_TIME_WAIT) {
4640 mptcp_close(mpte, mp_tp);
4641 }
4642
4643 mptcp_session_destroy(mpte);
4644
4645 DTRACE_MPTCP4(dispose, struct socket *, mp_so,
4646 struct sockbuf *, &mp_so->so_rcv,
4647 struct sockbuf *, &mp_so->so_snd,
4648 struct mppcb *, mpp);
4649
4650 mptcp_pcbdispose(mpp);
4651 sodealloc(mp_so);
4652 }
4653
4654 return active;
4655 }
4656
4657 /*
4658 * Drop a MPTCP connection, reporting the specified error.
4659 */
4660 struct mptses *
mptcp_drop(struct mptses * mpte,struct mptcb * mp_tp,u_short errno)4661 mptcp_drop(struct mptses *mpte, struct mptcb *mp_tp, u_short errno)
4662 {
4663 struct socket *mp_so = mptetoso(mpte);
4664
4665 VERIFY(mpte->mpte_mptcb == mp_tp);
4666
4667 socket_lock_assert_owned(mp_so);
4668
4669 DTRACE_MPTCP2(state__change, struct mptcb *, mp_tp,
4670 uint32_t, 0 /* event */);
4671
4672 if (errno == ETIMEDOUT && mp_tp->mpt_softerror != 0) {
4673 errno = mp_tp->mpt_softerror;
4674 }
4675 mp_so->so_error = errno;
4676
4677 return mptcp_close(mpte, mp_tp);
4678 }
4679
4680 /*
4681 * Close a MPTCP control block.
4682 */
4683 struct mptses *
mptcp_close(struct mptses * mpte,struct mptcb * mp_tp)4684 mptcp_close(struct mptses *mpte, struct mptcb *mp_tp)
4685 {
4686 struct mptsub *mpts = NULL, *tmpts = NULL;
4687 struct socket *mp_so = mptetoso(mpte);
4688
4689 socket_lock_assert_owned(mp_so);
4690 VERIFY(mpte->mpte_mptcb == mp_tp);
4691
4692 mp_tp->mpt_state = MPTCPS_TERMINATE;
4693
4694 mptcp_freeq(mp_tp);
4695
4696 soisdisconnected(mp_so);
4697
4698 /* Clean up all subflows */
4699 TAILQ_FOREACH_SAFE(mpts, &mpte->mpte_subflows, mpts_entry, tmpts) {
4700 mptcp_subflow_disconnect(mpte, mpts);
4701 }
4702
4703 return NULL;
4704 }
4705
4706 void
mptcp_notify_close(struct socket * so)4707 mptcp_notify_close(struct socket *so)
4708 {
4709 soevent(so, (SO_FILT_HINT_LOCKED | SO_FILT_HINT_DISCONNECTED));
4710 }
4711
4712 typedef struct mptcp_subflow_event_entry {
4713 uint32_t sofilt_hint_mask;
4714 ev_ret_t (*sofilt_hint_ev_hdlr)(
4715 struct mptses *mpte,
4716 struct mptsub *mpts,
4717 uint32_t *p_mpsofilt_hint,
4718 uint32_t event);
4719 } mptsub_ev_entry_t;
4720
4721 /*
4722 * XXX The order of the event handlers below is really
4723 * really important. Think twice before changing it.
4724 */
4725 static mptsub_ev_entry_t mpsub_ev_entry_tbl[] = {
4726 {
4727 .sofilt_hint_mask = SO_FILT_HINT_MP_SUB_ERROR,
4728 .sofilt_hint_ev_hdlr = mptcp_subflow_mpsuberror_ev,
4729 },
4730 {
4731 .sofilt_hint_mask = SO_FILT_HINT_MPCANTRCVMORE,
4732 .sofilt_hint_ev_hdlr = mptcp_subflow_mpcantrcvmore_ev,
4733 },
4734 {
4735 .sofilt_hint_mask = SO_FILT_HINT_MPFAILOVER,
4736 .sofilt_hint_ev_hdlr = mptcp_subflow_failover_ev,
4737 },
4738 {
4739 .sofilt_hint_mask = SO_FILT_HINT_CONNRESET,
4740 .sofilt_hint_ev_hdlr = mptcp_subflow_propagate_ev,
4741 },
4742 {
4743 .sofilt_hint_mask = SO_FILT_HINT_MUSTRST,
4744 .sofilt_hint_ev_hdlr = mptcp_subflow_mustrst_ev,
4745 },
4746 {
4747 .sofilt_hint_mask = SO_FILT_HINT_CANTRCVMORE,
4748 .sofilt_hint_ev_hdlr = mptcp_subflow_propagate_ev,
4749 },
4750 {
4751 .sofilt_hint_mask = SO_FILT_HINT_TIMEOUT,
4752 .sofilt_hint_ev_hdlr = mptcp_subflow_propagate_ev,
4753 },
4754 {
4755 .sofilt_hint_mask = SO_FILT_HINT_NOSRCADDR,
4756 .sofilt_hint_ev_hdlr = mptcp_subflow_nosrcaddr_ev,
4757 },
4758 {
4759 .sofilt_hint_mask = SO_FILT_HINT_IFDENIED,
4760 .sofilt_hint_ev_hdlr = mptcp_subflow_ifdenied_ev,
4761 },
4762 {
4763 .sofilt_hint_mask = SO_FILT_HINT_CONNECTED,
4764 .sofilt_hint_ev_hdlr = mptcp_subflow_connected_ev,
4765 },
4766 {
4767 .sofilt_hint_mask = SO_FILT_HINT_MPSTATUS,
4768 .sofilt_hint_ev_hdlr = mptcp_subflow_mpstatus_ev,
4769 },
4770 {
4771 .sofilt_hint_mask = SO_FILT_HINT_DISCONNECTED,
4772 .sofilt_hint_ev_hdlr = mptcp_subflow_disconnected_ev,
4773 },
4774 {
4775 .sofilt_hint_mask = SO_FILT_HINT_ADAPTIVE_RTIMO,
4776 .sofilt_hint_ev_hdlr = mptcp_subflow_adaptive_rtimo_ev,
4777 },
4778 {
4779 .sofilt_hint_mask = SO_FILT_HINT_ADAPTIVE_WTIMO,
4780 .sofilt_hint_ev_hdlr = mptcp_subflow_adaptive_wtimo_ev,
4781 },
4782 };
4783
4784 /*
4785 * Subflow socket control events.
4786 *
4787 * Called for handling events related to the underlying subflow socket.
4788 */
4789 static ev_ret_t
mptcp_subflow_events(struct mptses * mpte,struct mptsub * mpts,uint32_t * p_mpsofilt_hint)4790 mptcp_subflow_events(struct mptses *mpte, struct mptsub *mpts,
4791 uint32_t *p_mpsofilt_hint)
4792 {
4793 ev_ret_t ret = MPTS_EVRET_OK;
4794 int i, mpsub_ev_entry_count = sizeof(mpsub_ev_entry_tbl) /
4795 sizeof(mpsub_ev_entry_tbl[0]);
4796
4797 /* bail if there's nothing to process */
4798 if (!mpts->mpts_evctl) {
4799 return ret;
4800 }
4801
4802 if (mpts->mpts_evctl & (SO_FILT_HINT_CONNRESET | SO_FILT_HINT_MUSTRST |
4803 SO_FILT_HINT_CANTSENDMORE | SO_FILT_HINT_TIMEOUT |
4804 SO_FILT_HINT_NOSRCADDR | SO_FILT_HINT_IFDENIED |
4805 SO_FILT_HINT_DISCONNECTED)) {
4806 mpts->mpts_evctl |= SO_FILT_HINT_MPFAILOVER;
4807 }
4808
4809 DTRACE_MPTCP3(subflow__events, struct mptses *, mpte,
4810 struct mptsub *, mpts, uint32_t, mpts->mpts_evctl);
4811
4812 /*
4813 * Process all the socket filter hints and reset the hint
4814 * once it is handled
4815 */
4816 for (i = 0; i < mpsub_ev_entry_count && mpts->mpts_evctl; i++) {
4817 /*
4818 * Always execute the DISCONNECTED event, because it will wakeup
4819 * the app.
4820 */
4821 if ((mpts->mpts_evctl & mpsub_ev_entry_tbl[i].sofilt_hint_mask) &&
4822 (ret >= MPTS_EVRET_OK ||
4823 mpsub_ev_entry_tbl[i].sofilt_hint_mask == SO_FILT_HINT_DISCONNECTED)) {
4824 mpts->mpts_evctl &= ~mpsub_ev_entry_tbl[i].sofilt_hint_mask;
4825 ev_ret_t error =
4826 mpsub_ev_entry_tbl[i].sofilt_hint_ev_hdlr(mpte, mpts, p_mpsofilt_hint, mpsub_ev_entry_tbl[i].sofilt_hint_mask);
4827 ret = ((error >= MPTS_EVRET_OK) ? MAX(error, ret) : error);
4828 }
4829 }
4830
4831 return ret;
4832 }
4833
4834 /*
4835 * MPTCP workloop.
4836 */
4837 void
mptcp_subflow_workloop(struct mptses * mpte)4838 mptcp_subflow_workloop(struct mptses *mpte)
4839 {
4840 boolean_t connect_pending = FALSE, disconnect_fallback = FALSE;
4841 uint32_t mpsofilt_hint_mask = SO_FILT_HINT_LOCKED;
4842 struct mptsub *mpts, *tmpts;
4843 struct socket *mp_so;
4844
4845 mp_so = mptetoso(mpte);
4846
4847 socket_lock_assert_owned(mp_so);
4848
4849 if (mpte->mpte_flags & MPTE_IN_WORKLOOP) {
4850 mpte->mpte_flags |= MPTE_WORKLOOP_RELAUNCH;
4851 return;
4852 }
4853 mpte->mpte_flags |= MPTE_IN_WORKLOOP;
4854
4855 relaunch:
4856 mpte->mpte_flags &= ~MPTE_WORKLOOP_RELAUNCH;
4857
4858 TAILQ_FOREACH_SAFE(mpts, &mpte->mpte_subflows, mpts_entry, tmpts) {
4859 ev_ret_t ret;
4860
4861 if (mpts->mpts_socket->so_usecount == 0) {
4862 /* Will be removed soon by tcp_garbage_collect */
4863 continue;
4864 }
4865
4866 mptcp_subflow_addref(mpts);
4867 mpts->mpts_socket->so_usecount++;
4868
4869 ret = mptcp_subflow_events(mpte, mpts, &mpsofilt_hint_mask);
4870
4871 /*
4872 * If MPTCP socket is closed, disconnect all subflows.
4873 * This will generate a disconnect event which will
4874 * be handled during the next iteration, causing a
4875 * non-zero error to be returned above.
4876 */
4877 if (mp_so->so_flags & SOF_PCBCLEARING) {
4878 mptcp_subflow_disconnect(mpte, mpts);
4879 }
4880
4881 switch (ret) {
4882 case MPTS_EVRET_OK:
4883 /* nothing to do */
4884 break;
4885 case MPTS_EVRET_DELETE:
4886 mptcp_subflow_soclose(mpts);
4887 break;
4888 case MPTS_EVRET_CONNECT_PENDING:
4889 connect_pending = TRUE;
4890 break;
4891 case MPTS_EVRET_DISCONNECT_FALLBACK:
4892 disconnect_fallback = TRUE;
4893 break;
4894 default:
4895 break;
4896 }
4897 mptcp_subflow_remref(mpts); /* ours */
4898
4899 VERIFY(mpts->mpts_socket->so_usecount != 0);
4900 mpts->mpts_socket->so_usecount--;
4901 }
4902
4903 if (mpsofilt_hint_mask != SO_FILT_HINT_LOCKED) {
4904 VERIFY(mpsofilt_hint_mask & SO_FILT_HINT_LOCKED);
4905
4906 if (mpsofilt_hint_mask & SO_FILT_HINT_CANTRCVMORE) {
4907 mp_so->so_state |= SS_CANTRCVMORE;
4908 sorwakeup(mp_so);
4909 }
4910
4911 soevent(mp_so, mpsofilt_hint_mask);
4912 }
4913
4914 if (!connect_pending && !disconnect_fallback) {
4915 goto exit;
4916 }
4917
4918 TAILQ_FOREACH_SAFE(mpts, &mpte->mpte_subflows, mpts_entry, tmpts) {
4919 if (disconnect_fallback) {
4920 struct socket *so = NULL;
4921 struct inpcb *inp = NULL;
4922 struct tcpcb *tp = NULL;
4923
4924 if (mpts->mpts_flags & MPTSF_MP_DEGRADED) {
4925 continue;
4926 }
4927
4928 mpts->mpts_flags |= MPTSF_MP_DEGRADED;
4929
4930 if (mpts->mpts_flags & (MPTSF_DISCONNECTING |
4931 MPTSF_DISCONNECTED)) {
4932 continue;
4933 }
4934
4935 so = mpts->mpts_socket;
4936
4937 /*
4938 * The MPTCP connection has degraded to a fallback
4939 * mode, so there is no point in keeping this subflow
4940 * regardless of its MPTCP-readiness state, unless it
4941 * is the primary one which we use for fallback. This
4942 * assumes that the subflow used for fallback is the
4943 * ACTIVE one.
4944 */
4945
4946 inp = sotoinpcb(so);
4947 tp = intotcpcb(inp);
4948 tp->t_mpflags &=
4949 ~(TMPF_MPTCP_READY | TMPF_MPTCP_TRUE);
4950 tp->t_mpflags |= TMPF_TCP_FALLBACK;
4951
4952 soevent(so, SO_FILT_HINT_MUSTRST);
4953 } else if (connect_pending) {
4954 /*
4955 * The MPTCP connection has progressed to a state
4956 * where it supports full multipath semantics; allow
4957 * additional joins to be attempted for all subflows
4958 * that are in the PENDING state.
4959 */
4960 if (mpts->mpts_flags & MPTSF_CONNECT_PENDING) {
4961 int error = mptcp_subflow_soconnectx(mpte, mpts);
4962
4963 if (error) {
4964 mptcp_subflow_abort(mpts, error);
4965 }
4966 }
4967 }
4968 }
4969
4970 exit:
4971 if (mpte->mpte_flags & MPTE_WORKLOOP_RELAUNCH) {
4972 goto relaunch;
4973 }
4974
4975 mpte->mpte_flags &= ~MPTE_IN_WORKLOOP;
4976 }
4977
4978 /*
4979 * Protocol pr_lock callback.
4980 */
4981 int
mptcp_lock(struct socket * mp_so,int refcount,void * lr)4982 mptcp_lock(struct socket *mp_so, int refcount, void *lr)
4983 {
4984 struct mppcb *mpp = mpsotomppcb(mp_so);
4985 lr_ref_t lr_saved = TCP_INIT_LR_SAVED(lr);
4986
4987 if (mpp == NULL) {
4988 panic("%s: so=%p NO PCB! lr=%p lrh= %s", __func__,
4989 mp_so, lr_saved, solockhistory_nr(mp_so));
4990 /* NOTREACHED */
4991 }
4992 mpp_lock(mpp);
4993
4994 if (mp_so->so_usecount < 0) {
4995 panic("%s: so=%p so_pcb=%p lr=%p ref=%x lrh= %s", __func__,
4996 mp_so, mp_so->so_pcb, lr_saved, mp_so->so_usecount,
4997 solockhistory_nr(mp_so));
4998 /* NOTREACHED */
4999 }
5000 if (refcount != 0) {
5001 mp_so->so_usecount++;
5002 mpp->mpp_inside++;
5003 }
5004 mp_so->lock_lr[mp_so->next_lock_lr] = lr_saved;
5005 mp_so->next_lock_lr = (mp_so->next_lock_lr + 1) % SO_LCKDBG_MAX;
5006
5007 return 0;
5008 }
5009
5010 /*
5011 * Protocol pr_unlock callback.
5012 */
5013 int
mptcp_unlock(struct socket * mp_so,int refcount,void * lr)5014 mptcp_unlock(struct socket *mp_so, int refcount, void *lr)
5015 {
5016 struct mppcb *mpp = mpsotomppcb(mp_so);
5017 lr_ref_t lr_saved = TCP_INIT_LR_SAVED(lr);
5018
5019 if (mpp == NULL) {
5020 panic("%s: so=%p NO PCB usecount=%x lr=%p lrh= %s", __func__,
5021 mp_so, mp_so->so_usecount, lr_saved,
5022 solockhistory_nr(mp_so));
5023 /* NOTREACHED */
5024 }
5025 socket_lock_assert_owned(mp_so);
5026
5027 if (refcount != 0) {
5028 mp_so->so_usecount--;
5029 mpp->mpp_inside--;
5030 }
5031
5032 if (mp_so->so_usecount < 0) {
5033 panic("%s: so=%p usecount=%x lrh= %s", __func__,
5034 mp_so, mp_so->so_usecount, solockhistory_nr(mp_so));
5035 /* NOTREACHED */
5036 }
5037 if (mpp->mpp_inside < 0) {
5038 panic("%s: mpp=%p inside=%x lrh= %s", __func__,
5039 mpp, mpp->mpp_inside, solockhistory_nr(mp_so));
5040 /* NOTREACHED */
5041 }
5042 mp_so->unlock_lr[mp_so->next_unlock_lr] = lr_saved;
5043 mp_so->next_unlock_lr = (mp_so->next_unlock_lr + 1) % SO_LCKDBG_MAX;
5044 mpp_unlock(mpp);
5045
5046 return 0;
5047 }
5048
5049 /*
5050 * Protocol pr_getlock callback.
5051 */
5052 lck_mtx_t *
mptcp_getlock(struct socket * mp_so,int flags)5053 mptcp_getlock(struct socket *mp_so, int flags)
5054 {
5055 struct mppcb *mpp = mpsotomppcb(mp_so);
5056
5057 if (mpp == NULL) {
5058 panic("%s: so=%p NULL so_pcb %s", __func__, mp_so,
5059 solockhistory_nr(mp_so));
5060 /* NOTREACHED */
5061 }
5062 if (mp_so->so_usecount < 0) {
5063 panic("%s: so=%p usecount=%x lrh= %s", __func__,
5064 mp_so, mp_so->so_usecount, solockhistory_nr(mp_so));
5065 /* NOTREACHED */
5066 }
5067 return mpp_getlock(mpp, flags);
5068 }
5069
5070 void
mptcp_get_rands(mptcp_addr_id addr_id,struct mptcb * mp_tp,u_int32_t * lrand,u_int32_t * rrand)5071 mptcp_get_rands(mptcp_addr_id addr_id, struct mptcb *mp_tp, u_int32_t *lrand,
5072 u_int32_t *rrand)
5073 {
5074 struct mptcp_subf_auth_entry *sauth_entry;
5075
5076 LIST_FOREACH(sauth_entry, &mp_tp->mpt_subauth_list, msae_next) {
5077 if (sauth_entry->msae_laddr_id == addr_id) {
5078 if (lrand) {
5079 *lrand = sauth_entry->msae_laddr_rand;
5080 }
5081 if (rrand) {
5082 *rrand = sauth_entry->msae_raddr_rand;
5083 }
5084 break;
5085 }
5086 }
5087 }
5088
5089 void
mptcp_set_raddr_rand(mptcp_addr_id laddr_id,struct mptcb * mp_tp,mptcp_addr_id raddr_id,u_int32_t raddr_rand)5090 mptcp_set_raddr_rand(mptcp_addr_id laddr_id, struct mptcb *mp_tp,
5091 mptcp_addr_id raddr_id, u_int32_t raddr_rand)
5092 {
5093 struct mptcp_subf_auth_entry *sauth_entry;
5094
5095 LIST_FOREACH(sauth_entry, &mp_tp->mpt_subauth_list, msae_next) {
5096 if (sauth_entry->msae_laddr_id == laddr_id) {
5097 if ((sauth_entry->msae_raddr_id != 0) &&
5098 (sauth_entry->msae_raddr_id != raddr_id)) {
5099 os_log_error(mptcp_log_handle, "%s - %lx: mismatched"
5100 " address ids %d %d \n", __func__, (unsigned long)VM_KERNEL_ADDRPERM(mp_tp->mpt_mpte),
5101 raddr_id, sauth_entry->msae_raddr_id);
5102 return;
5103 }
5104 sauth_entry->msae_raddr_id = raddr_id;
5105 if ((sauth_entry->msae_raddr_rand != 0) &&
5106 (sauth_entry->msae_raddr_rand != raddr_rand)) {
5107 os_log_error(mptcp_log_handle, "%s - %lx: "
5108 "dup SYN_ACK %d %d \n",
5109 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mp_tp->mpt_mpte),
5110 raddr_rand, sauth_entry->msae_raddr_rand);
5111 return;
5112 }
5113 sauth_entry->msae_raddr_rand = raddr_rand;
5114 return;
5115 }
5116 }
5117 }
5118
5119 /*
5120 * SHA-256 support for MPTCP
5121 */
5122
5123 static void
mptcp_do_sha256(mptcp_key_t * key,char sha_digest[SHA256_DIGEST_LENGTH])5124 mptcp_do_sha256(mptcp_key_t *key, char sha_digest[SHA256_DIGEST_LENGTH])
5125 {
5126 const unsigned char *sha2_base;
5127 int sha2_size;
5128
5129 sha2_base = (const unsigned char *) key;
5130 sha2_size = sizeof(mptcp_key_t);
5131
5132 SHA256_CTX sha_ctx;
5133 SHA256_Init(&sha_ctx);
5134 SHA256_Update(&sha_ctx, sha2_base, sha2_size);
5135 SHA256_Final(sha_digest, &sha_ctx);
5136 }
5137
5138 void
mptcp_hmac_sha256(mptcp_key_t key1,mptcp_key_t key2,u_char * msg __sized_by (msg_len),uint16_t msg_len,u_char digest[SHA256_DIGEST_LENGTH])5139 mptcp_hmac_sha256(mptcp_key_t key1, mptcp_key_t key2,
5140 u_char *msg __sized_by(msg_len), uint16_t msg_len, u_char digest[SHA256_DIGEST_LENGTH])
5141 {
5142 SHA256_CTX sha_ctx;
5143 mptcp_key_t key_ipad[8] = {0}; /* key XOR'd with inner pad */
5144 mptcp_key_t key_opad[8] = {0}; /* key XOR'd with outer pad */
5145 int i;
5146
5147 bzero(digest, SHA256_DIGEST_LENGTH);
5148
5149 /* Set up the Key for HMAC */
5150 key_ipad[0] = key1;
5151 key_ipad[1] = key2;
5152
5153 key_opad[0] = key1;
5154 key_opad[1] = key2;
5155
5156 /* Key is 512 block length, so no need to compute hash */
5157
5158 /* Compute SHA1(Key XOR opad, SHA1(Key XOR ipad, data)) */
5159
5160 for (i = 0; i < 8; i++) {
5161 key_ipad[i] ^= 0x3636363636363636;
5162 key_opad[i] ^= 0x5c5c5c5c5c5c5c5c;
5163 }
5164
5165 /* Perform inner SHA256 */
5166 SHA256_Init(&sha_ctx);
5167 SHA256_Update(&sha_ctx, (unsigned char *)key_ipad, sizeof(key_ipad));
5168 SHA256_Update(&sha_ctx, msg, msg_len);
5169 SHA256_Final(digest, &sha_ctx);
5170
5171 /* Perform outer SHA256 */
5172 SHA256_Init(&sha_ctx);
5173 SHA256_Update(&sha_ctx, (unsigned char *)key_opad, sizeof(key_opad));
5174 SHA256_Update(&sha_ctx, (unsigned char *)digest, SHA256_DIGEST_LENGTH);
5175 SHA256_Final(digest, &sha_ctx);
5176 }
5177
5178 /*
5179 * SHA1 support for MPTCP
5180 */
5181
5182 static void
mptcp_do_sha1(mptcp_key_t * key,char sha_digest[SHA1_RESULTLEN])5183 mptcp_do_sha1(mptcp_key_t *key, char sha_digest[SHA1_RESULTLEN])
5184 {
5185 SHA1_CTX sha1ctxt;
5186 const unsigned char *sha1_base;
5187 int sha1_size;
5188
5189 sha1_base = (const unsigned char *) key;
5190 sha1_size = sizeof(mptcp_key_t);
5191 SHA1Init(&sha1ctxt);
5192 SHA1Update(&sha1ctxt, sha1_base, sha1_size);
5193 SHA1Final(sha_digest, &sha1ctxt);
5194 }
5195
5196 void
mptcp_hmac_sha1(mptcp_key_t key1,mptcp_key_t key2,u_int32_t rand1,u_int32_t rand2,u_char digest[SHA1_RESULTLEN])5197 mptcp_hmac_sha1(mptcp_key_t key1, mptcp_key_t key2,
5198 u_int32_t rand1, u_int32_t rand2, u_char digest[SHA1_RESULTLEN])
5199 {
5200 SHA1_CTX sha1ctxt;
5201 mptcp_key_t key_ipad[8] = {0}; /* key XOR'd with inner pad */
5202 mptcp_key_t key_opad[8] = {0}; /* key XOR'd with outer pad */
5203 u_int32_t data[2];
5204 int i;
5205
5206 bzero(digest, SHA1_RESULTLEN);
5207
5208 /* Set up the Key for HMAC */
5209 key_ipad[0] = key1;
5210 key_ipad[1] = key2;
5211
5212 key_opad[0] = key1;
5213 key_opad[1] = key2;
5214
5215 /* Set up the message for HMAC */
5216 data[0] = rand1;
5217 data[1] = rand2;
5218
5219 /* Key is 512 block length, so no need to compute hash */
5220
5221 /* Compute SHA1(Key XOR opad, SHA1(Key XOR ipad, data)) */
5222
5223 for (i = 0; i < 8; i++) {
5224 key_ipad[i] ^= 0x3636363636363636;
5225 key_opad[i] ^= 0x5c5c5c5c5c5c5c5c;
5226 }
5227
5228 /* Perform inner SHA1 */
5229 SHA1Init(&sha1ctxt);
5230 SHA1Update(&sha1ctxt, (unsigned char *)key_ipad, sizeof(key_ipad));
5231 SHA1Update(&sha1ctxt, (unsigned char *)data, sizeof(data));
5232 SHA1Final(digest, &sha1ctxt);
5233
5234 /* Perform outer SHA1 */
5235 SHA1Init(&sha1ctxt);
5236 SHA1Update(&sha1ctxt, (unsigned char *)key_opad, sizeof(key_opad));
5237 SHA1Update(&sha1ctxt, (unsigned char *)digest, SHA1_RESULTLEN);
5238 SHA1Final(digest, &sha1ctxt);
5239 }
5240
5241 /*
5242 * corresponds to MAC-B = MAC (Key=(Key-B+Key-A), Msg=(R-B+R-A))
5243 * corresponds to MAC-A = MAC (Key=(Key-A+Key-B), Msg=(R-A+R-B))
5244 */
5245 void
mptcp_get_mpjoin_hmac(mptcp_addr_id aid,struct mptcb * mp_tp,u_char * digest __sized_by (digest_len),uint8_t digest_len)5246 mptcp_get_mpjoin_hmac(mptcp_addr_id aid, struct mptcb *mp_tp, u_char *digest __sized_by(digest_len), uint8_t digest_len)
5247 {
5248 uint32_t lrand, rrand;
5249
5250 lrand = rrand = 0;
5251 mptcp_get_rands(aid, mp_tp, &lrand, &rrand);
5252
5253 u_char full_digest[MAX(SHA1_RESULTLEN, SHA256_DIGEST_LENGTH)] = {0};
5254 if (mp_tp->mpt_version == MPTCP_VERSION_0) {
5255 mptcp_hmac_sha1(mp_tp->mpt_localkey, mp_tp->mpt_remotekey, lrand, rrand, full_digest);
5256 } else {
5257 uint32_t data[2];
5258 data[0] = lrand;
5259 data[1] = rrand;
5260 mptcp_hmac_sha256(mp_tp->mpt_localkey, mp_tp->mpt_remotekey, (u_char*)data, 8, full_digest);
5261 }
5262 bcopy(full_digest, digest, digest_len);
5263 }
5264
5265 /*
5266 * Authentication data generation
5267 */
5268 static void
mptcp_generate_token(char * sha_digest __sized_by (sha_digest_len),int sha_digest_len,caddr_t token __sized_by (token_len),int token_len)5269 mptcp_generate_token(char *sha_digest __sized_by(sha_digest_len), int sha_digest_len, caddr_t token __sized_by(token_len),
5270 int token_len)
5271 {
5272 VERIFY(token_len == sizeof(u_int32_t));
5273 VERIFY(sha_digest_len == SHA1_RESULTLEN ||
5274 sha_digest_len == SHA256_DIGEST_LENGTH);
5275
5276 /* Most significant 32 bits of the SHA1/SHA256 hash */
5277 bcopy(sha_digest, token, sizeof(u_int32_t));
5278 return;
5279 }
5280
5281 static void
mptcp_generate_idsn(char * sha_digest __sized_by (sha_digest_len),int sha_digest_len,caddr_t idsn __sized_by (idsn_len),int idsn_len,uint8_t mp_version)5282 mptcp_generate_idsn(char *sha_digest __sized_by(sha_digest_len), int sha_digest_len, caddr_t idsn __sized_by(idsn_len),
5283 int idsn_len, uint8_t mp_version)
5284 {
5285 VERIFY(idsn_len == sizeof(u_int64_t));
5286 VERIFY(sha_digest_len == SHA1_RESULTLEN ||
5287 sha_digest_len == SHA256_DIGEST_LENGTH);
5288 VERIFY(mp_version == MPTCP_VERSION_0 || mp_version == MPTCP_VERSION_1);
5289
5290 /*
5291 * Least significant 64 bits of the hash
5292 */
5293
5294 if (mp_version == MPTCP_VERSION_0) {
5295 idsn[7] = sha_digest[12];
5296 idsn[6] = sha_digest[13];
5297 idsn[5] = sha_digest[14];
5298 idsn[4] = sha_digest[15];
5299 idsn[3] = sha_digest[16];
5300 idsn[2] = sha_digest[17];
5301 idsn[1] = sha_digest[18];
5302 idsn[0] = sha_digest[19];
5303 } else {
5304 idsn[7] = sha_digest[24];
5305 idsn[6] = sha_digest[25];
5306 idsn[5] = sha_digest[26];
5307 idsn[4] = sha_digest[27];
5308 idsn[3] = sha_digest[28];
5309 idsn[2] = sha_digest[29];
5310 idsn[1] = sha_digest[30];
5311 idsn[0] = sha_digest[31];
5312 }
5313 return;
5314 }
5315
5316 static void
mptcp_conn_properties(struct mptcb * mp_tp)5317 mptcp_conn_properties(struct mptcb *mp_tp)
5318 {
5319 /* Set DSS checksum flag */
5320 if (mptcp_dss_csum) {
5321 mp_tp->mpt_flags |= MPTCPF_CHECKSUM;
5322 }
5323
5324 /* Set up receive window */
5325 mp_tp->mpt_rcvwnd = mptcp_sbspace(mp_tp);
5326
5327 /* Set up gc ticks */
5328 mp_tp->mpt_gc_ticks = MPT_GC_TICKS;
5329 }
5330
5331 static void
mptcp_init_local_parms(struct mptses * mpte,struct sockaddr * dst)5332 mptcp_init_local_parms(struct mptses *mpte, struct sockaddr* dst)
5333 {
5334 struct mptcb *mp_tp = mpte->mpte_mptcb;
5335 char key_digest[MAX(SHA1_RESULTLEN, SHA256_DIGEST_LENGTH)];
5336 uint16_t digest_len;
5337
5338 if (mpte->mpte_flags & MPTE_FORCE_V0 || !mptcp_enable_v1) {
5339 mp_tp->mpt_version = MPTCP_VERSION_0;
5340 } else if (mpte->mpte_flags & MPTE_FORCE_V1 && mptcp_enable_v1) {
5341 mp_tp->mpt_version = MPTCP_VERSION_1;
5342 } else {
5343 mp_tp->mpt_version = tcp_cache_get_mptcp_version(dst);
5344 }
5345 VERIFY(mp_tp->mpt_version == MPTCP_VERSION_0 ||
5346 mp_tp->mpt_version == MPTCP_VERSION_1);
5347
5348 read_frandom(&mp_tp->mpt_localkey, sizeof(mp_tp->mpt_localkey));
5349 if (mp_tp->mpt_version == MPTCP_VERSION_0) {
5350 digest_len = SHA1_RESULTLEN;
5351 mptcp_do_sha1(&mp_tp->mpt_localkey, key_digest);
5352 } else {
5353 digest_len = SHA256_DIGEST_LENGTH;
5354 mptcp_do_sha256(&mp_tp->mpt_localkey, key_digest);
5355 }
5356
5357 mptcp_generate_token(key_digest, digest_len,
5358 (caddr_t)&mp_tp->mpt_localtoken, sizeof(mp_tp->mpt_localtoken));
5359 mptcp_generate_idsn(key_digest, digest_len,
5360 (caddr_t)&mp_tp->mpt_local_idsn, sizeof(u_int64_t), mp_tp->mpt_version);
5361 /* The subflow SYN is also first MPTCP byte */
5362 mp_tp->mpt_snduna = mp_tp->mpt_sndmax = mp_tp->mpt_local_idsn + 1;
5363 mp_tp->mpt_sndnxt = mp_tp->mpt_snduna;
5364
5365 mptcp_conn_properties(mp_tp);
5366 }
5367
5368 int
mptcp_init_remote_parms(struct mptcb * mp_tp)5369 mptcp_init_remote_parms(struct mptcb *mp_tp)
5370 {
5371 /* Setup local and remote tokens and Initial DSNs */
5372 char remote_digest[MAX(SHA1_RESULTLEN, SHA256_DIGEST_LENGTH)];
5373 uint16_t digest_len;
5374
5375 if (mp_tp->mpt_version == MPTCP_VERSION_0) {
5376 digest_len = SHA1_RESULTLEN;
5377 mptcp_do_sha1(&mp_tp->mpt_remotekey, remote_digest);
5378 } else if (mp_tp->mpt_version == MPTCP_VERSION_1) {
5379 digest_len = SHA256_DIGEST_LENGTH;
5380 mptcp_do_sha256(&mp_tp->mpt_remotekey, remote_digest);
5381 } else {
5382 return -1;
5383 }
5384
5385 mptcp_generate_token(remote_digest, digest_len,
5386 (caddr_t)&mp_tp->mpt_remotetoken, sizeof(mp_tp->mpt_remotetoken));
5387 mptcp_generate_idsn(remote_digest, digest_len,
5388 (caddr_t)&mp_tp->mpt_remote_idsn, sizeof(u_int64_t), mp_tp->mpt_version);
5389 mp_tp->mpt_rcvnxt = mp_tp->mpt_remote_idsn + 1;
5390 mp_tp->mpt_rcvadv = mp_tp->mpt_rcvnxt + mp_tp->mpt_rcvwnd;
5391 return 0;
5392 }
5393
5394 static void
mptcp_send_dfin(struct socket * so)5395 mptcp_send_dfin(struct socket *so)
5396 {
5397 struct tcpcb *tp = NULL;
5398 struct inpcb *inp = NULL;
5399
5400 inp = sotoinpcb(so);
5401 if (!inp) {
5402 return;
5403 }
5404
5405 tp = intotcpcb(inp);
5406 if (!tp) {
5407 return;
5408 }
5409
5410 if (!(tp->t_mpflags & TMPF_RESET)) {
5411 tp->t_mpflags |= TMPF_SEND_DFIN;
5412 }
5413 }
5414
5415 /*
5416 * Data Sequence Mapping routines
5417 */
5418 void
mptcp_insert_dsn(struct mppcb * mpp,struct mbuf * m)5419 mptcp_insert_dsn(struct mppcb *mpp, struct mbuf *m)
5420 {
5421 struct mptcb *mp_tp;
5422
5423 if (m == NULL) {
5424 return;
5425 }
5426
5427 mp_tp = &__container_of(mpp, struct mpp_mtp, mpp)->mtcb;
5428
5429 while (m) {
5430 VERIFY(m->m_flags & M_PKTHDR);
5431 m->m_pkthdr.pkt_flags |= (PKTF_MPTCP | PKTF_MPSO);
5432 m->m_pkthdr.mp_dsn = mp_tp->mpt_sndmax;
5433 VERIFY(m_pktlen(m) >= 0 && m_pktlen(m) < UINT16_MAX);
5434 m->m_pkthdr.mp_rlen = (uint16_t)m_pktlen(m);
5435 mp_tp->mpt_sndmax += m_pktlen(m);
5436 m = m->m_next;
5437 }
5438 }
5439
5440 void
mptcp_fallback_sbdrop(struct socket * so,struct mbuf * m,int len)5441 mptcp_fallback_sbdrop(struct socket *so, struct mbuf *m, int len)
5442 {
5443 struct mptcb *mp_tp = tptomptp(sototcpcb(so));
5444 uint64_t data_ack;
5445 uint64_t dsn;
5446
5447 VERIFY(len >= 0);
5448
5449 if (!m || len == 0) {
5450 return;
5451 }
5452
5453 while (m && len > 0) {
5454 VERIFY(m->m_flags & M_PKTHDR);
5455 VERIFY(m->m_pkthdr.pkt_flags & PKTF_MPTCP);
5456
5457 data_ack = m->m_pkthdr.mp_dsn + m->m_pkthdr.mp_rlen;
5458 dsn = m->m_pkthdr.mp_dsn;
5459
5460 len -= m->m_len;
5461 m = m->m_next;
5462 }
5463
5464 if (m && len == 0) {
5465 /*
5466 * If there is one more mbuf in the chain, it automatically means
5467 * that up to m->mp_dsn has been ack'ed.
5468 *
5469 * This means, we actually correct data_ack back down (compared
5470 * to what we set inside the loop - dsn + data_len). Because in
5471 * the loop we are "optimistic" and assume that the full mapping
5472 * will be acked. If that's not the case and we get out of the
5473 * loop with m != NULL, it means only up to m->mp_dsn has been
5474 * really acked.
5475 */
5476 data_ack = m->m_pkthdr.mp_dsn;
5477 }
5478
5479 if (len < 0) {
5480 /*
5481 * If len is negative, meaning we acked in the middle of an mbuf,
5482 * only up to this mbuf's data-sequence number has been acked
5483 * at the MPTCP-level.
5484 */
5485 data_ack = dsn;
5486 }
5487
5488 /* We can have data in the subflow's send-queue that is being acked,
5489 * while the DATA_ACK has already advanced. Thus, we should check whether
5490 * or not the DATA_ACK is actually new here.
5491 */
5492 if (MPTCP_SEQ_LEQ(data_ack, mp_tp->mpt_sndmax) &&
5493 MPTCP_SEQ_GEQ(data_ack, mp_tp->mpt_snduna)) {
5494 mptcp_data_ack_rcvd(mp_tp, sototcpcb(so), data_ack);
5495 }
5496 }
5497
5498 void
mptcp_preproc_sbdrop(struct socket * so,struct mbuf * m,unsigned int len)5499 mptcp_preproc_sbdrop(struct socket *so, struct mbuf *m, unsigned int len)
5500 {
5501 int rewinding = 0;
5502
5503 /* TFO makes things complicated. */
5504 if (so->so_flags1 & SOF1_TFO_REWIND) {
5505 rewinding = 1;
5506 so->so_flags1 &= ~SOF1_TFO_REWIND;
5507 }
5508
5509 while (m && (!(so->so_flags & SOF_MP_SUBFLOW) || rewinding)) {
5510 u_int32_t sub_len;
5511 VERIFY(m->m_flags & M_PKTHDR);
5512 VERIFY(m->m_pkthdr.pkt_flags & PKTF_MPTCP);
5513
5514 sub_len = m->m_pkthdr.mp_rlen;
5515
5516 if (sub_len < len) {
5517 m->m_pkthdr.mp_dsn += sub_len;
5518 if (!(m->m_pkthdr.pkt_flags & PKTF_MPSO)) {
5519 m->m_pkthdr.mp_rseq += sub_len;
5520 }
5521 m->m_pkthdr.mp_rlen = 0;
5522 len -= sub_len;
5523 } else {
5524 /* sub_len >= len */
5525 if (rewinding == 0) {
5526 m->m_pkthdr.mp_dsn += len;
5527 }
5528 if (!(m->m_pkthdr.pkt_flags & PKTF_MPSO)) {
5529 if (rewinding == 0) {
5530 m->m_pkthdr.mp_rseq += len;
5531 }
5532 }
5533 m->m_pkthdr.mp_rlen -= len;
5534 break;
5535 }
5536 m = m->m_next;
5537 }
5538
5539 if (so->so_flags & SOF_MP_SUBFLOW &&
5540 !(sototcpcb(so)->t_mpflags & TMPF_TFO_REQUEST) &&
5541 !(sototcpcb(so)->t_mpflags & TMPF_RCVD_DACK)) {
5542 /*
5543 * Received an ack without receiving a DATA_ACK.
5544 * Need to fallback to regular TCP (or destroy this subflow).
5545 */
5546 sototcpcb(so)->t_mpflags |= TMPF_INFIN_SENT;
5547 mptcp_notify_mpfail(so);
5548 }
5549 }
5550
5551 /* Obtain the DSN mapping stored in the mbuf */
5552 void
mptcp_output_getm_dsnmap32(struct socket * so,int off,uint32_t * dsn,uint32_t * relseq,uint16_t * data_len,uint16_t * dss_csum)5553 mptcp_output_getm_dsnmap32(struct socket *so, int off,
5554 uint32_t *dsn, uint32_t *relseq, uint16_t *data_len, uint16_t *dss_csum)
5555 {
5556 u_int64_t dsn64;
5557
5558 mptcp_output_getm_dsnmap64(so, off, &dsn64, relseq, data_len, dss_csum);
5559 *dsn = (u_int32_t)MPTCP_DATASEQ_LOW32(dsn64);
5560 }
5561
5562 void
mptcp_output_getm_dsnmap64(struct socket * so,int off,uint64_t * dsn,uint32_t * relseq,uint16_t * data_len,uint16_t * dss_csum)5563 mptcp_output_getm_dsnmap64(struct socket *so, int off, uint64_t *dsn,
5564 uint32_t *relseq, uint16_t *data_len,
5565 uint16_t *dss_csum)
5566 {
5567 struct mbuf *m = so->so_snd.sb_mb;
5568
5569 VERIFY(off >= 0);
5570
5571 if (m == NULL && (so->so_flags & SOF_DEFUNCT)) {
5572 *dsn = 0;
5573 *relseq = 0;
5574 *data_len = 0;
5575 *dss_csum = 0;
5576 return;
5577 }
5578
5579 /*
5580 * In the subflow socket, the DSN sequencing can be discontiguous,
5581 * but the subflow sequence mapping is contiguous. Use the subflow
5582 * sequence property to find the right mbuf and corresponding dsn
5583 * mapping.
5584 */
5585
5586 while (m) {
5587 VERIFY(m->m_flags & M_PKTHDR);
5588 VERIFY(m->m_pkthdr.pkt_flags & PKTF_MPTCP);
5589
5590 if (off >= m->m_len) {
5591 off -= m->m_len;
5592 m = m->m_next;
5593 } else {
5594 break;
5595 }
5596 }
5597
5598 VERIFY(off >= 0);
5599 VERIFY(m->m_pkthdr.mp_rlen <= UINT16_MAX);
5600
5601 *dsn = m->m_pkthdr.mp_dsn;
5602 *relseq = m->m_pkthdr.mp_rseq;
5603 *data_len = m->m_pkthdr.mp_rlen;
5604 *dss_csum = m->m_pkthdr.mp_csum;
5605 }
5606
5607 void
mptcp_output_getm_data_level_details(struct socket * so,int off,uint16_t * data_len,uint16_t * dss_csum)5608 mptcp_output_getm_data_level_details(struct socket *so, int off, uint16_t *data_len, uint16_t *dss_csum)
5609 {
5610 uint64_t dsn;
5611 uint32_t relseq;
5612
5613 mptcp_output_getm_dsnmap64(so, off, &dsn, &relseq, data_len, dss_csum);
5614 }
5615
5616 /*
5617 * Note that this is called only from tcp_input() via mptcp_input_preproc()
5618 * tcp_input() may trim data after the dsn mapping is inserted into the mbuf.
5619 * When it trims data tcp_input calls m_adj() which does not remove the
5620 * m_pkthdr even if the m_len becomes 0 as a result of trimming the mbuf.
5621 * The dsn map insertion cannot be delayed after trim, because data can be in
5622 * the reassembly queue for a while and the DSN option info in tp will be
5623 * overwritten for every new packet received.
5624 * The dsn map will be adjusted just prior to appending to subflow sockbuf
5625 * with mptcp_adj_rmap()
5626 */
5627 void
mptcp_insert_rmap(struct tcpcb * tp,struct mbuf * m,struct tcphdr * th)5628 mptcp_insert_rmap(struct tcpcb *tp, struct mbuf *m, struct tcphdr *th)
5629 {
5630 VERIFY(m->m_flags & M_PKTHDR);
5631 VERIFY(!(m->m_pkthdr.pkt_flags & PKTF_MPTCP));
5632
5633 if (tp->t_mpflags & TMPF_EMBED_DSN) {
5634 m->m_pkthdr.mp_dsn = tp->t_rcv_map.mpt_dsn;
5635 m->m_pkthdr.mp_rseq = tp->t_rcv_map.mpt_sseq;
5636 m->m_pkthdr.mp_rlen = tp->t_rcv_map.mpt_len;
5637 m->m_pkthdr.mp_csum = tp->t_rcv_map.mpt_csum;
5638 if (tp->t_rcv_map.mpt_dfin) {
5639 m->m_pkthdr.pkt_flags |= PKTF_MPTCP_DFIN;
5640 }
5641
5642 m->m_pkthdr.pkt_flags |= PKTF_MPTCP;
5643
5644 tp->t_mpflags &= ~TMPF_EMBED_DSN;
5645 tp->t_mpflags |= TMPF_MPTCP_ACKNOW;
5646 } else if (tp->t_mpflags & TMPF_TCP_FALLBACK) {
5647 if (th->th_flags & TH_FIN) {
5648 m->m_pkthdr.pkt_flags |= PKTF_MPTCP_DFIN;
5649 }
5650 }
5651 }
5652
5653 /*
5654 * Following routines help with failure detection and failover of data
5655 * transfer from one subflow to another.
5656 */
5657 void
mptcp_act_on_txfail(struct socket * so)5658 mptcp_act_on_txfail(struct socket *so)
5659 {
5660 struct tcpcb *tp = NULL;
5661 struct inpcb *inp = sotoinpcb(so);
5662
5663 if (inp == NULL) {
5664 return;
5665 }
5666
5667 tp = intotcpcb(inp);
5668 if (tp == NULL) {
5669 return;
5670 }
5671
5672 if (so->so_flags & SOF_MP_TRYFAILOVER) {
5673 return;
5674 }
5675
5676 so->so_flags |= SOF_MP_TRYFAILOVER;
5677 soevent(so, (SO_FILT_HINT_LOCKED | SO_FILT_HINT_MPFAILOVER));
5678 }
5679
5680 /*
5681 * Support for MP_FAIL option
5682 */
5683 int
mptcp_get_map_for_dsn(struct socket * so,uint64_t dsn_fail,uint32_t * tcp_seq)5684 mptcp_get_map_for_dsn(struct socket *so, uint64_t dsn_fail, uint32_t *tcp_seq)
5685 {
5686 struct mbuf *m = so->so_snd.sb_mb;
5687 uint16_t datalen;
5688 uint64_t dsn;
5689 int off = 0;
5690
5691 if (m == NULL) {
5692 return -1;
5693 }
5694
5695 while (m != NULL) {
5696 VERIFY(m->m_pkthdr.pkt_flags & PKTF_MPTCP);
5697 VERIFY(m->m_flags & M_PKTHDR);
5698 dsn = m->m_pkthdr.mp_dsn;
5699 datalen = m->m_pkthdr.mp_rlen;
5700 if (MPTCP_SEQ_LEQ(dsn, dsn_fail) &&
5701 (MPTCP_SEQ_GEQ(dsn + datalen, dsn_fail))) {
5702 off = (int)(dsn_fail - dsn);
5703 *tcp_seq = m->m_pkthdr.mp_rseq + off;
5704 return 0;
5705 }
5706
5707 m = m->m_next;
5708 }
5709
5710 /*
5711 * If there was no mbuf data and a fallback to TCP occurred, there's
5712 * not much else to do.
5713 */
5714
5715 os_log_error(mptcp_log_handle, "%s: %llu not found \n", __func__, dsn_fail);
5716 return -1;
5717 }
5718
5719 /*
5720 * Support for sending contiguous MPTCP bytes in subflow
5721 * Also for preventing sending data with ACK in 3-way handshake
5722 */
5723 int32_t
mptcp_adj_sendlen(struct socket * so,int32_t off)5724 mptcp_adj_sendlen(struct socket *so, int32_t off)
5725 {
5726 struct tcpcb *tp = sototcpcb(so);
5727 struct mptsub *mpts = tp->t_mpsub;
5728 uint64_t mdss_dsn;
5729 uint32_t mdss_subflow_seq;
5730 int mdss_subflow_off;
5731 uint16_t mdss_data_len;
5732 uint16_t dss_csum;
5733
5734 if (so->so_snd.sb_mb == NULL && (so->so_flags & SOF_DEFUNCT)) {
5735 return 0;
5736 }
5737
5738 mptcp_output_getm_dsnmap64(so, off, &mdss_dsn, &mdss_subflow_seq,
5739 &mdss_data_len, &dss_csum);
5740
5741 /*
5742 * We need to compute how much of the mapping still remains.
5743 * So, we compute the offset in the send-buffer of the dss-sub-seq.
5744 */
5745 mdss_subflow_off = (mdss_subflow_seq + mpts->mpts_iss) - tp->snd_una;
5746
5747 /*
5748 * When TFO is used, we are sending the mpts->mpts_iss although the relative
5749 * seq has been set to 1 (while it should be 0).
5750 */
5751 if (tp->t_mpflags & TMPF_TFO_REQUEST) {
5752 mdss_subflow_off--;
5753 }
5754
5755 VERIFY(off >= mdss_subflow_off);
5756
5757 return mdss_data_len - (off - mdss_subflow_off);
5758 }
5759
5760 static uint32_t
mptcp_get_maxseg(struct mptses * mpte)5761 mptcp_get_maxseg(struct mptses *mpte)
5762 {
5763 struct mptsub *mpts;
5764 uint32_t maxseg = 0;
5765
5766 TAILQ_FOREACH(mpts, &mpte->mpte_subflows, mpts_entry) {
5767 struct tcpcb *tp = sototcpcb(mpts->mpts_socket);
5768
5769 if (!TCPS_HAVEESTABLISHED(tp->t_state) ||
5770 TCPS_HAVERCVDFIN2(tp->t_state)) {
5771 continue;
5772 }
5773
5774 if (tp->t_maxseg > maxseg) {
5775 maxseg = tp->t_maxseg;
5776 }
5777 }
5778
5779 return maxseg;
5780 }
5781
5782 static uint8_t
mptcp_get_rcvscale(struct mptses * mpte)5783 mptcp_get_rcvscale(struct mptses *mpte)
5784 {
5785 struct mptsub *mpts;
5786 uint8_t rcvscale = UINT8_MAX;
5787
5788 TAILQ_FOREACH(mpts, &mpte->mpte_subflows, mpts_entry) {
5789 struct tcpcb *tp = sototcpcb(mpts->mpts_socket);
5790
5791 if (!TCPS_HAVEESTABLISHED(tp->t_state) ||
5792 TCPS_HAVERCVDFIN2(tp->t_state)) {
5793 continue;
5794 }
5795
5796 if (tp->rcv_scale < rcvscale) {
5797 rcvscale = tp->rcv_scale;
5798 }
5799 }
5800
5801 return rcvscale;
5802 }
5803
5804 /* Similar to tcp_sbrcv_reserve */
5805 static void
mptcp_sbrcv_reserve(struct mptcb * mp_tp,struct sockbuf * sbrcv,u_int32_t newsize,u_int32_t idealsize)5806 mptcp_sbrcv_reserve(struct mptcb *mp_tp, struct sockbuf *sbrcv,
5807 u_int32_t newsize, u_int32_t idealsize)
5808 {
5809 uint8_t rcvscale = mptcp_get_rcvscale(mp_tp->mpt_mpte);
5810
5811 if (rcvscale == UINT8_MAX) {
5812 return;
5813 }
5814
5815 /* newsize should not exceed max */
5816 newsize = min(newsize, tcp_autorcvbuf_max);
5817
5818 /* The receive window scale negotiated at the
5819 * beginning of the connection will also set a
5820 * limit on the socket buffer size
5821 */
5822 newsize = min(newsize, TCP_MAXWIN << rcvscale);
5823
5824 /* Set new socket buffer size */
5825 if (newsize > sbrcv->sb_hiwat &&
5826 (sbreserve(sbrcv, newsize) == 1)) {
5827 sbrcv->sb_idealsize = min(max(sbrcv->sb_idealsize,
5828 (idealsize != 0) ? idealsize : newsize), tcp_autorcvbuf_max);
5829
5830 /* Again check the limit set by the advertised
5831 * window scale
5832 */
5833 sbrcv->sb_idealsize = min(sbrcv->sb_idealsize,
5834 TCP_MAXWIN << rcvscale);
5835 }
5836 }
5837
5838 void
mptcp_sbrcv_grow(struct mptcb * mp_tp)5839 mptcp_sbrcv_grow(struct mptcb *mp_tp)
5840 {
5841 struct mptses *mpte = mp_tp->mpt_mpte;
5842 struct socket *mp_so = mpte->mpte_mppcb->mpp_socket;
5843 struct sockbuf *sbrcv = &mp_so->so_rcv;
5844 uint32_t hiwat_sum = 0;
5845 uint32_t ideal_sum = 0;
5846 struct mptsub *mpts;
5847
5848 /*
5849 * Do not grow the receive socket buffer if
5850 * - auto resizing is disabled, globally or on this socket
5851 * - the high water mark already reached the maximum
5852 * - the stream is in background and receive side is being
5853 * throttled
5854 * - if there are segments in reassembly queue indicating loss,
5855 * do not need to increase recv window during recovery as more
5856 * data is not going to be sent. A duplicate ack sent during
5857 * recovery should not change the receive window
5858 */
5859 if (tcp_do_autorcvbuf == 0 ||
5860 (sbrcv->sb_flags & SB_AUTOSIZE) == 0 ||
5861 sbrcv->sb_hiwat >= tcp_autorcvbuf_max ||
5862 (mp_so->so_flags1 & SOF1_EXTEND_BK_IDLE_WANTED) ||
5863 !LIST_EMPTY(&mp_tp->mpt_segq)) {
5864 /* Can not resize the socket buffer, just return */
5865 return;
5866 }
5867
5868 /*
5869 * Ideally, we want the rbuf to be (sum_i {bw_i} * rtt_max * 2)
5870 *
5871 * But, for this we first need accurate receiver-RTT estimations, which
5872 * we currently don't have.
5873 *
5874 * Let's use a dummy algorithm for now, just taking the sum of all
5875 * subflow's receive-buffers. It's too low, but that's all we can get
5876 * for now.
5877 */
5878
5879 TAILQ_FOREACH(mpts, &mpte->mpte_subflows, mpts_entry) {
5880 hiwat_sum += mpts->mpts_socket->so_rcv.sb_hiwat;
5881 ideal_sum += mpts->mpts_socket->so_rcv.sb_idealsize;
5882 }
5883
5884 mptcp_sbrcv_reserve(mp_tp, sbrcv, hiwat_sum, ideal_sum);
5885 }
5886
5887 /*
5888 * Determine if we can grow the recieve socket buffer to avoid sending
5889 * a zero window update to the peer. We allow even socket buffers that
5890 * have fixed size (set by the application) to grow if the resource
5891 * constraints are met. They will also be trimmed after the application
5892 * reads data.
5893 *
5894 * Similar to tcp_sbrcv_grow_rwin
5895 */
5896 static void
mptcp_sbrcv_grow_rwin(struct mptcb * mp_tp,struct sockbuf * sb)5897 mptcp_sbrcv_grow_rwin(struct mptcb *mp_tp, struct sockbuf *sb)
5898 {
5899 struct socket *mp_so = mp_tp->mpt_mpte->mpte_mppcb->mpp_socket;
5900 u_int32_t rcvbufinc = mptcp_get_maxseg(mp_tp->mpt_mpte) << 4;
5901 u_int32_t rcvbuf = sb->sb_hiwat;
5902
5903 if (tcp_recv_bg == 1 || IS_TCP_RECV_BG(mp_so)) {
5904 return;
5905 }
5906
5907 if (tcp_do_autorcvbuf == 1 &&
5908 /* Diff to tcp_sbrcv_grow_rwin */
5909 (mp_so->so_flags1 & SOF1_EXTEND_BK_IDLE_WANTED) == 0 &&
5910 (rcvbuf - sb->sb_cc) < rcvbufinc &&
5911 rcvbuf < tcp_autorcvbuf_max &&
5912 (sb->sb_idealsize > 0 &&
5913 sb->sb_hiwat <= (sb->sb_idealsize + rcvbufinc))) {
5914 sbreserve(sb, min((sb->sb_hiwat + rcvbufinc), tcp_autorcvbuf_max));
5915 }
5916 }
5917
5918 /* Similar to tcp_sbspace */
5919 int32_t
mptcp_sbspace(struct mptcb * mp_tp)5920 mptcp_sbspace(struct mptcb *mp_tp)
5921 {
5922 struct sockbuf *sb = &mp_tp->mpt_mpte->mpte_mppcb->mpp_socket->so_rcv;
5923 uint32_t rcvbuf;
5924 int32_t space;
5925 int32_t pending = 0;
5926
5927 socket_lock_assert_owned(mptetoso(mp_tp->mpt_mpte));
5928
5929 mptcp_sbrcv_grow_rwin(mp_tp, sb);
5930
5931 /* hiwat might have changed */
5932 rcvbuf = sb->sb_hiwat;
5933
5934 space = ((int32_t) imin((rcvbuf - sb->sb_cc),
5935 (sb->sb_mbmax - sb->sb_mbcnt)));
5936 if (space < 0) {
5937 space = 0;
5938 }
5939
5940 #if CONTENT_FILTER
5941 /* Compensate for data being processed by content filters */
5942 pending = cfil_sock_data_space(sb);
5943 #endif /* CONTENT_FILTER */
5944 if (pending > space) {
5945 space = 0;
5946 } else {
5947 space -= pending;
5948 }
5949
5950 return space;
5951 }
5952
5953 /*
5954 * Support Fallback to Regular TCP
5955 */
5956 void
mptcp_notify_mpready(struct socket * so)5957 mptcp_notify_mpready(struct socket *so)
5958 {
5959 struct tcpcb *tp = NULL;
5960
5961 if (so == NULL) {
5962 return;
5963 }
5964
5965 tp = intotcpcb(sotoinpcb(so));
5966
5967 if (tp == NULL) {
5968 return;
5969 }
5970
5971 DTRACE_MPTCP4(multipath__ready, struct socket *, so,
5972 struct sockbuf *, &so->so_rcv, struct sockbuf *, &so->so_snd,
5973 struct tcpcb *, tp);
5974
5975 if (!(tp->t_mpflags & TMPF_MPTCP_TRUE)) {
5976 return;
5977 }
5978
5979 if (tp->t_mpflags & TMPF_MPTCP_READY) {
5980 return;
5981 }
5982
5983 tp->t_mpflags &= ~TMPF_TCP_FALLBACK;
5984 tp->t_mpflags |= TMPF_MPTCP_READY;
5985
5986 soevent(so, (SO_FILT_HINT_LOCKED | SO_FILT_HINT_MPSTATUS));
5987 }
5988
5989 void
mptcp_notify_mpfail(struct socket * so)5990 mptcp_notify_mpfail(struct socket *so)
5991 {
5992 struct tcpcb *tp = NULL;
5993
5994 if (so == NULL) {
5995 return;
5996 }
5997
5998 tp = intotcpcb(sotoinpcb(so));
5999
6000 if (tp == NULL) {
6001 return;
6002 }
6003
6004 DTRACE_MPTCP4(multipath__failed, struct socket *, so,
6005 struct sockbuf *, &so->so_rcv, struct sockbuf *, &so->so_snd,
6006 struct tcpcb *, tp);
6007
6008 if (tp->t_mpflags & TMPF_TCP_FALLBACK) {
6009 return;
6010 }
6011
6012 tp->t_mpflags &= ~(TMPF_MPTCP_READY | TMPF_MPTCP_TRUE);
6013 tp->t_mpflags |= TMPF_TCP_FALLBACK;
6014
6015 soevent(so, (SO_FILT_HINT_LOCKED | SO_FILT_HINT_MPSTATUS));
6016 }
6017
6018 /*
6019 * Keepalive helper function
6020 */
6021 boolean_t
mptcp_ok_to_keepalive(struct mptcb * mp_tp)6022 mptcp_ok_to_keepalive(struct mptcb *mp_tp)
6023 {
6024 boolean_t ret = 1;
6025
6026 socket_lock_assert_owned(mptetoso(mp_tp->mpt_mpte));
6027
6028 if (mp_tp->mpt_state >= MPTCPS_CLOSE_WAIT) {
6029 ret = 0;
6030 }
6031 return ret;
6032 }
6033
6034 /*
6035 * MPTCP t_maxseg adjustment function
6036 */
6037 int
mptcp_adj_mss(struct tcpcb * tp,boolean_t mtudisc)6038 mptcp_adj_mss(struct tcpcb *tp, boolean_t mtudisc)
6039 {
6040 int mss_lower = 0;
6041 struct mptcb *mp_tp = tptomptp(tp);
6042
6043 #define MPTCP_COMPUTE_LEN { \
6044 mss_lower = sizeof (struct mptcp_dss_ack_opt); \
6045 if (mp_tp->mpt_flags & MPTCPF_CHECKSUM) \
6046 mss_lower += 2; \
6047 else \
6048 /* adjust to 32-bit boundary + EOL */ \
6049 mss_lower += 2; \
6050 }
6051 if (mp_tp == NULL) {
6052 return 0;
6053 }
6054
6055 socket_lock_assert_owned(mptetoso(mp_tp->mpt_mpte));
6056
6057 /*
6058 * For the first subflow and subsequent subflows, adjust mss for
6059 * most common MPTCP option size, for case where tcp_mss is called
6060 * during option processing and MTU discovery.
6061 */
6062 if (!mtudisc) {
6063 if (tp->t_mpflags & TMPF_MPTCP_TRUE &&
6064 !(tp->t_mpflags & TMPF_JOINED_FLOW)) {
6065 MPTCP_COMPUTE_LEN;
6066 }
6067
6068 if (tp->t_mpflags & TMPF_PREESTABLISHED &&
6069 tp->t_mpflags & TMPF_SENT_JOIN) {
6070 MPTCP_COMPUTE_LEN;
6071 }
6072 } else {
6073 if (tp->t_mpflags & TMPF_MPTCP_TRUE) {
6074 MPTCP_COMPUTE_LEN;
6075 }
6076 }
6077
6078 return mss_lower;
6079 }
6080
6081 static void
fill_mptcp_subflow(struct socket * so,mptcp_flow_t * flow,struct mptsub * mpts)6082 fill_mptcp_subflow(struct socket *so, mptcp_flow_t *flow, struct mptsub *mpts)
6083 {
6084 struct inpcb *inp;
6085
6086 tcp_getconninfo(so, &flow->flow_ci);
6087 inp = sotoinpcb(so);
6088 if ((inp->inp_vflag & INP_IPV6) != 0) {
6089 flow->flow_src.ss_family = AF_INET6;
6090 flow->flow_dst.ss_family = AF_INET6;
6091 flow->flow_src.ss_len = sizeof(struct sockaddr_in6);
6092 flow->flow_dst.ss_len = sizeof(struct sockaddr_in6);
6093 SIN6(&flow->flow_src)->sin6_port = inp->in6p_lport;
6094 SIN6(&flow->flow_dst)->sin6_port = inp->in6p_fport;
6095 SIN6(&flow->flow_src)->sin6_addr = inp->in6p_laddr;
6096 SIN6(&flow->flow_dst)->sin6_addr = inp->in6p_faddr;
6097 } else if ((inp->inp_vflag & INP_IPV4) != 0) {
6098 flow->flow_src.ss_family = AF_INET;
6099 flow->flow_dst.ss_family = AF_INET;
6100 flow->flow_src.ss_len = sizeof(struct sockaddr_in);
6101 flow->flow_dst.ss_len = sizeof(struct sockaddr_in);
6102 SIN(&flow->flow_src)->sin_port = inp->inp_lport;
6103 SIN(&flow->flow_dst)->sin_port = inp->inp_fport;
6104 SIN(&flow->flow_src)->sin_addr = inp->inp_laddr;
6105 SIN(&flow->flow_dst)->sin_addr = inp->inp_faddr;
6106 }
6107 flow->flow_len = sizeof(*flow);
6108 flow->flow_tcpci_offset = offsetof(mptcp_flow_t, flow_ci);
6109 flow->flow_flags = mpts->mpts_flags;
6110 flow->flow_cid = mpts->mpts_connid;
6111 flow->flow_relseq = mpts->mpts_rel_seq;
6112 flow->flow_soerror = mpts->mpts_socket->so_error;
6113 flow->flow_probecnt = mpts->mpts_probecnt;
6114 }
6115
6116 static int
6117 mptcp_pcblist SYSCTL_HANDLER_ARGS
6118 {
6119 #pragma unused(oidp, arg1, arg2)
6120 int error = 0, f;
6121 size_t len;
6122 struct mppcb *mpp;
6123 struct mptses *mpte;
6124 struct mptcb *mp_tp;
6125 struct mptsub *mpts;
6126 struct socket *so;
6127 conninfo_mptcp_t mptcpci;
6128 mptcp_flow_t *flows = NULL;
6129
6130 if (req->newptr != USER_ADDR_NULL) {
6131 return EPERM;
6132 }
6133
6134 lck_mtx_lock(&mtcbinfo.mppi_lock);
6135 if (req->oldptr == USER_ADDR_NULL) {
6136 size_t n = mtcbinfo.mppi_count;
6137 lck_mtx_unlock(&mtcbinfo.mppi_lock);
6138 req->oldidx = (n + n / 8) * sizeof(conninfo_mptcp_t) +
6139 4 * (n + n / 8) * sizeof(mptcp_flow_t);
6140 return 0;
6141 }
6142 TAILQ_FOREACH(mpp, &mtcbinfo.mppi_pcbs, mpp_entry) {
6143 flows = NULL;
6144 socket_lock(mpp->mpp_socket, 1);
6145 VERIFY(mpp->mpp_flags & MPP_ATTACHED);
6146 mpte = mptompte(mpp);
6147
6148 socket_lock_assert_owned(mptetoso(mpte));
6149 mp_tp = mpte->mpte_mptcb;
6150
6151 bzero(&mptcpci, sizeof(mptcpci));
6152 mptcpci.mptcpci_state = mp_tp->mpt_state;
6153 mptcpci.mptcpci_flags = mp_tp->mpt_flags;
6154 mptcpci.mptcpci_ltoken = mp_tp->mpt_localtoken;
6155 mptcpci.mptcpci_rtoken = mp_tp->mpt_remotetoken;
6156 mptcpci.mptcpci_notsent_lowat = mp_tp->mpt_notsent_lowat;
6157 mptcpci.mptcpci_snduna = mp_tp->mpt_snduna;
6158 mptcpci.mptcpci_sndnxt = mp_tp->mpt_sndnxt;
6159 mptcpci.mptcpci_sndmax = mp_tp->mpt_sndmax;
6160 mptcpci.mptcpci_lidsn = mp_tp->mpt_local_idsn;
6161 mptcpci.mptcpci_sndwnd = mp_tp->mpt_sndwnd;
6162 mptcpci.mptcpci_rcvnxt = mp_tp->mpt_rcvnxt;
6163 mptcpci.mptcpci_rcvatmark = mp_tp->mpt_rcvnxt;
6164 mptcpci.mptcpci_ridsn = mp_tp->mpt_remote_idsn;
6165 mptcpci.mptcpci_rcvwnd = mp_tp->mpt_rcvwnd;
6166
6167 mptcpci.mptcpci_nflows = mpte->mpte_numflows;
6168 mptcpci.mptcpci_mpte_flags = mpte->mpte_flags;
6169 mptcpci.mptcpci_mpte_addrid = mpte->mpte_addrid_last;
6170 mptcpci.mptcpci_flow_offset =
6171 offsetof(conninfo_mptcp_t, mptcpci_flows);
6172
6173 len = sizeof(*flows) * mpte->mpte_numflows;
6174 if (mpte->mpte_numflows != 0) {
6175 flows = kalloc_data(len, Z_WAITOK | Z_ZERO);
6176 if (flows == NULL) {
6177 socket_unlock(mpp->mpp_socket, 1);
6178 break;
6179 }
6180 mptcpci.mptcpci_len = sizeof(mptcpci) +
6181 sizeof(*flows) * (mptcpci.mptcpci_nflows - 1);
6182 error = SYSCTL_OUT(req, &mptcpci,
6183 sizeof(mptcpci) - sizeof(mptcp_flow_t));
6184 } else {
6185 mptcpci.mptcpci_len = sizeof(mptcpci);
6186 error = SYSCTL_OUT(req, &mptcpci, sizeof(mptcpci));
6187 }
6188 if (error) {
6189 socket_unlock(mpp->mpp_socket, 1);
6190 kfree_data(flows, len);
6191 break;
6192 }
6193 f = 0;
6194 TAILQ_FOREACH(mpts, &mpte->mpte_subflows, mpts_entry) {
6195 so = mpts->mpts_socket;
6196 fill_mptcp_subflow(so, &flows[f], mpts);
6197 f++;
6198 }
6199 socket_unlock(mpp->mpp_socket, 1);
6200 if (flows) {
6201 error = SYSCTL_OUT(req, flows, len);
6202 kfree_data(flows, len);
6203 if (error) {
6204 break;
6205 }
6206 }
6207 }
6208 lck_mtx_unlock(&mtcbinfo.mppi_lock);
6209
6210 return error;
6211 }
6212
6213 SYSCTL_PROC(_net_inet_mptcp, OID_AUTO, pcblist, CTLFLAG_RD | CTLFLAG_LOCKED,
6214 0, 0, mptcp_pcblist, "S,conninfo_mptcp_t",
6215 "List of active MPTCP connections");
6216
6217 /*
6218 * Set notsent lowat mark on the MPTCB
6219 */
6220 int
mptcp_set_notsent_lowat(struct mptses * mpte,int optval)6221 mptcp_set_notsent_lowat(struct mptses *mpte, int optval)
6222 {
6223 struct mptcb *mp_tp = NULL;
6224 int error = 0;
6225
6226 if (mpte->mpte_mppcb->mpp_flags & MPP_ATTACHED) {
6227 mp_tp = mpte->mpte_mptcb;
6228 }
6229
6230 if (mp_tp) {
6231 mp_tp->mpt_notsent_lowat = optval;
6232 } else {
6233 error = EINVAL;
6234 }
6235
6236 return error;
6237 }
6238
6239 u_int32_t
mptcp_get_notsent_lowat(struct mptses * mpte)6240 mptcp_get_notsent_lowat(struct mptses *mpte)
6241 {
6242 struct mptcb *mp_tp = NULL;
6243
6244 if (mpte->mpte_mppcb->mpp_flags & MPP_ATTACHED) {
6245 mp_tp = mpte->mpte_mptcb;
6246 }
6247
6248 if (mp_tp) {
6249 return mp_tp->mpt_notsent_lowat;
6250 } else {
6251 return 0;
6252 }
6253 }
6254
6255 int
mptcp_notsent_lowat_check(struct socket * so)6256 mptcp_notsent_lowat_check(struct socket *so)
6257 {
6258 struct mptses *mpte;
6259 struct mppcb *mpp;
6260 struct mptcb *mp_tp;
6261 struct mptsub *mpts;
6262
6263 int notsent = 0;
6264
6265 mpp = mpsotomppcb(so);
6266 if (mpp == NULL || mpp->mpp_state == MPPCB_STATE_DEAD) {
6267 return 0;
6268 }
6269
6270 mpte = mptompte(mpp);
6271 socket_lock_assert_owned(mptetoso(mpte));
6272 mp_tp = mpte->mpte_mptcb;
6273
6274 notsent = so->so_snd.sb_cc;
6275
6276 if ((notsent == 0) ||
6277 ((notsent - (mp_tp->mpt_sndnxt - mp_tp->mpt_snduna)) <=
6278 mp_tp->mpt_notsent_lowat)) {
6279 return 1;
6280 }
6281
6282 /* When Nagle's algorithm is not disabled, it is better
6283 * to wakeup the client even before there is atleast one
6284 * maxseg of data to write.
6285 */
6286 TAILQ_FOREACH(mpts, &mpte->mpte_subflows, mpts_entry) {
6287 int retval = 0;
6288 if (mpts->mpts_flags & MPTSF_ACTIVE) {
6289 struct socket *subf_so = mpts->mpts_socket;
6290 struct tcpcb *tp = intotcpcb(sotoinpcb(subf_so));
6291
6292 notsent = so->so_snd.sb_cc -
6293 (tp->snd_nxt - tp->snd_una);
6294
6295 if ((tp->t_flags & TF_NODELAY) == 0 &&
6296 notsent > 0 && (notsent <= (int)tp->t_maxseg)) {
6297 retval = 1;
6298 }
6299 return retval;
6300 }
6301 }
6302 return 0;
6303 }
6304
6305 static errno_t
mptcp_symptoms_ctl_connect(kern_ctl_ref kctlref,struct sockaddr_ctl * sac,void ** unitinfo)6306 mptcp_symptoms_ctl_connect(kern_ctl_ref kctlref, struct sockaddr_ctl *sac,
6307 void **unitinfo)
6308 {
6309 #pragma unused(kctlref, sac, unitinfo)
6310
6311 if (OSIncrementAtomic(&mptcp_kern_skt_inuse) > 0) {
6312 os_log_error(mptcp_log_handle, "%s: MPTCP kernel-control socket for Symptoms already open!", __func__);
6313 }
6314
6315 mptcp_kern_skt_unit = sac->sc_unit;
6316
6317 return 0;
6318 }
6319
6320 static void
mptcp_allow_uuid(uuid_t uuid,int32_t rssi)6321 mptcp_allow_uuid(uuid_t uuid, int32_t rssi)
6322 {
6323 struct mppcb *mpp;
6324
6325 /* Iterate over all MPTCP connections */
6326
6327 lck_mtx_lock(&mtcbinfo.mppi_lock);
6328
6329 TAILQ_FOREACH(mpp, &mtcbinfo.mppi_pcbs, mpp_entry) {
6330 struct socket *mp_so = mpp->mpp_socket;
6331 struct mptses *mpte = mpp->mpp_pcbe;
6332
6333 socket_lock(mp_so, 1);
6334
6335 if (mp_so->so_flags & SOF_DELEGATED &&
6336 uuid_compare(uuid, mp_so->e_uuid)) {
6337 goto next;
6338 } else if (!(mp_so->so_flags & SOF_DELEGATED) &&
6339 uuid_compare(uuid, mp_so->last_uuid)) {
6340 goto next;
6341 }
6342
6343 os_log(mptcp_log_handle, "%s - %lx: Got allowance for useApp with rssi %d\n",
6344 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), rssi);
6345
6346 mpte->mpte_flags |= MPTE_ACCESS_GRANTED;
6347
6348 if (rssi > MPTCP_TARGET_BASED_RSSI_THRESHOLD) {
6349 mpte->mpte_flags |= MPTE_CELL_PROHIBITED;
6350 }
6351
6352 mptcp_check_subflows_and_add(mpte);
6353 mptcp_remove_subflows(mpte);
6354
6355 mpte->mpte_flags &= ~(MPTE_ACCESS_GRANTED | MPTE_CELL_PROHIBITED);
6356
6357 next:
6358 socket_unlock(mp_so, 1);
6359 }
6360
6361 lck_mtx_unlock(&mtcbinfo.mppi_lock);
6362 }
6363
6364 static void
mptcp_wifi_status_changed(void)6365 mptcp_wifi_status_changed(void)
6366 {
6367 struct mppcb *mpp;
6368
6369 /* Iterate over all MPTCP connections */
6370
6371 lck_mtx_lock(&mtcbinfo.mppi_lock);
6372
6373 TAILQ_FOREACH(mpp, &mtcbinfo.mppi_pcbs, mpp_entry) {
6374 struct socket *mp_so = mpp->mpp_socket;
6375 struct mptses *mpte = mpp->mpp_pcbe;
6376
6377 socket_lock(mp_so, 1);
6378
6379 /* Only handover- and urgency-mode are purely driven by Symptom's Wi-Fi status */
6380 if (mpte->mpte_svctype != MPTCP_SVCTYPE_HANDOVER &&
6381 mpte->mpte_svctype != MPTCP_SVCTYPE_PURE_HANDOVER &&
6382 mpte->mpte_svctype != MPTCP_SVCTYPE_TARGET_BASED) {
6383 goto next;
6384 }
6385
6386 mptcp_check_subflows_and_add(mpte);
6387 mptcp_check_subflows_and_remove(mpte);
6388
6389 next:
6390 socket_unlock(mp_so, 1);
6391 }
6392
6393 lck_mtx_unlock(&mtcbinfo.mppi_lock);
6394 }
6395
6396 struct mptcp_uuid_search_info {
6397 uuid_t target_uuid;
6398 proc_t found_proc;
6399 boolean_t is_proc_found;
6400 };
6401
6402 static int
mptcp_find_proc_filter(proc_t p,void * arg)6403 mptcp_find_proc_filter(proc_t p, void *arg)
6404 {
6405 struct mptcp_uuid_search_info *info = (struct mptcp_uuid_search_info *)arg;
6406 int found;
6407
6408 if (info->is_proc_found) {
6409 return 0;
6410 }
6411
6412 /*
6413 * uuid_compare returns 0 if the uuids are matching, but the proc-filter
6414 * expects != 0 for a matching filter.
6415 */
6416 found = uuid_compare(proc_executableuuid_addr(p), info->target_uuid) == 0;
6417 if (found) {
6418 info->is_proc_found = true;
6419 }
6420
6421 return found;
6422 }
6423
6424 static int
mptcp_find_proc_callout(proc_t p,void * arg)6425 mptcp_find_proc_callout(proc_t p, void * arg)
6426 {
6427 struct mptcp_uuid_search_info *info = (struct mptcp_uuid_search_info *)arg;
6428
6429 if (uuid_compare(proc_executableuuid_addr(p), info->target_uuid) == 0) {
6430 info->found_proc = p;
6431 return PROC_CLAIMED_DONE;
6432 }
6433
6434 return PROC_RETURNED;
6435 }
6436
6437 static proc_t
mptcp_find_proc(const uuid_t uuid)6438 mptcp_find_proc(const uuid_t uuid)
6439 {
6440 struct mptcp_uuid_search_info info;
6441
6442 uuid_copy(info.target_uuid, uuid);
6443 info.found_proc = PROC_NULL;
6444 info.is_proc_found = false;
6445
6446 proc_iterate(PROC_ALLPROCLIST, mptcp_find_proc_callout, &info,
6447 mptcp_find_proc_filter, &info);
6448
6449 return info.found_proc;
6450 }
6451
6452 void
mptcp_ask_symptoms(struct mptses * mpte)6453 mptcp_ask_symptoms(struct mptses *mpte)
6454 {
6455 struct mptcp_symptoms_ask_uuid ask;
6456 struct socket *mp_so;
6457 struct proc *p = PROC_NULL;
6458 int pid, prio, err;
6459
6460 if (mptcp_kern_skt_unit == 0) {
6461 os_log_error(mptcp_log_handle, "%s - %lx: skt_unit is still 0\n",
6462 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte));
6463 return;
6464 }
6465
6466 mp_so = mptetoso(mpte);
6467
6468 if (mp_so->so_flags & SOF_DELEGATED) {
6469 if (mpte->mpte_epid != 0) {
6470 p = proc_find(mpte->mpte_epid);
6471 if (p != PROC_NULL) {
6472 /* We found a pid, check its UUID */
6473 if (uuid_compare(mp_so->e_uuid, proc_executableuuid_addr(p))) {
6474 /* It's not the same - we need to look for the real proc */
6475 proc_rele(p);
6476 p = PROC_NULL;
6477 }
6478 }
6479 }
6480
6481 if (p == PROC_NULL) {
6482 p = mptcp_find_proc(mp_so->e_uuid);
6483 if (p == PROC_NULL) {
6484 uuid_string_t uuid_string;
6485 uuid_unparse(mp_so->e_uuid, uuid_string);
6486
6487 os_log_error(mptcp_log_handle, "%s - %lx: Couldn't find proc for uuid %s\n",
6488 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), uuid_string);
6489
6490 return;
6491 }
6492 mpte->mpte_epid = proc_pid(p);
6493 }
6494
6495 pid = mpte->mpte_epid;
6496 uuid_copy(ask.uuid, mp_so->e_uuid);
6497 } else {
6498 pid = mp_so->last_pid;
6499
6500 p = proc_find(pid);
6501 if (p == PROC_NULL) {
6502 os_log_error(mptcp_log_handle, "%s - %lx: Couldn't find proc for pid %u\n",
6503 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), pid);
6504 return;
6505 }
6506
6507 uuid_copy(ask.uuid, mp_so->last_uuid);
6508 }
6509
6510
6511 ask.cmd = MPTCP_SYMPTOMS_ASK_UUID;
6512
6513 prio = proc_get_effective_task_policy(proc_task(p), TASK_POLICY_ROLE);
6514
6515 if (prio == TASK_BACKGROUND_APPLICATION || prio == TASK_NONUI_APPLICATION ||
6516 prio == TASK_DARWINBG_APPLICATION) {
6517 ask.priority = MPTCP_SYMPTOMS_BACKGROUND;
6518 } else if (prio == TASK_FOREGROUND_APPLICATION) {
6519 ask.priority = MPTCP_SYMPTOMS_FOREGROUND;
6520 } else {
6521 ask.priority = MPTCP_SYMPTOMS_UNKNOWN;
6522 }
6523
6524 err = ctl_enqueuedata(mptcp_kern_ctrl_ref, mptcp_kern_skt_unit,
6525 &ask, sizeof(ask), CTL_DATA_EOR);
6526
6527 os_log(mptcp_log_handle, "%s - %lx: asked symptoms about pid %u, taskprio %u, prio %u, err %d\n",
6528 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), pid, prio, ask.priority, err);
6529
6530
6531 proc_rele(p);
6532 }
6533
6534 static errno_t
mptcp_symptoms_ctl_disconnect(kern_ctl_ref kctlref,u_int32_t kcunit,void * unitinfo)6535 mptcp_symptoms_ctl_disconnect(kern_ctl_ref kctlref, u_int32_t kcunit,
6536 void *unitinfo)
6537 {
6538 #pragma unused(kctlref, kcunit, unitinfo)
6539
6540 OSDecrementAtomic(&mptcp_kern_skt_inuse);
6541
6542 return 0;
6543 }
6544
6545 static errno_t
mptcp_symptoms_ctl_send(kern_ctl_ref kctlref,u_int32_t kcunit,void * unitinfo,mbuf_t m,int flags)6546 mptcp_symptoms_ctl_send(kern_ctl_ref kctlref, u_int32_t kcunit, void *unitinfo,
6547 mbuf_t m, int flags)
6548 {
6549 #pragma unused(kctlref, unitinfo, flags)
6550 symptoms_advisory_t *sa = NULL;
6551
6552 if (kcunit != mptcp_kern_skt_unit) {
6553 os_log_error(mptcp_log_handle, "%s: kcunit %u is different from expected one %u\n",
6554 __func__, kcunit, mptcp_kern_skt_unit);
6555 }
6556
6557 if (mbuf_pkthdr_len(m) < sizeof(*sa)) {
6558 mbuf_freem(m);
6559 return EINVAL;
6560 }
6561
6562 if (mbuf_len(m) < sizeof(*sa)) {
6563 os_log_error(mptcp_log_handle, "%s: mbuf is %lu but need %lu\n",
6564 __func__, mbuf_len(m), sizeof(*sa));
6565 mbuf_freem(m);
6566 return EINVAL;
6567 }
6568
6569 sa = mtod(m, void *);
6570
6571 if (sa->sa_nwk_status != SYMPTOMS_ADVISORY_USEAPP) {
6572 os_log(mptcp_log_handle, "%s: wifi new,old: %d,%d, cell new, old: %d,%d\n", __func__,
6573 sa->sa_wifi_status, mptcp_advisory.sa_wifi_status,
6574 sa->sa_cell_status, mptcp_advisory.sa_cell_status);
6575
6576 if (sa->sa_wifi_status != mptcp_advisory.sa_wifi_status) {
6577 mptcp_advisory.sa_wifi_status = sa->sa_wifi_status;
6578 mptcp_wifi_status_changed();
6579 }
6580 } else {
6581 struct mptcp_symptoms_answer answer;
6582 errno_t err;
6583
6584 /* We temporarily allow different sizes for ease of submission */
6585 if (mbuf_len(m) != sizeof(uuid_t) + sizeof(*sa) &&
6586 mbuf_len(m) != sizeof(answer)) {
6587 os_log_error(mptcp_log_handle, "%s: mbuf is %lu but need %lu or %lu\n",
6588 __func__, mbuf_len(m), sizeof(uuid_t) + sizeof(*sa),
6589 sizeof(answer));
6590 mbuf_free(m);
6591 return EINVAL;
6592 }
6593
6594 memset(&answer, 0, sizeof(answer));
6595
6596 err = mbuf_copydata(m, 0, mbuf_len(m), &answer);
6597 if (err) {
6598 os_log_error(mptcp_log_handle, "%s: mbuf_copydata returned %d\n", __func__, err);
6599 mbuf_free(m);
6600 return err;
6601 }
6602
6603 mptcp_allow_uuid(answer.uuid, answer.rssi);
6604 }
6605
6606 mbuf_freem(m);
6607 return 0;
6608 }
6609
6610 void
mptcp_control_register(void)6611 mptcp_control_register(void)
6612 {
6613 /* Set up the advisory control socket */
6614 struct kern_ctl_reg mptcp_kern_ctl;
6615
6616 bzero(&mptcp_kern_ctl, sizeof(mptcp_kern_ctl));
6617 strlcpy(mptcp_kern_ctl.ctl_name, MPTCP_KERN_CTL_NAME,
6618 sizeof(mptcp_kern_ctl.ctl_name));
6619 mptcp_kern_ctl.ctl_connect = mptcp_symptoms_ctl_connect;
6620 mptcp_kern_ctl.ctl_disconnect = mptcp_symptoms_ctl_disconnect;
6621 mptcp_kern_ctl.ctl_send = mptcp_symptoms_ctl_send;
6622 mptcp_kern_ctl.ctl_flags = CTL_FLAG_PRIVILEGED;
6623
6624 (void)ctl_register(&mptcp_kern_ctl, &mptcp_kern_ctrl_ref);
6625 }
6626
6627 mptcp_wifi_quality_t
mptcp_wifi_quality_for_session(struct mptses * mpte)6628 mptcp_wifi_quality_for_session(struct mptses *mpte)
6629 {
6630 if (mpte->mpte_flags & MPTE_FIRSTPARTY) {
6631 if (mpte->mpte_svctype != MPTCP_SVCTYPE_HANDOVER &&
6632 mptcp_advisory.sa_wifi_status) {
6633 return symptoms_is_wifi_lossy() ? MPTCP_WIFI_QUALITY_BAD : MPTCP_WIFI_QUALITY_GOOD;
6634 }
6635
6636 /*
6637 * If it's a first-party app and we don't have any info
6638 * about the Wi-Fi state, let's be pessimistic.
6639 */
6640 return MPTCP_WIFI_QUALITY_UNSURE;
6641 } else {
6642 if (symptoms_is_wifi_lossy()) {
6643 return MPTCP_WIFI_QUALITY_BAD;
6644 }
6645
6646 /*
6647 * If we are target-based (meaning, we allow to be more lax on
6648 * the when wifi is considered bad), we only *know* about the state once
6649 * we got the allowance from Symptoms (MPTE_ACCESS_GRANTED).
6650 *
6651 * If RSSI is not bad enough, MPTE_CELL_PROHIBITED will then
6652 * be set.
6653 *
6654 * In any other case (while in target-mode), consider WiFi bad
6655 * and we are going to ask for allowance from Symptoms anyway.
6656 */
6657 if (mpte->mpte_svctype == MPTCP_SVCTYPE_TARGET_BASED) {
6658 if (mpte->mpte_flags & MPTE_ACCESS_GRANTED &&
6659 mpte->mpte_flags & MPTE_CELL_PROHIBITED) {
6660 return MPTCP_WIFI_QUALITY_GOOD;
6661 }
6662
6663 return MPTCP_WIFI_QUALITY_BAD;
6664 }
6665
6666 return MPTCP_WIFI_QUALITY_GOOD;
6667 }
6668 }
6669
6670 boolean_t
symptoms_is_wifi_lossy(void)6671 symptoms_is_wifi_lossy(void)
6672 {
6673 return (mptcp_advisory.sa_wifi_status & SYMPTOMS_ADVISORY_WIFI_OK) ? false : true;
6674 }
6675
6676 int
mptcp_freeq(struct mptcb * mp_tp)6677 mptcp_freeq(struct mptcb *mp_tp)
6678 {
6679 struct tseg_qent *q;
6680 int rv = 0;
6681 int count = 0;
6682
6683 while ((q = LIST_FIRST(&mp_tp->mpt_segq)) != NULL) {
6684 LIST_REMOVE(q, tqe_q);
6685 m_freem(q->tqe_m);
6686 tcp_reass_qent_free(q);
6687 count++;
6688 rv = 1;
6689 }
6690 mp_tp->mpt_reassqlen = 0;
6691
6692 if (count > 0) {
6693 OSAddAtomic(-count, &mptcp_reass_total_qlen);
6694 }
6695
6696 return rv;
6697 }
6698
6699 static int
mptcp_post_event(u_int32_t event_code,int value)6700 mptcp_post_event(u_int32_t event_code, int value)
6701 {
6702 struct kev_mptcp_data event_data;
6703 struct kev_msg ev_msg;
6704
6705 memset(&ev_msg, 0, sizeof(ev_msg));
6706
6707 ev_msg.vendor_code = KEV_VENDOR_APPLE;
6708 ev_msg.kev_class = KEV_NETWORK_CLASS;
6709 ev_msg.kev_subclass = KEV_MPTCP_SUBCLASS;
6710 ev_msg.event_code = event_code;
6711
6712 event_data.value = value;
6713
6714 ev_msg.dv[0].data_ptr = &event_data;
6715 ev_msg.dv[0].data_length = sizeof(event_data);
6716
6717 return kev_post_msg(&ev_msg);
6718 }
6719
6720 static void
mptcp_set_cellicon(struct mptses * mpte,struct mptsub * mpts)6721 mptcp_set_cellicon(struct mptses *mpte, struct mptsub *mpts)
6722 {
6723 struct tcpcb *tp = sototcpcb(mpts->mpts_socket);
6724 int error;
6725
6726 /* First-party apps (Siri) don't flip the cellicon */
6727 if (mpte->mpte_flags & MPTE_FIRSTPARTY) {
6728 return;
6729 }
6730
6731 /* Subflow is disappearing - don't set it on this one */
6732 if (mpts->mpts_flags & (MPTSF_DISCONNECTING | MPTSF_DISCONNECTED)) {
6733 return;
6734 }
6735
6736 /* Fallen back connections are not triggering the cellicon */
6737 if (mpte->mpte_mptcb->mpt_flags & MPTCPF_FALLBACK_TO_TCP) {
6738 return;
6739 }
6740
6741 /* Remember the last time we set the cellicon. Needed for debouncing */
6742 mpte->mpte_last_cellicon_set = tcp_now;
6743
6744 tp->t_timer[TCPT_CELLICON] = OFFSET_FROM_START(tp, MPTCP_CELLICON_TOGGLE_RATE);
6745 tcp_sched_timers(tp);
6746
6747 if (mpts->mpts_flags & MPTSF_CELLICON_SET &&
6748 mpte->mpte_cellicon_increments != 0) {
6749 if (mptcp_cellicon_refcount == 0) {
6750 os_log_error(mptcp_log_handle, "%s - %lx: Cell should be set (count is %u), but it's zero!\n",
6751 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), mpte->mpte_cellicon_increments);
6752
6753 /* Continue, so that the icon gets set... */
6754 } else {
6755 /*
6756 * In this case, the cellicon is already set. No need to bump it
6757 * even higher
6758 */
6759
6760 return;
6761 }
6762 }
6763
6764 /* When tearing down this subflow, we need to decrement the
6765 * reference counter
6766 */
6767 mpts->mpts_flags |= MPTSF_CELLICON_SET;
6768
6769 /* This counter, so that when a session gets destroyed we decrement
6770 * the reference counter by whatever is left
6771 */
6772 mpte->mpte_cellicon_increments++;
6773
6774 if (OSIncrementAtomic(&mptcp_cellicon_refcount)) {
6775 /* If cellicon is already set, get out of here! */
6776 return;
6777 }
6778
6779 error = mptcp_post_event(KEV_MPTCP_CELLUSE, 1);
6780
6781 if (error) {
6782 os_log_error(mptcp_log_handle, "%s - %lx: Setting cellicon failed with %d\n",
6783 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), error);
6784 } else {
6785 os_log(mptcp_log_handle, "%s - %lx: successfully set the cellicon\n",
6786 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte));
6787 }
6788 }
6789
6790 void
mptcp_clear_cellicon(void)6791 mptcp_clear_cellicon(void)
6792 {
6793 int error = mptcp_post_event(KEV_MPTCP_CELLUSE, 0);
6794
6795 if (error) {
6796 os_log_error(mptcp_log_handle, "%s: Unsetting cellicon failed with %d\n",
6797 __func__, error);
6798 } else {
6799 os_log(mptcp_log_handle, "%s: successfully unset the cellicon\n",
6800 __func__);
6801 }
6802 }
6803
6804 /*
6805 * Returns true if the icon has been flipped to WiFi.
6806 */
6807 static boolean_t
__mptcp_unset_cellicon(uint32_t val)6808 __mptcp_unset_cellicon(uint32_t val)
6809 {
6810 VERIFY(val < INT32_MAX);
6811 if (OSAddAtomic((int32_t)-val, &mptcp_cellicon_refcount) != 1) {
6812 return false;
6813 }
6814
6815 mptcp_clear_cellicon();
6816
6817 return true;
6818 }
6819
6820 void
mptcp_unset_cellicon(struct mptses * mpte,struct mptsub * mpts,uint32_t val)6821 mptcp_unset_cellicon(struct mptses *mpte, struct mptsub *mpts, uint32_t val)
6822 {
6823 /* First-party apps (Siri) don't flip the cellicon */
6824 if (mpte->mpte_flags & MPTE_FIRSTPARTY) {
6825 return;
6826 }
6827
6828 if (mpte->mpte_cellicon_increments == 0) {
6829 /* This flow never used cell - get out of here! */
6830 return;
6831 }
6832
6833 if (mptcp_cellicon_refcount == 0) {
6834 os_log_error(mptcp_log_handle, "%s - %lx: Cell is off, but should be at least %u\n",
6835 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), mpte->mpte_cellicon_increments);
6836
6837 return;
6838 }
6839
6840 if (mpts) {
6841 if (!(mpts->mpts_flags & MPTSF_CELLICON_SET)) {
6842 return;
6843 }
6844
6845 mpts->mpts_flags &= ~MPTSF_CELLICON_SET;
6846 }
6847
6848 if (mpte->mpte_cellicon_increments < val) {
6849 os_log_error(mptcp_log_handle, "%s - %lx: Increments is %u but want to dec by %u.\n",
6850 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), mpte->mpte_cellicon_increments, val);
6851 val = mpte->mpte_cellicon_increments;
6852 }
6853
6854 mpte->mpte_cellicon_increments -= val;
6855
6856 if (__mptcp_unset_cellicon(val) == false) {
6857 return;
6858 }
6859
6860 /* All flows are gone - our counter should be at zero too! */
6861 if (mpte->mpte_cellicon_increments != 0) {
6862 os_log_error(mptcp_log_handle, "%s - %lx: Inconsistent state! Cell refcount is zero but increments are at %u\n",
6863 __func__, (unsigned long)VM_KERNEL_ADDRPERM(mpte), mpte->mpte_cellicon_increments);
6864 }
6865 }
6866
6867 void
mptcp_reset_rexmit_state(struct tcpcb * tp)6868 mptcp_reset_rexmit_state(struct tcpcb *tp)
6869 {
6870 struct mptsub *mpts;
6871 struct inpcb *inp;
6872 struct socket *so;
6873
6874 inp = tp->t_inpcb;
6875 if (inp == NULL) {
6876 return;
6877 }
6878
6879 so = inp->inp_socket;
6880 if (so == NULL) {
6881 return;
6882 }
6883
6884 if (!(so->so_flags & SOF_MP_SUBFLOW)) {
6885 return;
6886 }
6887
6888 mpts = tp->t_mpsub;
6889
6890 mpts->mpts_flags &= ~MPTSF_WRITE_STALL;
6891 so->so_flags &= ~SOF_MP_TRYFAILOVER;
6892 }
6893
6894 void
mptcp_reset_keepalive(struct tcpcb * tp)6895 mptcp_reset_keepalive(struct tcpcb *tp)
6896 {
6897 struct mptsub *mpts = tp->t_mpsub;
6898
6899 mpts->mpts_flags &= ~MPTSF_READ_STALL;
6900 }
6901
6902 static struct mppcb *
mtcp_alloc(void)6903 mtcp_alloc(void)
6904 {
6905 return &kalloc_type(struct mpp_mtp, Z_WAITOK | Z_ZERO | Z_NOFAIL)->mpp;
6906 }
6907
6908 static void
mtcp_free(struct mppcb * mpp)6909 mtcp_free(struct mppcb *mpp)
6910 {
6911 struct mpp_mtp *mtp = __container_of(mpp, struct mpp_mtp, mpp);
6912
6913 kfree_type(struct mpp_mtp, mtp);
6914 }
6915
6916 /*
6917 * Protocol pr_init callback.
6918 */
6919 void
mptcp_init(struct protosw * pp,struct domain * dp)6920 mptcp_init(struct protosw *pp, struct domain *dp)
6921 {
6922 #pragma unused(dp)
6923 static int mptcp_initialized = 0;
6924 struct protosw *prp;
6925 struct ip6protosw *prp6;
6926
6927 VERIFY((pp->pr_flags & (PR_INITIALIZED | PR_ATTACHED)) == PR_ATTACHED);
6928
6929 /* do this only once */
6930 if (mptcp_initialized) {
6931 return;
6932 }
6933 mptcp_initialized = 1;
6934
6935 mptcp_advisory.sa_wifi_status = SYMPTOMS_ADVISORY_WIFI_OK;
6936
6937 /*
6938 * Since PF_MULTIPATH gets initialized after PF_INET/INET6,
6939 * we must be able to find IPPROTO_TCP entries for both.
6940 */
6941 prp = pffindproto_locked(PF_INET, IPPROTO_TCP, SOCK_STREAM);
6942 VERIFY(prp != NULL);
6943 bcopy(prp, &mptcp_subflow_protosw, sizeof(*prp));
6944 bcopy(prp->pr_usrreqs, &mptcp_subflow_usrreqs,
6945 sizeof(mptcp_subflow_usrreqs));
6946 mptcp_subflow_protosw.pr_entry.tqe_next = NULL;
6947 mptcp_subflow_protosw.pr_entry.tqe_prev = NULL;
6948 mptcp_subflow_protosw.pr_usrreqs = &mptcp_subflow_usrreqs;
6949 mptcp_subflow_usrreqs.pru_soreceive = mptcp_subflow_soreceive;
6950 mptcp_subflow_usrreqs.pru_sosend = mptcp_subflow_sosend;
6951 mptcp_subflow_usrreqs.pru_rcvoob = pru_rcvoob_notsupp;
6952 /*
6953 * Socket filters shouldn't attach/detach to/from this protosw
6954 * since pr_protosw is to be used instead, which points to the
6955 * real protocol; if they do, it is a bug and we should panic.
6956 */
6957 mptcp_subflow_protosw.pr_filter_head.tqh_first =
6958 __unsafe_forge_single(struct socket_filter *, 0xdeadbeefdeadbeef);
6959 mptcp_subflow_protosw.pr_filter_head.tqh_last =
6960 __unsafe_forge_single(struct socket_filter **, 0xdeadbeefdeadbeef);
6961
6962 prp6 = (struct ip6protosw *)pffindproto_locked(PF_INET6,
6963 IPPROTO_TCP, SOCK_STREAM);
6964 VERIFY(prp6 != NULL);
6965 bcopy(prp6, &mptcp_subflow_protosw6, sizeof(*prp6));
6966 bcopy(prp6->pr_usrreqs, &mptcp_subflow_usrreqs6,
6967 sizeof(mptcp_subflow_usrreqs6));
6968 mptcp_subflow_protosw6.pr_entry.tqe_next = NULL;
6969 mptcp_subflow_protosw6.pr_entry.tqe_prev = NULL;
6970 mptcp_subflow_protosw6.pr_usrreqs = &mptcp_subflow_usrreqs6;
6971 mptcp_subflow_usrreqs6.pru_soreceive = mptcp_subflow_soreceive;
6972 mptcp_subflow_usrreqs6.pru_sosend = mptcp_subflow_sosend;
6973 mptcp_subflow_usrreqs6.pru_rcvoob = pru_rcvoob_notsupp;
6974 /*
6975 * Socket filters shouldn't attach/detach to/from this protosw
6976 * since pr_protosw is to be used instead, which points to the
6977 * real protocol; if they do, it is a bug and we should panic.
6978 */
6979 mptcp_subflow_protosw6.pr_filter_head.tqh_first =
6980 __unsafe_forge_single(struct socket_filter *, 0xdeadbeefdeadbeef);
6981 mptcp_subflow_protosw6.pr_filter_head.tqh_last =
6982 __unsafe_forge_single(struct socket_filter **, 0xdeadbeefdeadbeef);
6983
6984 bzero(&mtcbinfo, sizeof(mtcbinfo));
6985 TAILQ_INIT(&mtcbinfo.mppi_pcbs);
6986 mtcbinfo.mppi_alloc = mtcp_alloc;
6987 mtcbinfo.mppi_free = mtcp_free;
6988
6989 mtcbinfo.mppi_lock_grp = lck_grp_alloc_init("mppcb", LCK_GRP_ATTR_NULL);
6990 lck_attr_setdefault(&mtcbinfo.mppi_lock_attr);
6991 lck_mtx_init(&mtcbinfo.mppi_lock, mtcbinfo.mppi_lock_grp,
6992 &mtcbinfo.mppi_lock_attr);
6993
6994 mtcbinfo.mppi_gc = mptcp_gc;
6995 mtcbinfo.mppi_timer = mptcp_timer;
6996
6997 /* attach to MP domain for garbage collection to take place */
6998 mp_pcbinfo_attach(&mtcbinfo);
6999
7000 mptcp_log_handle = os_log_create("com.apple.xnu.net.mptcp", "mptcp");
7001 }
7002