-
Notifications
You must be signed in to change notification settings - Fork 201
/
Copy pathuipc_socket.c
8164 lines (7246 loc) · 203 KB
/
uipc_socket.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1998-2022 Apple Inc. All rights reserved.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* unlawful or unlicensed copies of an Apple operating system, or to
* circumvent, violate, or enable the circumvention or violation of, any
* terms of an Apple operating system software license agreement.
*
* Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_END@
*/
/* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
/*
* Copyright (c) 1982, 1986, 1988, 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)uipc_socket.c 8.3 (Berkeley) 4/15/94
*/
/*
* NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
* support for mandatory and extensible security protections. This notice
* is included in support of clause 2.2 (b) of the Apple Public License,
* Version 2.0.
*/
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/filedesc.h>
#include <sys/proc.h>
#include <sys/proc_internal.h>
#include <sys/kauth.h>
#include <sys/file_internal.h>
#include <sys/fcntl.h>
#include <sys/malloc.h>
#include <sys/mbuf.h>
#include <sys/domain.h>
#include <sys/kernel.h>
#include <sys/event.h>
#include <sys/poll.h>
#include <sys/protosw.h>
#include <sys/socket.h>
#include <sys/socketvar.h>
#include <sys/resourcevar.h>
#include <sys/signalvar.h>
#include <sys/sysctl.h>
#include <sys/syslog.h>
#include <sys/uio.h>
#include <sys/uio_internal.h>
#include <sys/ev.h>
#include <sys/kdebug.h>
#include <sys/un.h>
#include <sys/user.h>
#include <sys/priv.h>
#include <sys/kern_event.h>
#include <sys/persona.h>
#include <net/route.h>
#include <net/init.h>
#include <net/net_api_stats.h>
#include <net/ntstat.h>
#include <net/content_filter.h>
#include <netinet/in.h>
#include <netinet/in_pcb.h>
#include <netinet/in_tclass.h>
#include <netinet/in_var.h>
#include <netinet/tcp_var.h>
#include <netinet/ip6.h>
#include <netinet6/ip6_var.h>
#include <netinet/flow_divert.h>
#include <kern/zalloc.h>
#include <kern/locks.h>
#include <machine/limits.h>
#include <libkern/OSAtomic.h>
#include <pexpert/pexpert.h>
#include <kern/assert.h>
#include <kern/task.h>
#include <kern/policy_internal.h>
#include <sys/kpi_mbuf.h>
#include <sys/mcache.h>
#include <sys/unpcb.h>
#include <libkern/section_keywords.h>
#include <os/log.h>
#if CONFIG_MACF
#include <security/mac_framework.h>
#endif /* MAC */
#if MULTIPATH
#include <netinet/mp_pcb.h>
#include <netinet/mptcp_var.h>
#endif /* MULTIPATH */
#define ROUNDUP(a, b) (((a) + ((b) - 1)) & (~((b) - 1)))
#if DEBUG || DEVELOPMENT
#define DEBUG_KERNEL_ADDRPERM(_v) (_v)
#else
#define DEBUG_KERNEL_ADDRPERM(_v) VM_KERNEL_ADDRPERM(_v)
#endif
/* TODO: this should be in a header file somewhere */
extern char *proc_name_address(void *p);
static u_int32_t so_cache_hw; /* High water mark for socache */
static u_int32_t so_cache_timeouts; /* number of timeouts */
static u_int32_t so_cache_max_freed; /* max freed per timeout */
static u_int32_t cached_sock_count = 0;
STAILQ_HEAD(, socket) so_cache_head;
int max_cached_sock_count = MAX_CACHED_SOCKETS;
static uint64_t so_cache_time;
static int socketinit_done;
static struct zone *so_cache_zone;
static LCK_GRP_DECLARE(so_cache_mtx_grp, "so_cache");
static LCK_MTX_DECLARE(so_cache_mtx, &so_cache_mtx_grp);
#include <machine/limits.h>
static int filt_sorattach(struct knote *kn, struct kevent_qos_s *kev);
static void filt_sordetach(struct knote *kn);
static int filt_soread(struct knote *kn, long hint);
static int filt_sortouch(struct knote *kn, struct kevent_qos_s *kev);
static int filt_sorprocess(struct knote *kn, struct kevent_qos_s *kev);
static int filt_sowattach(struct knote *kn, struct kevent_qos_s *kev);
static void filt_sowdetach(struct knote *kn);
static int filt_sowrite(struct knote *kn, long hint);
static int filt_sowtouch(struct knote *kn, struct kevent_qos_s *kev);
static int filt_sowprocess(struct knote *kn, struct kevent_qos_s *kev);
static int filt_sockattach(struct knote *kn, struct kevent_qos_s *kev);
static void filt_sockdetach(struct knote *kn);
static int filt_sockev(struct knote *kn, long hint);
static int filt_socktouch(struct knote *kn, struct kevent_qos_s *kev);
static int filt_sockprocess(struct knote *kn, struct kevent_qos_s *kev);
static int sooptcopyin_timeval(struct sockopt *, struct timeval *);
static int sooptcopyout_timeval(struct sockopt *, const struct timeval *);
SECURITY_READ_ONLY_EARLY(struct filterops) soread_filtops = {
.f_isfd = 1,
.f_attach = filt_sorattach,
.f_detach = filt_sordetach,
.f_event = filt_soread,
.f_touch = filt_sortouch,
.f_process = filt_sorprocess,
};
SECURITY_READ_ONLY_EARLY(struct filterops) sowrite_filtops = {
.f_isfd = 1,
.f_attach = filt_sowattach,
.f_detach = filt_sowdetach,
.f_event = filt_sowrite,
.f_touch = filt_sowtouch,
.f_process = filt_sowprocess,
};
SECURITY_READ_ONLY_EARLY(struct filterops) sock_filtops = {
.f_isfd = 1,
.f_attach = filt_sockattach,
.f_detach = filt_sockdetach,
.f_event = filt_sockev,
.f_touch = filt_socktouch,
.f_process = filt_sockprocess,
};
SECURITY_READ_ONLY_EARLY(struct filterops) soexcept_filtops = {
.f_isfd = 1,
.f_attach = filt_sorattach,
.f_detach = filt_sordetach,
.f_event = filt_soread,
.f_touch = filt_sortouch,
.f_process = filt_sorprocess,
};
SYSCTL_DECL(_kern_ipc);
#define EVEN_MORE_LOCKING_DEBUG 0
int socket_debug = 0;
SYSCTL_INT(_kern_ipc, OID_AUTO, socket_debug,
CTLFLAG_RW | CTLFLAG_LOCKED, &socket_debug, 0, "");
#if (DEBUG || DEVELOPMENT)
#define DEFAULT_SOSEND_ASSERT_PANIC 1
#else
#define DEFAULT_SOSEND_ASSERT_PANIC 0
#endif /* (DEBUG || DEVELOPMENT) */
int sosend_assert_panic = 0;
SYSCTL_INT(_kern_ipc, OID_AUTO, sosend_assert_panic,
CTLFLAG_RW | CTLFLAG_LOCKED, &sosend_assert_panic, DEFAULT_SOSEND_ASSERT_PANIC, "");
static unsigned long sodefunct_calls = 0;
SYSCTL_LONG(_kern_ipc, OID_AUTO, sodefunct_calls, CTLFLAG_LOCKED,
&sodefunct_calls, "");
ZONE_DEFINE_TYPE(socket_zone, "socket", struct socket, ZC_ZFREE_CLEARMEM);
so_gen_t so_gencnt; /* generation count for sockets */
MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
#define DBG_LAYER_IN_BEG NETDBG_CODE(DBG_NETSOCK, 0)
#define DBG_LAYER_IN_END NETDBG_CODE(DBG_NETSOCK, 2)
#define DBG_LAYER_OUT_BEG NETDBG_CODE(DBG_NETSOCK, 1)
#define DBG_LAYER_OUT_END NETDBG_CODE(DBG_NETSOCK, 3)
#define DBG_FNC_SOSEND NETDBG_CODE(DBG_NETSOCK, (4 << 8) | 1)
#define DBG_FNC_SOSEND_LIST NETDBG_CODE(DBG_NETSOCK, (4 << 8) | 3)
#define DBG_FNC_SORECEIVE NETDBG_CODE(DBG_NETSOCK, (8 << 8))
#define DBG_FNC_SORECEIVE_LIST NETDBG_CODE(DBG_NETSOCK, (8 << 8) | 3)
#define DBG_FNC_SOSHUTDOWN NETDBG_CODE(DBG_NETSOCK, (9 << 8))
#define MAX_SOOPTGETM_SIZE (128 * MCLBYTES)
int somaxconn = SOMAXCONN;
SYSCTL_INT(_kern_ipc, KIPC_SOMAXCONN, somaxconn,
CTLFLAG_RW | CTLFLAG_LOCKED, &somaxconn, 0, "");
/* Should we get a maximum also ??? */
static int sosendmaxchain = 65536;
static int sosendminchain = 16384;
static int sorecvmincopy = 16384;
SYSCTL_INT(_kern_ipc, OID_AUTO, sosendminchain,
CTLFLAG_RW | CTLFLAG_LOCKED, &sosendminchain, 0, "");
SYSCTL_INT(_kern_ipc, OID_AUTO, sorecvmincopy,
CTLFLAG_RW | CTLFLAG_LOCKED, &sorecvmincopy, 0, "");
/*
* Set to enable jumbo clusters (if available) for large writes when
* the socket is marked with SOF_MULTIPAGES; see below.
*/
int sosendjcl = 1;
SYSCTL_INT(_kern_ipc, OID_AUTO, sosendjcl,
CTLFLAG_RW | CTLFLAG_LOCKED, &sosendjcl, 0, "");
/*
* Set this to ignore SOF_MULTIPAGES and use jumbo clusters for large
* writes on the socket for all protocols on any network interfaces,
* depending upon sosendjcl above. Be extra careful when setting this
* to 1, because sending down packets that cross physical pages down to
* broken drivers (those that falsely assume that the physical pages
* are contiguous) might lead to system panics or silent data corruption.
* When set to 0, the system will respect SOF_MULTIPAGES, which is set
* only for TCP sockets whose outgoing interface is IFNET_MULTIPAGES
* capable. Set this to 1 only for testing/debugging purposes.
*/
int sosendjcl_ignore_capab = 0;
SYSCTL_INT(_kern_ipc, OID_AUTO, sosendjcl_ignore_capab,
CTLFLAG_RW | CTLFLAG_LOCKED, &sosendjcl_ignore_capab, 0, "");
/*
* Set this to ignore SOF1_IF_2KCL and use big clusters for large
* writes on the socket for all protocols on any network interfaces.
* Be extra careful when setting this to 1, because sending down packets with
* clusters larger that 2 KB might lead to system panics or data corruption.
* When set to 0, the system will respect SOF1_IF_2KCL, which is set
* on the outgoing interface
* Set this to 1 for testing/debugging purposes only.
*/
int sosendbigcl_ignore_capab = 0;
SYSCTL_INT(_kern_ipc, OID_AUTO, sosendbigcl_ignore_capab,
CTLFLAG_RW | CTLFLAG_LOCKED, &sosendbigcl_ignore_capab, 0, "");
int sodefunctlog = 0;
SYSCTL_INT(_kern_ipc, OID_AUTO, sodefunctlog, CTLFLAG_RW | CTLFLAG_LOCKED,
&sodefunctlog, 0, "");
int sothrottlelog = 0;
SYSCTL_INT(_kern_ipc, OID_AUTO, sothrottlelog, CTLFLAG_RW | CTLFLAG_LOCKED,
&sothrottlelog, 0, "");
int sorestrictrecv = 1;
SYSCTL_INT(_kern_ipc, OID_AUTO, sorestrictrecv, CTLFLAG_RW | CTLFLAG_LOCKED,
&sorestrictrecv, 0, "Enable inbound interface restrictions");
int sorestrictsend = 1;
SYSCTL_INT(_kern_ipc, OID_AUTO, sorestrictsend, CTLFLAG_RW | CTLFLAG_LOCKED,
&sorestrictsend, 0, "Enable outbound interface restrictions");
int soreserveheadroom = 1;
SYSCTL_INT(_kern_ipc, OID_AUTO, soreserveheadroom, CTLFLAG_RW | CTLFLAG_LOCKED,
&soreserveheadroom, 0, "To allocate contiguous datagram buffers");
#if (DEBUG || DEVELOPMENT)
int so_notsent_lowat_check = 1;
SYSCTL_INT(_kern_ipc, OID_AUTO, notsent_lowat, CTLFLAG_RW | CTLFLAG_LOCKED,
&so_notsent_lowat_check, 0, "enable/disable notsnet lowat check");
#endif /* DEBUG || DEVELOPMENT */
int so_accept_list_waits = 0;
#if (DEBUG || DEVELOPMENT)
SYSCTL_INT(_kern_ipc, OID_AUTO, accept_list_waits, CTLFLAG_RW | CTLFLAG_LOCKED,
&so_accept_list_waits, 0, "number of waits for listener incomp list");
#endif /* DEBUG || DEVELOPMENT */
extern struct inpcbinfo tcbinfo;
/* TODO: these should be in header file */
extern int get_inpcb_str_size(void);
extern int get_tcp_str_size(void);
vm_size_t so_cache_zone_element_size;
static int sodelayed_copy(struct socket *, struct uio *, struct mbuf **,
user_ssize_t *);
static void cached_sock_alloc(struct socket **, zalloc_flags_t);
static void cached_sock_free(struct socket *);
/*
* Maximum of extended background idle sockets per process
* Set to zero to disable further setting of the option
*/
#define SO_IDLE_BK_IDLE_MAX_PER_PROC 1
#define SO_IDLE_BK_IDLE_TIME 600
#define SO_IDLE_BK_IDLE_RCV_HIWAT 131072
struct soextbkidlestat soextbkidlestat;
SYSCTL_UINT(_kern_ipc, OID_AUTO, maxextbkidleperproc,
CTLFLAG_RW | CTLFLAG_LOCKED, &soextbkidlestat.so_xbkidle_maxperproc, 0,
"Maximum of extended background idle sockets per process");
SYSCTL_UINT(_kern_ipc, OID_AUTO, extbkidletime, CTLFLAG_RW | CTLFLAG_LOCKED,
&soextbkidlestat.so_xbkidle_time, 0,
"Time in seconds to keep extended background idle sockets");
SYSCTL_UINT(_kern_ipc, OID_AUTO, extbkidlercvhiwat, CTLFLAG_RW | CTLFLAG_LOCKED,
&soextbkidlestat.so_xbkidle_rcvhiwat, 0,
"High water mark for extended background idle sockets");
SYSCTL_STRUCT(_kern_ipc, OID_AUTO, extbkidlestat, CTLFLAG_RD | CTLFLAG_LOCKED,
&soextbkidlestat, soextbkidlestat, "");
int so_set_extended_bk_idle(struct socket *, int);
#define SO_MAX_MSG_X 1024
/*
* SOTCDB_NO_DSCP is set by default, to prevent the networking stack from
* setting the DSCP code on the packet based on the service class; see
* <rdar://problem/11277343> for details.
*/
__private_extern__ u_int32_t sotcdb = 0;
SYSCTL_INT(_kern_ipc, OID_AUTO, sotcdb, CTLFLAG_RW | CTLFLAG_LOCKED,
&sotcdb, 0, "");
void
socketinit(void)
{
_CASSERT(sizeof(so_gencnt) == sizeof(uint64_t));
VERIFY(IS_P2ALIGNED(&so_gencnt, sizeof(uint32_t)));
#ifdef __LP64__
_CASSERT(sizeof(struct sa_endpoints) == sizeof(struct user64_sa_endpoints));
_CASSERT(offsetof(struct sa_endpoints, sae_srcif) == offsetof(struct user64_sa_endpoints, sae_srcif));
_CASSERT(offsetof(struct sa_endpoints, sae_srcaddr) == offsetof(struct user64_sa_endpoints, sae_srcaddr));
_CASSERT(offsetof(struct sa_endpoints, sae_srcaddrlen) == offsetof(struct user64_sa_endpoints, sae_srcaddrlen));
_CASSERT(offsetof(struct sa_endpoints, sae_dstaddr) == offsetof(struct user64_sa_endpoints, sae_dstaddr));
_CASSERT(offsetof(struct sa_endpoints, sae_dstaddrlen) == offsetof(struct user64_sa_endpoints, sae_dstaddrlen));
#else
_CASSERT(sizeof(struct sa_endpoints) == sizeof(struct user32_sa_endpoints));
_CASSERT(offsetof(struct sa_endpoints, sae_srcif) == offsetof(struct user32_sa_endpoints, sae_srcif));
_CASSERT(offsetof(struct sa_endpoints, sae_srcaddr) == offsetof(struct user32_sa_endpoints, sae_srcaddr));
_CASSERT(offsetof(struct sa_endpoints, sae_srcaddrlen) == offsetof(struct user32_sa_endpoints, sae_srcaddrlen));
_CASSERT(offsetof(struct sa_endpoints, sae_dstaddr) == offsetof(struct user32_sa_endpoints, sae_dstaddr));
_CASSERT(offsetof(struct sa_endpoints, sae_dstaddrlen) == offsetof(struct user32_sa_endpoints, sae_dstaddrlen));
#endif
if (socketinit_done) {
printf("socketinit: already called...\n");
return;
}
socketinit_done = 1;
PE_parse_boot_argn("socket_debug", &socket_debug,
sizeof(socket_debug));
PE_parse_boot_argn("sosend_assert_panic", &sosend_assert_panic,
sizeof(sosend_assert_panic));
STAILQ_INIT(&so_cache_head);
so_cache_zone_element_size = (vm_size_t)(sizeof(struct socket) + 4
+ get_inpcb_str_size() + 4 + get_tcp_str_size());
so_cache_zone = zone_create("socache zone", so_cache_zone_element_size,
ZC_PGZ_USE_GUARDS | ZC_ZFREE_CLEARMEM);
bzero(&soextbkidlestat, sizeof(struct soextbkidlestat));
soextbkidlestat.so_xbkidle_maxperproc = SO_IDLE_BK_IDLE_MAX_PER_PROC;
soextbkidlestat.so_xbkidle_time = SO_IDLE_BK_IDLE_TIME;
soextbkidlestat.so_xbkidle_rcvhiwat = SO_IDLE_BK_IDLE_RCV_HIWAT;
in_pcbinit();
}
static void
cached_sock_alloc(struct socket **so, zalloc_flags_t how)
{
caddr_t temp;
uintptr_t offset;
lck_mtx_lock(&so_cache_mtx);
if (!STAILQ_EMPTY(&so_cache_head)) {
VERIFY(cached_sock_count > 0);
*so = STAILQ_FIRST(&so_cache_head);
STAILQ_REMOVE_HEAD(&so_cache_head, so_cache_ent);
STAILQ_NEXT((*so), so_cache_ent) = NULL;
cached_sock_count--;
lck_mtx_unlock(&so_cache_mtx);
temp = (*so)->so_saved_pcb;
bzero((caddr_t)*so, sizeof(struct socket));
(*so)->so_saved_pcb = temp;
} else {
lck_mtx_unlock(&so_cache_mtx);
*so = zalloc_flags(so_cache_zone, how | Z_ZERO);
/*
* Define offsets for extra structures into our
* single block of memory. Align extra structures
* on longword boundaries.
*/
offset = (uintptr_t)*so;
offset += sizeof(struct socket);
offset = ALIGN(offset);
(*so)->so_saved_pcb = (caddr_t)offset;
offset += get_inpcb_str_size();
offset = ALIGN(offset);
((struct inpcb *)(void *)(*so)->so_saved_pcb)->inp_saved_ppcb =
(caddr_t)offset;
}
OSBitOrAtomic(SOF1_CACHED_IN_SOCK_LAYER, &(*so)->so_flags1);
}
static void
cached_sock_free(struct socket *so)
{
lck_mtx_lock(&so_cache_mtx);
so_cache_time = net_uptime();
if (++cached_sock_count > max_cached_sock_count) {
--cached_sock_count;
lck_mtx_unlock(&so_cache_mtx);
zfree(so_cache_zone, so);
} else {
if (so_cache_hw < cached_sock_count) {
so_cache_hw = cached_sock_count;
}
STAILQ_INSERT_TAIL(&so_cache_head, so, so_cache_ent);
so->cache_timestamp = so_cache_time;
lck_mtx_unlock(&so_cache_mtx);
}
}
void
so_update_last_owner_locked(struct socket *so, proc_t self)
{
if (so->last_pid != 0) {
/*
* last_pid and last_upid should remain zero for sockets
* created using sock_socket. The check above achieves that
*/
if (self == PROC_NULL) {
self = current_proc();
}
if (so->last_upid != proc_uniqueid(self) ||
so->last_pid != proc_pid(self)) {
so->last_upid = proc_uniqueid(self);
so->last_pid = proc_pid(self);
proc_getexecutableuuid(self, so->last_uuid,
sizeof(so->last_uuid));
if (so->so_proto != NULL && so->so_proto->pr_update_last_owner != NULL) {
(*so->so_proto->pr_update_last_owner)(so, self, NULL);
}
}
proc_pidoriginatoruuid(so->so_vuuid, sizeof(so->so_vuuid));
}
}
void
so_update_policy(struct socket *so)
{
if (SOCK_DOM(so) == PF_INET || SOCK_DOM(so) == PF_INET6) {
(void) inp_update_policy(sotoinpcb(so));
}
}
#if NECP
static void
so_update_necp_policy(struct socket *so, struct sockaddr *override_local_addr,
struct sockaddr *override_remote_addr)
{
if (SOCK_DOM(so) == PF_INET || SOCK_DOM(so) == PF_INET6) {
inp_update_necp_policy(sotoinpcb(so), override_local_addr,
override_remote_addr, 0);
}
}
#endif /* NECP */
boolean_t
so_cache_timer(void)
{
struct socket *p;
int n_freed = 0;
boolean_t rc = FALSE;
lck_mtx_lock(&so_cache_mtx);
so_cache_timeouts++;
so_cache_time = net_uptime();
while (!STAILQ_EMPTY(&so_cache_head)) {
VERIFY(cached_sock_count > 0);
p = STAILQ_FIRST(&so_cache_head);
if ((so_cache_time - p->cache_timestamp) <
SO_CACHE_TIME_LIMIT) {
break;
}
STAILQ_REMOVE_HEAD(&so_cache_head, so_cache_ent);
--cached_sock_count;
zfree(so_cache_zone, p);
if (++n_freed >= SO_CACHE_MAX_FREE_BATCH) {
so_cache_max_freed++;
break;
}
}
/* Schedule again if there is more to cleanup */
if (!STAILQ_EMPTY(&so_cache_head)) {
rc = TRUE;
}
lck_mtx_unlock(&so_cache_mtx);
return rc;
}
/*
* Get a socket structure from our zone, and initialize it.
* We don't implement `waitok' yet (see comments in uipc_domain.c).
* Note that it would probably be better to allocate socket
* and PCB at the same time, but I'm not convinced that all
* the protocols can be easily modified to do this.
*/
struct socket *
soalloc(int waitok, int dom, int type)
{
zalloc_flags_t how = waitok ? Z_WAITOK : Z_NOWAIT;
struct socket *so;
if ((dom == PF_INET) && (type == SOCK_STREAM)) {
cached_sock_alloc(&so, how);
} else {
so = zalloc_flags(socket_zone, how | Z_ZERO);
}
if (so != NULL) {
so->so_gencnt = OSIncrementAtomic64((SInt64 *)&so_gencnt);
/*
* Increment the socket allocation statistics
*/
INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_alloc_total);
}
return so;
}
int
socreate_internal(int dom, struct socket **aso, int type, int proto,
struct proc *p, uint32_t flags, struct proc *ep)
{
struct protosw *prp;
struct socket *so;
int error = 0;
#if defined(XNU_TARGET_OS_OSX)
pid_t rpid = -1;
#endif
#if TCPDEBUG
extern int tcpconsdebug;
#endif
VERIFY(aso != NULL);
*aso = NULL;
if (proto != 0) {
prp = pffindproto(dom, proto, type);
} else {
prp = pffindtype(dom, type);
}
if (prp == NULL || prp->pr_usrreqs->pru_attach == NULL) {
if (pffinddomain(dom) == NULL) {
return EAFNOSUPPORT;
}
if (proto != 0) {
if (pffindprotonotype(dom, proto) != NULL) {
return EPROTOTYPE;
}
}
return EPROTONOSUPPORT;
}
if (prp->pr_type != type) {
return EPROTOTYPE;
}
so = soalloc(1, dom, type);
if (so == NULL) {
return ENOBUFS;
}
switch (dom) {
case PF_LOCAL:
INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_domain_local_total);
break;
case PF_INET:
INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_domain_inet_total);
if (type == SOCK_STREAM) {
INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_inet_stream_total);
} else {
INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_inet_dgram_total);
}
break;
case PF_ROUTE:
INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_domain_route_total);
break;
case PF_NDRV:
INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_domain_ndrv_total);
break;
case PF_KEY:
INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_domain_key_total);
break;
case PF_INET6:
INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_domain_inet6_total);
if (type == SOCK_STREAM) {
INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_inet6_stream_total);
} else {
INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_inet6_dgram_total);
}
break;
case PF_SYSTEM:
INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_domain_system_total);
break;
case PF_MULTIPATH:
INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_domain_multipath_total);
break;
default:
INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_domain_other_total);
break;
}
if (flags & SOCF_MPTCP) {
so->so_state |= SS_NBIO;
}
TAILQ_INIT(&so->so_incomp);
TAILQ_INIT(&so->so_comp);
so->so_type = (short)type;
so->last_upid = proc_uniqueid(p);
so->last_pid = proc_pid(p);
proc_getexecutableuuid(p, so->last_uuid, sizeof(so->last_uuid));
proc_pidoriginatoruuid(so->so_vuuid, sizeof(so->so_vuuid));
if (ep != PROC_NULL && ep != p) {
so->e_upid = proc_uniqueid(ep);
so->e_pid = proc_pid(ep);
proc_getexecutableuuid(ep, so->e_uuid, sizeof(so->e_uuid));
so->so_flags |= SOF_DELEGATED;
#if defined(XNU_TARGET_OS_OSX)
if (ep->p_responsible_pid != so->e_pid) {
rpid = ep->p_responsible_pid;
}
#endif
}
#if defined(XNU_TARGET_OS_OSX)
if (rpid < 0 && p->p_responsible_pid != so->last_pid) {
rpid = p->p_responsible_pid;
}
so->so_rpid = -1;
uuid_clear(so->so_ruuid);
if (rpid >= 0) {
proc_t rp = proc_find(rpid);
if (rp != PROC_NULL) {
proc_getexecutableuuid(rp, so->so_ruuid, sizeof(so->so_ruuid));
so->so_rpid = rpid;
proc_rele(rp);
}
}
#endif
so->so_cred = kauth_cred_proc_ref(p);
if (!suser(kauth_cred_get(), NULL)) {
so->so_state |= SS_PRIV;
}
so->so_persona_id = current_persona_get_id();
so->so_proto = prp;
so->so_rcv.sb_flags |= SB_RECV;
so->so_rcv.sb_so = so->so_snd.sb_so = so;
so->next_lock_lr = 0;
so->next_unlock_lr = 0;
/*
* Attachment will create the per pcb lock if necessary and
* increase refcount for creation, make sure it's done before
* socket is inserted in lists.
*/
so->so_usecount++;
error = (*prp->pr_usrreqs->pru_attach)(so, proto, p);
if (error != 0) {
/*
* Warning:
* If so_pcb is not zero, the socket will be leaked,
* so protocol attachment handler must be coded carefuly
*/
if (so->so_pcb != NULL) {
os_log_error(OS_LOG_DEFAULT,
"so_pcb not NULL after pru_attach error %d for dom %d, proto %d, type %d",
error, dom, proto, type);
}
/*
* Both SS_NOFDREF and SOF_PCBCLEARING should be set to free the socket
*/
so->so_state |= SS_NOFDREF;
so->so_flags |= SOF_PCBCLEARING;
VERIFY(so->so_usecount > 0);
so->so_usecount--;
sofreelastref(so, 1); /* will deallocate the socket */
return error;
}
/*
* Note: needs so_pcb to be set after pru_attach
*/
if (prp->pr_update_last_owner != NULL) {
(*prp->pr_update_last_owner)(so, p, ep);
}
os_atomic_inc(&prp->pr_domain->dom_refs, relaxed);
/* Attach socket filters for this protocol */
sflt_initsock(so);
#if TCPDEBUG
if (tcpconsdebug == 2) {
so->so_options |= SO_DEBUG;
}
#endif
so_set_default_traffic_class(so);
/*
* If this thread or task is marked to create backgrounded sockets,
* mark the socket as background.
*/
if (!(flags & SOCF_MPTCP) &&
proc_get_effective_thread_policy(current_thread(), TASK_POLICY_NEW_SOCKETS_BG)) {
socket_set_traffic_mgt_flags(so, TRAFFIC_MGT_SO_BACKGROUND);
so->so_background_thread = current_thread();
}
switch (dom) {
/*
* Don't mark Unix domain or system
* eligible for defunct by default.
*/
case PF_LOCAL:
case PF_SYSTEM:
so->so_flags |= SOF_NODEFUNCT;
break;
default:
break;
}
/*
* Entitlements can't be checked at socket creation time except if the
* application requested a feature guarded by a privilege (c.f., socket
* delegation).
* The priv(9) and the Sandboxing APIs are designed with the idea that
* a privilege check should only be triggered by a userland request.
* A privilege check at socket creation time is time consuming and
* could trigger many authorisation error messages from the security
* APIs.
*/
*aso = so;
return 0;
}
/*
* Returns: 0 Success
* EAFNOSUPPORT
* EPROTOTYPE
* EPROTONOSUPPORT
* ENOBUFS
* <pru_attach>:ENOBUFS[AF_UNIX]
* <pru_attach>:ENOBUFS[TCP]
* <pru_attach>:ENOMEM[TCP]
* <pru_attach>:??? [other protocol families, IPSEC]
*/
int
socreate(int dom, struct socket **aso, int type, int proto)
{
return socreate_internal(dom, aso, type, proto, current_proc(), 0,
PROC_NULL);
}
int
socreate_delegate(int dom, struct socket **aso, int type, int proto, pid_t epid)
{
int error = 0;
struct proc *ep = PROC_NULL;
if ((proc_selfpid() != epid) && ((ep = proc_find(epid)) == PROC_NULL)) {
error = ESRCH;
goto done;
}
error = socreate_internal(dom, aso, type, proto, current_proc(), 0, ep);
/*
* It might not be wise to hold the proc reference when calling
* socreate_internal since it calls soalloc with M_WAITOK
*/
done:
if (ep != PROC_NULL) {
proc_rele(ep);
}
return error;
}
/*
* Returns: 0 Success
* <pru_bind>:EINVAL Invalid argument [COMMON_START]
* <pru_bind>:EAFNOSUPPORT Address family not supported
* <pru_bind>:EADDRNOTAVAIL Address not available.
* <pru_bind>:EINVAL Invalid argument
* <pru_bind>:EAFNOSUPPORT Address family not supported [notdef]
* <pru_bind>:EACCES Permission denied
* <pru_bind>:EADDRINUSE Address in use
* <pru_bind>:EAGAIN Resource unavailable, try again
* <pru_bind>:EPERM Operation not permitted
* <pru_bind>:???
* <sf_bind>:???
*
* Notes: It's not possible to fully enumerate the return codes above,
* since socket filter authors and protocol family authors may
* not choose to limit their error returns to those listed, even
* though this may result in some software operating incorrectly.
*
* The error codes which are enumerated above are those known to
* be returned by the tcp_usr_bind function supplied.
*/
int
sobindlock(struct socket *so, struct sockaddr *nam, int dolock)
{
struct proc *p = current_proc();
int error = 0;
if (dolock) {
socket_lock(so, 1);
}
so_update_last_owner_locked(so, p);
so_update_policy(so);
#if NECP
so_update_necp_policy(so, nam, NULL);
#endif /* NECP */
/*
* If this is a bind request on a socket that has been marked
* as inactive, reject it now before we go any further.
*/
if (so->so_flags & SOF_DEFUNCT) {
error = EINVAL;
SODEFUNCTLOG("%s[%d, %s]: defunct so 0x%llu [%d,%d] (%d)\n",
__func__, proc_pid(p), proc_best_name(p),
so->so_gencnt,
SOCK_DOM(so), SOCK_TYPE(so), error);
goto out;
}
/* Socket filter */
error = sflt_bind(so, nam);
if (error == 0) {
error = (*so->so_proto->pr_usrreqs->pru_bind)(so, nam, p);
}
out:
if (dolock) {
socket_unlock(so, 1);
}
if (error == EJUSTRETURN) {
error = 0;
}
return error;
}
void
sodealloc(struct socket *so)
{
kauth_cred_unref(&so->so_cred);
/* Remove any filters */
sflt_termsock(so);
so->so_gencnt = OSIncrementAtomic64((SInt64 *)&so_gencnt);
if (so->so_flags1 & SOF1_CACHED_IN_SOCK_LAYER) {
cached_sock_free(so);
} else {
zfree(socket_zone, so);
}
}
/*
* Returns: 0 Success
* EINVAL
* EOPNOTSUPP
* <pru_listen>:EINVAL[AF_UNIX]
* <pru_listen>:EINVAL[TCP]
* <pru_listen>:EADDRNOTAVAIL[TCP] Address not available.
* <pru_listen>:EINVAL[TCP] Invalid argument
* <pru_listen>:EAFNOSUPPORT[TCP] Address family not supported [notdef]
* <pru_listen>:EACCES[TCP] Permission denied
* <pru_listen>:EADDRINUSE[TCP] Address in use
* <pru_listen>:EAGAIN[TCP] Resource unavailable, try again
* <pru_listen>:EPERM[TCP] Operation not permitted
* <sf_listen>:???
*
* Notes: Other <pru_listen> returns depend on the protocol family; all
* <sf_listen> returns depend on what the filter author causes
* their filter to return.