syd 3.54.1

rock-solid application kernel
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
//
// Syd: rock-solid application kernel
// src/kernel/net/mod.rs: Network syscall handlers
//
// Copyright (c) 2023, 2024, 2025, 2026 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0

use std::{
    borrow::Cow,
    net::IpAddr,
    ops::Deref,
    os::{
        fd::{AsFd, AsRawFd, RawFd},
        unix::ffi::OsStrExt,
    },
};

use ipnet::{IpNet, Ipv4Net, Ipv6Net};
use iprange::IpRange;
use libseccomp::ScmpNotifResp;
use nix::{
    errno::Errno,
    fcntl::OFlag,
    sys::socket::{getsockname, SockaddrLike, SockaddrStorage, UnixAddr},
    NixPath,
};

use crate::{
    compat::{
        addr_family, getsockdomain, sockaddr_family, AddressFamily, MsgFlags, PF_ALG, PF_INET,
        PF_INET6, PF_MAX, PF_NETLINK, PF_UNIX, PF_UNSPEC,
    },
    config::HOOK_SCKCALLS,
    confine::scmp_arch_bits,
    fd::{fd_status_flags, is_readable, is_writable, route_open, route_query_src, route_src},
    info,
    ip::{
        clear_scope6, has_privileged_port_v4, has_privileged_port_v6, make_lo6addr, make_loaddr,
        SocketCall,
    },
    kernel::net::{
        accept::handle_accept,
        bind::handle_bind,
        connect::handle_connect,
        getpeername::handle_getpeername,
        getsockname::handle_getsockname,
        getsockopt::handle_getsockopt,
        recvfrom::{handle_recv, handle_recvfrom},
        recvmsg::{handle_recvmmsg, handle_recvmmsg64, handle_recvmsg},
        sendmsg::{handle_sendmmsg, handle_sendmsg},
        sendto::handle_sendto,
        socket::{handle_socket, handle_socketpair},
    },
    log_enabled,
    lookup::{file_type, safe_canonicalize, CanonicalPath, FileType, FsFlags},
    path::{XPath, XPathBuf},
    req::UNotifyEventRequest,
    sandbox::{Action, AddressPattern, Capability, CidrRule, Flags, Options, SandboxGuard},
    syslog::LogLevel,
    warn,
};

pub(crate) mod accept;
pub(crate) mod bind;
pub(crate) mod connect;
pub(crate) mod getpeername;
pub(crate) mod getsockname;
pub(crate) mod getsockopt;
pub(crate) mod recvfrom;
pub(crate) mod recvmsg;
pub(crate) mod sendmsg;
pub(crate) mod sendto;
pub(crate) mod socket;

const UNIX_PATH_MAX: usize = 108;

#[derive(Copy, Clone, Debug)]
pub(crate) struct SockOpts {
    pub sock_dom: AddressFamily,
    pub flags: Flags,
    pub options: Options,
    pub is_nonblock: bool,
}

pub(crate) fn sys_socketcall(request: UNotifyEventRequest) -> ScmpNotifResp {
    let req = request.scmpreq;

    // Determine socket subcall.
    let call: u8 = match req.data.args[0].try_into() {
        Ok(call) => call,
        Err(_) => return request.fail_syscall(Errno::EINVAL),
    };

    if HOOK_SCKCALLS.binary_search(&call).is_err() {
        // SAFETY: No pointer dereference in access check.
        return unsafe { request.continue_syscall() };
    }

    // RecvMmsg64 is synthetic.
    let subcall: SocketCall = match SocketCall::try_from(call) {
        Ok(SocketCall::RecvMmsg64) | Err(_) => return request.fail_syscall(Errno::EINVAL),
        Ok(subcall) => subcall,
    };

    // Determine system call arguments.
    // On x86 unsigned long is 4 bytes, and on s390x 8 bytes.
    let is32 = scmp_arch_bits(req.data.arch) == 32;
    let sizeof_ulong: usize = if is32 { 4 } else { 8 };

    const ARGLEN: usize = 6;
    let mut args = [0u64; ARGLEN];

    // Linux reads only required number of arguments.
    const NARGS: [u8; 21] = [
        0, 3, 3, 3, 2, 3, 3, 3, 4, 4, 4, 6, 6, 2, 5, 5, 3, 3, 4, 5, 4,
    ];
    let narg = match NARGS.get(usize::from(call)) {
        Some(&n) => usize::from(n),
        None => return request.fail_syscall(Errno::EINVAL),
    };

    #[expect(clippy::arithmetic_side_effects)]
    let bufsiz = sizeof_ulong * narg;

    match request.read_vec_all(req.data.args[1], bufsiz) {
        Ok(buf) => {
            for (i, chunk) in buf.chunks_exact(sizeof_ulong).enumerate() {
                match sizeof_ulong {
                    4 => match chunk.try_into() {
                        Ok(bytes) => args[i] = u64::from(u32::from_ne_bytes(bytes)),
                        Err(_) => return request.fail_syscall(Errno::EFAULT),
                    },
                    8 => match chunk.try_into() {
                        Ok(bytes) => args[i] = u64::from_ne_bytes(bytes),
                        Err(_) => return request.fail_syscall(Errno::EFAULT),
                    },
                    _ => {
                        // is32 check above ensures this branch is never reached.
                        unreachable!("BUG: Invalid sizeof unsigned long: {sizeof_ulong}!");
                    }
                }
            }
        }
        Err(errno) => return request.fail_syscall(errno),
    }

    syscall_network_handler(request, subcall, &args)
}

pub(crate) fn sys_socket(request: UNotifyEventRequest) -> ScmpNotifResp {
    let req = request.scmpreq;
    syscall_network_handler(request, SocketCall::Socket, &req.data.args)
}

pub(crate) fn sys_socketpair(request: UNotifyEventRequest) -> ScmpNotifResp {
    let req = request.scmpreq;
    syscall_network_handler(request, SocketCall::SocketPair, &req.data.args)
}

pub(crate) fn sys_bind(request: UNotifyEventRequest) -> ScmpNotifResp {
    let req = request.scmpreq;
    syscall_network_handler(request, SocketCall::Bind, &req.data.args)
}

pub(crate) fn sys_accept(request: UNotifyEventRequest) -> ScmpNotifResp {
    let req = request.scmpreq;
    syscall_network_handler(request, SocketCall::Accept, &req.data.args)
}

pub(crate) fn sys_accept4(request: UNotifyEventRequest) -> ScmpNotifResp {
    let req = request.scmpreq;
    syscall_network_handler(request, SocketCall::Accept4, &req.data.args)
}

pub(crate) fn sys_getpeername(request: UNotifyEventRequest) -> ScmpNotifResp {
    let req = request.scmpreq;
    syscall_network_handler(request, SocketCall::GetPeerName, &req.data.args)
}

pub(crate) fn sys_getsockname(request: UNotifyEventRequest) -> ScmpNotifResp {
    let req = request.scmpreq;
    syscall_network_handler(request, SocketCall::GetSockName, &req.data.args)
}

pub(crate) fn sys_getsockopt(request: UNotifyEventRequest) -> ScmpNotifResp {
    let req = request.scmpreq;
    syscall_network_handler(request, SocketCall::GetSockOpt, &req.data.args)
}

pub(crate) fn sys_connect(request: UNotifyEventRequest) -> ScmpNotifResp {
    let req = request.scmpreq;
    syscall_network_handler(request, SocketCall::Connect, &req.data.args)
}

pub(crate) fn sys_recvfrom(request: UNotifyEventRequest) -> ScmpNotifResp {
    let req = request.scmpreq;
    syscall_network_handler(request, SocketCall::RecvFrom, &req.data.args)
}

pub(crate) fn sys_recvmsg(request: UNotifyEventRequest) -> ScmpNotifResp {
    let req = request.scmpreq;
    syscall_network_handler(request, SocketCall::RecvMsg, &req.data.args)
}

pub(crate) fn sys_recvmmsg(request: UNotifyEventRequest) -> ScmpNotifResp {
    let req = request.scmpreq;
    syscall_network_handler(request, SocketCall::RecvMmsg, &req.data.args)
}

pub(crate) fn sys_recvmmsg64(request: UNotifyEventRequest) -> ScmpNotifResp {
    let req = request.scmpreq;
    // recvmmsg_time64 does not have a socketcall(2) equivalent,
    // therefore we use the dummy op `SocketCall::RecvMmsg64`.
    syscall_network_handler(request, SocketCall::RecvMmsg64, &req.data.args)
}

pub(crate) fn sys_sendto(request: UNotifyEventRequest) -> ScmpNotifResp {
    let req = request.scmpreq;
    syscall_network_handler(request, SocketCall::SendTo, &req.data.args)
}

pub(crate) fn sys_sendmsg(request: UNotifyEventRequest) -> ScmpNotifResp {
    let req = request.scmpreq;
    syscall_network_handler(request, SocketCall::SendMsg, &req.data.args)
}

pub(crate) fn sys_sendmmsg(request: UNotifyEventRequest) -> ScmpNotifResp {
    let req = request.scmpreq;
    syscall_network_handler(request, SocketCall::SendMmsg, &req.data.args)
}

// A helper function to handle network-related syscalls.
fn syscall_network_handler(
    request: UNotifyEventRequest,
    subcall: SocketCall,
    args: &[u64; 6],
) -> ScmpNotifResp {
    syscall_handler!(request, |request: UNotifyEventRequest| {
        let sandbox = request.get_sandbox();
        let flags = *sandbox.flags;
        let options = *sandbox.options;
        let allow_safe_bind = options.allow_safe_bind();
        let allow_unsafe_kcapi = options.allow_unsafe_kcapi();
        let allow_unsupp_socket = options.allow_unsupp_socket();
        let restrict_oob = !options.allow_unsafe_oob();
        let restrict_recvmsg = !options.allow_unsafe_recvmsg();
        let randomize_fds = flags.force_rand_fd();

        let cap = match subcall {
            SocketCall::Socket => {
                // a. socket system call.
                // b. socketcall -> socket indirection.
                let nlfam = sandbox.netlink_families;
                drop(sandbox); // release read lock.
                return handle_socket(&request, args, flags, options, nlfam);
            }
            SocketCall::SocketPair => {
                // a. socketpair system call.
                // b. socketcall -> socketpair indirection.
                // As of version 3.42.0, this is checked for bind
                // access with the dummy `!unnamed' path.
                return handle_socketpair(&request, sandbox, args, SocketCall::SocketPair);
            }
            SocketCall::RecvMsg | SocketCall::RecvMmsg | SocketCall::RecvMmsg64 if !restrict_recvmsg => {
                // SAFETY:
                // 1. This can only happen by socketcall(2) indirection.
                // 2. No pointer dereference in access check.
                return Ok(unsafe { request.continue_syscall() });
            }
            SocketCall::Accept | SocketCall::GetSockName | SocketCall::GetPeerName | SocketCall::Recv | SocketCall::RecvFrom | SocketCall::RecvMsg | SocketCall::Accept4 | SocketCall::RecvMmsg | SocketCall::RecvMmsg64 => {
                // accept, accept4, getsockname, getpeername:
                //
                // accept{,4} are IP blocklist only.
                // get{peer,sock}name are informational.
                // recv and recvfrom are informational.
                // recvmsg, recvmmsg, and recvmmsg_time64 are informational.
                Capability::empty()
            }
            SocketCall::Bind => Capability::CAP_NET_BIND,
            _ /* connect, send{,to,{m,}msg} */ => Capability::CAP_NET_CONNECT,
        };
        drop(sandbox); // release read lock before get-fd.

        // Get the file descriptor before access check as it may change
        // after which is a TOCTOU vector. This also allows us to early
        // return on invalid file descriptors without having to resort
        // to access()'ing /proc/$pid/fd/$fd which will return ENOENT
        // with /proc mounted as hidepid=2.
        let fd = request.get_fd(args[0] as RawFd)?;

        // Check status flags.
        //
        // Linux rejects O_PATH fds with EBADF.
        let status_flags = fd_status_flags(&fd)?;
        if status_flags.contains(OFlag::O_PATH) {
            return Err(Errno::EBADF);
        }
        let is_nonblock = status_flags.contains(OFlag::O_NONBLOCK);

        // Linux validates flags before socket type for accept4(2).
        #[expect(clippy::cast_possible_truncation)]
        if subcall == SocketCall::Accept4
            && (args[3] as libc::c_int) & !(libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK) != 0
        {
            return Err(Errno::EINVAL);
        }

        // Check if fd points to a socket or return ENOTSOCK.
        if file_type(&fd, None, false)? != FileType::Sock {
            return Err(Errno::ENOTSOCK);
        }

        // Check fd readiness for nonblocking socket calls.
        if is_nonblock {
            check_socket_ready(&fd, subcall)?;
        }

        // Lookup socket domain to be used in validation.
        let sock_dom = getsockdomain(&fd).map(AddressFamily::from_raw)?;

        let opts = SockOpts {
            sock_dom,
            flags,
            options,
            is_nonblock,
        };

        match subcall {
            SocketCall::Accept | SocketCall::Accept4 => {
                // accept{,4} uses a different data structure,
                // so we handle it in its own branch.
                return handle_accept(fd, &request, args, subcall, is_nonblock);
            }
            SocketCall::GetSockName => {
                // getsockname is used for informational purposes only.
                return handle_getsockname(fd, &request, args);
            }
            SocketCall::GetPeerName => {
                // getpeername is used for informational purposes only.
                return handle_getpeername(fd, &request, args);
            }
            SocketCall::Send => {
                // send: Connection mode socket.
                // This only happens via socketcall(2) multiplexer.
                // On 64-bit we do not hook into send(2).
                return handle_sendto(fd, &request, args, opts, None);
            }
            SocketCall::Recv => {
                // recv: Connection mode socket.
                // This only happens via socketcall(2) multiplexer.
                // On 64-bit we do not hook into recv(2).
                return handle_recv(fd, &request, args, restrict_oob, is_nonblock);
            }
            SocketCall::RecvFrom => {
                // recvfrom is used for informational purposes only.
                return handle_recvfrom(fd, &request, args, restrict_oob, is_nonblock);
            }
            SocketCall::RecvMsg => {
                // recvmsg is used for informational purposes only.
                return handle_recvmsg(fd, &request, args, opts);
            }
            SocketCall::RecvMmsg => {
                // recvmsg is used for informational purposes only.
                return handle_recvmmsg(fd, &request, args, opts);
            }
            SocketCall::RecvMmsg64 => {
                // recvmmsg_time64 is used for informational purposes only.
                return handle_recvmmsg64(fd, &request, args, opts);
            }
            SocketCall::GetSockOpt => {
                // getsockopt is used for informational purposes only.
                return handle_getsockopt(fd, &request, args, randomize_fds);
            }
            SocketCall::SendMsg => {
                // sendmsg uses a different data structure, so we handle it in its own branch.
                return handle_sendmsg(fd, &request, args, opts);
            }
            SocketCall::SendMmsg => {
                // sendmmsg uses a different data structure, so we handle it in its own branch.
                return handle_sendmmsg(fd, &request, args, opts);
            }
            _ => {} // fall through.
        }

        let idx = if subcall == SocketCall::SendTo { 4 } else { 1 };
        let addr_remote = args[idx];

        // Linux kernel truncates upper bits and rejects negative values.
        #[expect(clippy::arithmetic_side_effects)]
        #[expect(clippy::cast_possible_truncation)]
        #[expect(clippy::cast_sign_loss)]
        let addr_len = {
            let len = args[idx + 1] as libc::c_int;
            if len < 0 {
                return Err(Errno::EINVAL);
            }
            len as libc::socklen_t
        };

        if addr_len == 0 {
            if subcall == SocketCall::SendTo {
                // sendto: Connection mode socket.
                // Linux ignores addr with addr_len == 0.
                return handle_sendto(fd, &request, args, opts, None);
            } else {
                // Linux rejects short addresses with EINVAL.
                return Err(Errno::EINVAL);
            }
        } else if addr_remote == 0 {
            return Err(Errno::EFAULT);
        } // else we have a valid address to check for access.

        let sandbox = request.get_sandbox();
        let anyaddr = sandbox.flags.allow_unsafe_any_addr();
        let local_net = sandbox.flags.force_local_net();
        let argaddr = get_addr(&request, subcall, sock_dom, addr_remote, addr_len)?;
        let (mut addr, root) = canon_addr(&request, &sandbox, &argaddr, cap)?;
        match addr_family(&addr) {
            PF_UNIX => {
                // Check for access.
                sandbox_addr(&request, &sandbox, subcall, &addr, &root, cap)?;
            }
            PF_INET => {
                // Turn 0.0.0.0 into 127.0.0.1 unless trace/allow_unsafe_any_addr:1.
                // Turn all addresses to 127.0.0.1 if trace/force_local_net:1.
                if !anyaddr {
                    make_loaddr(subcall, &mut addr, local_net)?;
                }
                // Check for access.
                sandbox_addr(&request, &sandbox, subcall, &addr, &root, cap).map_err(|errno| {
                    if subcall == SocketCall::Bind && has_privileged_port_v4(&addr) {
                        Errno::EACCES
                    } else {
                        errno
                    }
                })?;
            }
            PF_INET6 => {
                // Turn :: into :1 unless trace/allow_unsafe_any_addr:1.
                // Turn all addresses to ::1 if trace/force_local_net:1.
                if !anyaddr {
                    make_lo6addr(subcall, &mut addr, local_net)?;
                }
                // Zero out sin6_scope_id unless trace/allow_unsafe_ipv6_scope:1.
                if !sandbox.flags.allow_unsafe_ipv6_scope() {
                    if let Some((scope_id, ip, port)) = clear_scope6(&mut addr) {
                        warn!("ctx": "net", "op": "zero_scope_id",
                            "sys": subcall.name(), "pid": request.scmpreq.pid().as_raw(),
                            "addr": format!("{ip}!{port}"), "scope_id": scope_id,
                            "msg": format!("zeroed sin6_scope_id={scope_id} on {ip}!{port}"),
                            "tip": "configure `trace/allow_unsafe_ipv6_scope:1'");
                    }
                }
                // Check for access.
                sandbox_addr(&request, &sandbox, subcall, &addr, &root, cap).map_err(|errno| {
                    if subcall == SocketCall::Bind && has_privileged_port_v6(&addr) {
                        Errno::EACCES
                    } else {
                        errno
                    }
                })?;
            }
            PF_UNSPEC => {
                // We do not check address for AF_UNSPEC:
                // Some protocol sockets (e.g., TCP sockets as well as
                // datagram sockets in the UNIX and Internet domains)
                // may dissolve the association by connecting to an
                // address with the sa_family member of sockaddr set to
                // AF_UNSPEC; thereafter, the socket can be connected to
                // another address. (AF_UNSPEC is supported since Linux
                // 2.2.)
            }
            PF_NETLINK => {
                // We do not check Netlink address for access.
                // We apply filtering on netlink families at socket level.
            }
            PF_ALG if allow_unsafe_kcapi && subcall == SocketCall::Bind => {
                // Admin requested access to KCAPI.
            }
            PF_ALG => {
                // a. Access to KCAPI is disabled by default.
                // b. Non-bind(2) call is not supported for AF_ALG socket.
                return Err(Errno::EOPNOTSUPP);
            }
            n if n >= PF_MAX => return Err(Errno::EAFNOSUPPORT),
            _ if !allow_unsupp_socket => return Err(Errno::EAFNOSUPPORT),
            _ => {} // fall-through to emulate, continue here is unsafe.
        };
        drop(sandbox); // release read lock.

        // Emulate syscall.
        match subcall {
            SocketCall::Bind => handle_bind(fd, (addr, argaddr), root, &request, allow_safe_bind),
            SocketCall::Connect => {
                handle_connect(fd, (addr, argaddr), &request, allow_safe_bind, is_nonblock)
            }
            SocketCall::SendTo => handle_sendto(fd, &request, args, opts, Some((addr, argaddr))),
            _ => unreachable!(),
        }
    })
}

fn get_addr(
    request: &UNotifyEventRequest,
    subcall: SocketCall,
    sock_dom: AddressFamily,
    addr_remote: u64,
    addr_len: libc::socklen_t,
) -> Result<SockaddrStorage, Errno> {
    // Return EINVAL on negative or zero addr_len.
    // Return EINVAL on addr_len greater than sizeof(sockaddr_storage).
    let addr_len: usize = addr_len.try_into().or(Err(Errno::EINVAL))?;
    if !(1..=size_of::<libc::sockaddr_storage>()).contains(&addr_len) {
        return Err(Errno::EINVAL);
    }

    // Read address from sandbox process memory.
    let buf = request.read_vec_all(addr_remote, addr_len)?;

    // Linux rejects UNIX address on non-UNIX socket before path lookup.
    // Match Linux's per-protocol errno ordering (length check before
    // family check) without entering canon_addr (commit 970f7d44f).
    #[expect(clippy::cast_possible_truncation)]
    if buf.len() >= size_of::<libc::sa_family_t>() {
        let addr_fam = u16::from_ne_bytes([buf[0], buf[1]]);
        if addr_fam == libc::AF_UNIX as u16 && sock_dom != AddressFamily::Unix {
            let min_len = match sock_dom {
                AddressFamily::Inet => size_of::<libc::sockaddr_in>(),
                AddressFamily::Inet6 => size_of::<libc::sockaddr_in6>(),
                _ => size_of::<libc::sa_family_t>(),
            };
            return if addr_len < min_len {
                Err(Errno::EINVAL)
            } else {
                Err(Errno::EAFNOSUPPORT)
            };
        }
    }

    // Quoting unix(7):
    // "If a bind(2) call specifies addrlen as `sizeof(sa_family_t)`, or
    // [...], then the socket is autobound to an abstract address".
    #[expect(clippy::cast_possible_truncation)]
    #[expect(clippy::disallowed_methods)]
    if addr_len == size_of::<libc::sa_family_t>() {
        let addr_fam = u16::from_ne_bytes([buf[0], buf[1]]);
        if subcall == SocketCall::Bind && addr_fam == libc::AF_UNIX as u16 {
            let addr = UnixAddr::new_unnamed();
            // SAFETY: UnixAddr::as_ptr()/len() are valid.
            return Ok(unsafe {
                SockaddrStorage::from_raw(addr.as_ptr().cast(), Some(addr.len()))
            }
            .unwrap());
        }
        if addr_fam != libc::AF_UNSPEC as u16 {
            return Err(Errno::EINVAL);
        }
        // AF_UNSPEC falls through.
    }

    // Validate address length.
    let addr = buf.as_ptr().cast();
    let addr_len = buf.len().try_into().or(Err(Errno::EINVAL))?;

    // Linux accepts RFC 2133 24-byte legacy size for sockaddr_in6.
    const SIN6_LEN_RFC2133: usize = 24;

    // SAFETY:
    // 1. addr and addr_len are from sandbox process memory.
    // 2. addr_len has been validated above.
    match unsafe { SockaddrStorage::from_raw(addr, Some(addr_len)) } {
        Some(addr)
            if addr.as_sockaddr_in().is_some()
                && (addr_len as usize) < size_of::<libc::sockaddr_in>() =>
        {
            Err(Errno::EINVAL)
        }
        Some(addr)
            if addr.as_sockaddr_in6().is_some() && (addr_len as usize) < SIN6_LEN_RFC2133 =>
        {
            Err(Errno::EINVAL)
        }
        Some(addr) => Ok(addr),
        None => Err(Errno::EINVAL),
    }
}

// Canonicalizes UNIX domain socket names.
// Returns address and directory.
// Directory is None for non-UNIX addresses.
fn canon_addr(
    request: &UNotifyEventRequest,
    sandbox: &SandboxGuard,
    addr: &SockaddrStorage,
    cap: Capability,
) -> Result<(SockaddrStorage, Option<CanonicalPath>), Errno> {
    #[expect(clippy::cast_possible_truncation)]
    if let Some(path) = addr.as_unix_addr().and_then(|a| a.path()) {
        // Check for chroot.
        if sandbox.is_chroot() {
            return Err(Errno::ENOENT);
        }

        // Path may have trailing nul-bytes. Truncate the path at the
        // first occurrence of a null byte This is _not_ an abstract
        // UNIX socket so it's safe.
        let path = path.as_os_str().as_bytes();
        let null = memchr::memchr(0, path).unwrap_or(path.len());
        let path = XPathBuf::from(&path[..null]);

        // For bind(2), the path must be missing or we return EADDRINUSE.
        // For connect family, the path must exist or we return ENOENT.
        let fsflags = if cap == Capability::CAP_NET_BIND {
            FsFlags::MISS_LAST
        } else {
            FsFlags::MUST_PATH
        };

        // Always resolve symlinks.
        // Ensure relative UNIX socket paths match process CWD.
        let pid = request.scmpreq.pid();
        let path = safe_canonicalize(
            pid,
            None,
            &path,
            fsflags,
            Some(request),
            Some(sandbox.deref()),
        )?;

        // bind(2) doesn't follow dangling symlinks.
        // Return EADDRINUSE if the socket already exists.
        if fsflags.missing() && path.typ.is_some() {
            return Err(Errno::EADDRINUSE);
        }

        let sun_path = if path.base().is_empty() {
            // We open a FD to the path and then use the proc path
            // /proc/thread-self/fd/$fd in address' path argument to
            // avoid symlink TOCTOU because connect and sendto(2) follow
            // symlinks in basename unlike bind(2).
            let mut pfd = XPathBuf::from("/proc/thread-self/fd");
            pfd.push_fd(path.dir().as_raw_fd());
            pfd.append_byte(0);
            pfd
        } else {
            // We split the address into directory and basename
            // regardless of UNIX_PATH_MAX as we are later going to use
            // the handler thread to mitigate the TOCTOU vector in the
            // basename of the UNIX socket address. This is only used
            // for bind() which does not resolve symbolic links in
            // basename. We add "./" for easier identification at
            // recvfrom(2) boundary which is for informational purposes
            // only.
            let mut base = XPathBuf::from("./");
            base.append_bytes(path.base().as_os_str().as_bytes());
            base.append_byte(0);
            base
        };

        // Create sockaddr_un struct.
        let mut sockaddr = libc::sockaddr_un {
            sun_family: libc::AF_UNIX as libc::sa_family_t,
            sun_path: [0; UNIX_PATH_MAX],
        };
        let socklen = sun_path.len();
        if socklen > UNIX_PATH_MAX {
            return Err(Errno::ENAMETOOLONG);
        }

        // SAFETY: Copy the bytes without overlapping regions.
        unsafe {
            std::ptr::copy_nonoverlapping(
                sun_path.as_ptr(),
                sockaddr.sun_path.as_mut_ptr().cast(),
                socklen,
            )
        };

        // Calculate the correct size of the sockaddr_un struct,
        // including the family and the path. The size is the offset of
        // the sun_path field plus the length of the path (including the
        // null terminator).
        #[expect(clippy::arithmetic_side_effects)]
        let size = size_of::<libc::sa_family_t>() + socklen;

        // SAFETY: sockaddr is a locally constructed valid sockaddr_un.
        let addr = unsafe {
            SockaddrStorage::from_raw(
                std::ptr::addr_of!(sockaddr) as *const _,
                Some(size as libc::socklen_t),
            )
        }
        .ok_or(Errno::EINVAL)?;

        Ok((addr, Some(path)))
    } else {
        // No need to canonicalize.
        Ok((*addr, None))
    }
}

// Check given address against sandbox policy.
pub(crate) fn sandbox_addr(
    request: &UNotifyEventRequest,
    sandbox: &SandboxGuard,
    subcall: SocketCall,
    addr: &SockaddrStorage,
    root: &Option<CanonicalPath>,
    caps: Capability,
) -> Result<(), Errno> {
    assert!(
        matches!(
            subcall,
            SocketCall::Bind
                | SocketCall::Connect
                | SocketCall::Accept
                | SocketCall::SendTo
                | SocketCall::SendMsg
                | SocketCall::Accept4
                | SocketCall::SendMmsg
        ),
        "BUG: sandbox_addr called with invalid socket subcall:{subcall:#x}, report a bug!"
    );

    match sockaddr_family(addr) {
        AddressFamily::Unix => sandbox_addr_unix(request, sandbox, subcall, addr, root, caps),
        AddressFamily::Inet | AddressFamily::Inet6 => {
            sandbox_addr_inet(request, sandbox, subcall, addr, caps)
        }
        _ => sandbox_addr_notsup(sandbox),
    }
}

// Check given UNIX address against sandbox policy.
#[expect(clippy::cognitive_complexity)]
pub(crate) fn sandbox_addr_unix(
    request: &UNotifyEventRequest,
    sandbox: &SandboxGuard,
    subcall: SocketCall,
    addr: &SockaddrStorage,
    root: &Option<CanonicalPath>,
    caps: Capability,
) -> Result<(), Errno> {
    assert!(
        matches!(
            subcall,
            SocketCall::Bind
                | SocketCall::Connect
                | SocketCall::SendTo
                | SocketCall::SendMsg
                | SocketCall::SendMmsg
        ),
        "BUG: sandbox_addr_unix called with invalid socket subcall:{subcall:#x}, report a bug!"
    );

    if sandbox.getcaps(caps).is_empty() {
        // Sandboxing is off.
        return Ok(());
    }

    let addr = addr.as_unix_addr().ok_or(Errno::EINVAL)?;
    let (path, abs) = match (addr.path(), addr.as_abstract()) {
        (Some(path), _) => match root {
            Some(path) => (Cow::Borrowed(path.abs()), false),
            None => {
                // Check for chroot.
                if sandbox.is_chroot() {
                    return Err(Errno::ENOENT);
                }

                let path = path.as_os_str().as_bytes();
                let null = memchr::memchr(0, path).unwrap_or(path.len());
                let p = XPathBuf::from(&path[..null]);
                (Cow::Owned(p), false)
            }
        },
        (_, Some(path)) => {
            // Prefix UNIX abstract sockets with `@' before access check.
            // Abstract socket names may contain embedded NUL bytes.
            let mut unix = XPathBuf::from("@");
            unix.append_bytes(path);
            (Cow::Owned(unix), true)
        }
        _ => {
            // Use dummy path `!unnamed' for unnamed UNIX sockets.
            (Cow::Borrowed(XPath::from_bytes(b"!unnamed")), true)
        }
    };

    // Check for access.
    let action = sandbox.check_unix(caps, &path);

    if action.is_logging() && log_enabled!(LogLevel::Warn) {
        let sys = subcall.name();
        if sandbox.log_scmp() {
            warn!("ctx": "access", "cap": caps, "act": action,
                "sys": sys, "unix": &path, "abs": abs,
                "tip": format!("configure `allow/{caps}+{path}'"),
                "req": request);
        } else {
            warn!("ctx": "access", "cap": caps, "act": action,
                "sys": sys, "unix": &path, "abs": abs,
                "tip": format!("configure `allow/{caps}+{path}'"),
                "pid": request.scmpreq.pid);
        }
    }

    match action {
        Action::Allow | Action::Warn => Ok(()),
        Action::Deny | Action::Filter => Err(subcall.into()),
        Action::Panic => panic!(),
        Action::Exit => std::process::exit(Errno::from(subcall) as i32),
        action => {
            // Stop|Kill
            let _ = request.kill(action);
            Err(subcall.into())
        }
    }
}

// Check given IPv4 or IPv6 address against sandbox policy.
#[expect(clippy::cognitive_complexity)]
pub(crate) fn sandbox_addr_inet(
    request: &UNotifyEventRequest,
    sandbox: &SandboxGuard,
    subcall: SocketCall,
    addr: &SockaddrStorage,
    caps: Capability,
) -> Result<(), Errno> {
    // accept(2) and accept4(2) are treated specially:
    // No ACL is done, only IP blocklist check.
    if matches!(subcall, SocketCall::Accept | SocketCall::Accept4) {
        assert!(
            caps.is_empty(),
            "BUG: sandbox_addr_inet called with socket subcall:{subcall:#x} and {caps}, report a bug!"
        );
    } else if matches!(
        subcall,
        SocketCall::Bind
            | SocketCall::Connect
            | SocketCall::SendTo
            | SocketCall::SendMsg
            | SocketCall::SendMmsg
    ) {
        assert!(
            !caps.is_empty(),
            "BUG: sandbox_addr_inet called with socket subcall:{subcall:#x} and without caps, report a bug!"
        );
    } else {
        unreachable!(
            "BUG: sandbox_addr_inet called with socket subcall:{subcall:#x}, report a bug!"
        );
    }

    if !caps.is_empty() && sandbox.getcaps(caps).is_empty() {
        // Sandboxing is off.
        return Ok(());
    }

    let (addr, port) = if let Some(sin) = addr.as_sockaddr_in() {
        (IpAddr::V4(sin.ip()), sin.port())
    } else if let Some(sa6) = addr.as_sockaddr_in6() {
        (sa6.ip().to_canonical(), sa6.port())
    } else {
        return Err(Errno::EINVAL);
    };

    // Check for access and IP blocklist as necessary.
    // caps.is_empty() implies accept{,4}(2) here.
    let action = sandbox.check_ip(caps, addr, port);

    if caps.is_empty() && action.is_logging() {
        // accept{,4}
        let ipv = if addr.is_ipv6() { 6 } else { 4 };
        let sys = subcall.name();
        if sandbox.log_scmp() {
            warn!("ctx": "block", "act": action,
                "sys": sys, "addr": format!("{addr}!{port}"), "ipv": ipv,
                "tip": format!("configure `block-{addr}'"),
                "req": request);
        } else {
            warn!("ctx": "block", "act": action,
                "sys": sys, "addr": format!("{addr}!{port}"), "ipv": ipv,
                "tip": format!("configure `block-{addr}'"),
                "pid": request.scmpreq.pid);
        }
    } else if action.is_logging() {
        // connect, sendto, send{m,}msg
        let ipv = if addr.is_ipv6() { 6 } else { 4 };
        let sys = subcall.name();
        if sandbox.log_scmp() {
            warn!("ctx": "access", "cap": caps, "act": action,
                "sys": sys, "addr": format!("{addr}!{port}"), "ipv": ipv,
                "tip": format!("configure `allow/{caps}+{addr}!{port}'"),
                "req": request);
        } else {
            warn!("ctx": "access", "cap": caps, "act": action,
                "sys": sys, "addr": format!("{addr}!{port}"), "ipv": ipv,
                "tip": format!("configure `allow/{caps}+{addr}!{port}'"),
                "pid": request.scmpreq.pid);
        }
    }

    match action {
        Action::Allow | Action::Warn => Ok(()),
        Action::Deny | Action::Filter => Err(subcall.into()),
        Action::Panic => panic!(),
        Action::Exit => std::process::exit(Errno::from(subcall) as i32),
        action => {
            // Stop|Kill
            let _ = request.kill(action);
            Err(subcall.into())
        }
    }
}

// Check unsupported address against sandbox policy.
pub(crate) fn sandbox_addr_notsup(sandbox: &SandboxGuard) -> Result<(), Errno> {
    if sandbox.options.allow_unsupp_socket() {
        Ok(())
    } else {
        Err(Errno::EAFNOSUPPORT)
    }
}

// Check unnamed socket against sandbox policy.
//
// Used at socketpair(2) boundary for AF_UNIX sockets.
#[expect(clippy::cognitive_complexity)]
pub(crate) fn sandbox_addr_unnamed(
    request: &UNotifyEventRequest,
    sandbox: &SandboxGuard,
    subcall: SocketCall,
) -> Result<(), Errno> {
    assert_eq!(
        subcall,
        SocketCall::SocketPair,
        "BUG: sandbox_addr_unnamed called with invalid socket subcall:{subcall:#x}, report a bug!"
    );

    // Check for access.
    let caps = Capability::CAP_NET_BIND;
    let name = XPath::from_bytes(b"!unnamed");

    if sandbox.getcaps(caps).is_empty() {
        // Sandboxing is off.
        return Ok(());
    }
    let action = sandbox.check_unix(caps, name);

    if action.is_logging() && log_enabled!(LogLevel::Warn) {
        let sys = subcall.name();
        if sandbox.log_scmp() {
            warn!("ctx": "access", "cap": caps, "act": action,
                "sys": sys, "unix": &name, "abs": true,
                "tip": format!("configure `allow/{caps}+{name}'"),
                "req": request);
        } else {
            warn!("ctx": "access", "cap": caps, "act": action,
                "sys": sys, "unix": &name, "abs": true,
                "tip": format!("configure `allow/{caps}+{name}'"),
                "pid": request.scmpreq.pid);
        }
    }

    match action {
        Action::Allow | Action::Warn => Ok(()),
        Action::Deny | Action::Filter => Err(subcall.into()),
        Action::Panic => panic!(),
        Action::Exit => std::process::exit(Errno::from(subcall) as i32),
        action => {
            // Stop|Kill
            let _ = request.kill(action);
            Err(subcall.into())
        }
    }
}

// Handle allow_safe_bind for connect.
pub(crate) fn handle_safe_bind<Fd: AsFd>(
    request: &UNotifyEventRequest,
    fd: Fd,
) -> Result<(), Errno> {
    let addr = getsockname::<SockaddrStorage>(fd.as_fd().as_raw_fd())?;

    let (addr, port) = if let Some(addr) = addr.as_sockaddr_in() {
        let port = addr.port();
        if port == 0 {
            return Ok(());
        }

        let addr = IpNet::new_assert(IpAddr::V4(addr.ip()), 32);

        // Allow implicit bind with safe_bind.
        (addr, port)
    } else if let Some(addr) = addr.as_sockaddr_in6() {
        let port = addr.port();
        if port == 0 {
            return Ok(());
        }

        let addr = addr.ip();
        let addr = if let Some(addr) = addr.to_ipv4_mapped() {
            IpNet::new_assert(IpAddr::V4(addr), 32)
        } else {
            IpNet::new_assert(IpAddr::V6(addr), 128)
        };

        // Allow implicit bind with safe_bind.
        (addr, port)
    } else {
        return Ok(());
    };

    // Configure sandbox:
    // Remove and re-add the address so repeated binds to the
    // same address cannot overflow the vector.
    let addr = AddressPattern {
        addr,
        port: port.into(),
    };
    info!("ctx": "connect", "op": "allow_safe_bind",
        "sys": "connect", "pid": request.scmpreq.pid().as_raw(), "rule": &addr,
        "msg": format!("add rule `allow/net/connect+{addr}' after connect"));

    let rule = CidrRule {
        act: Action::Allow,
        cap: Capability::CAP_NET_CONNECT,
        pat: addr,
    };

    let mut sandbox = request.get_mut_sandbox();
    match sandbox.cidr_rules.iter().position(|r| *r == rule) {
        Some(0) => {} // No need to re-add.
        Some(idx) => {
            sandbox.cidr_rules.remove(idx);
            sandbox.cidr_rules.push_front(rule)?;
        }
        None => sandbox.cidr_rules.push_front(rule)?,
    }

    Ok(())
}

// Handle allow_safe_bind for sendto, sendmsg.
pub(crate) fn handle_safe_bind2(
    request: &UNotifyEventRequest,
    subcall: SocketCall,
    addr: &SockaddrStorage,
    port: u16,
) -> Result<(), Errno> {
    let ip = if let Some(addr) = addr.as_sockaddr_in() {
        IpAddr::V4(addr.ip())
    } else if let Some(addr) = addr.as_sockaddr_in6() {
        IpAddr::V6(addr.ip())
    } else {
        return Err(Errno::EINVAL);
    };

    // Query source address using netlink.
    let ip = route_src(ip)?;
    let addr = match ip {
        IpAddr::V4(_) => IpNet::new_assert(ip, 32),
        IpAddr::V6(ip6) => match ip6.to_ipv4_mapped() {
            Some(ip4) => IpNet::new_assert(IpAddr::V4(ip4), 32),
            None => IpNet::new_assert(ip, 128),
        },
    };

    // Configure sandbox:
    // Remove and re-add the address so repeated binds to the
    // same address cannot overflow the vector.
    let addr = AddressPattern {
        addr,
        port: port.into(),
    };
    info!("ctx": "connect", "op": "allow_safe_bind",
        "sys": subcall, "pid": request.scmpreq.pid().as_raw(), "rule": &addr,
        "msg": format!("add rule `allow/net/connect+{addr}' after {subcall}"));

    let rule = CidrRule {
        act: Action::Allow,
        cap: Capability::CAP_NET_CONNECT,
        pat: addr,
    };

    let mut sandbox = request.get_mut_sandbox();
    match sandbox.cidr_rules.iter().position(|r| *r == rule) {
        Some(0) => {} // No need to re-add.
        Some(idx) => {
            sandbox.cidr_rules.remove(idx);
            sandbox.cidr_rules.push_front(rule)?;
        }
        None => sandbox.cidr_rules.push_front(rule)?,
    }

    Ok(())
}

// Handle allow_safe_bind for sendmmsg on AF_INET sockets.
pub(crate) fn handle_safe_bind3_v4<'a, I>(
    request: &UNotifyEventRequest,
    port: u16,
    dsts: I,
) -> Result<(), Errno>
where
    I: Iterator<Item = &'a SockaddrStorage>,
{
    let nl = route_open()?;
    let mut ip_set = IpRange::<Ipv4Net>::new();
    let mut sandbox = request.get_mut_sandbox();

    for dst in dsts {
        let ip = match dst.as_sockaddr_in() {
            Some(addr) => addr.ip(),
            None => continue,
        };

        // Continue if address was seen.
        if ip_set.contains(&ip) {
            continue;
        }
        ip_set.add(Ipv4Net::new_assert(ip, 32));

        // Query source address using netlink.
        let src_ip = match route_query_src(&nl, IpAddr::V4(ip)) {
            Ok(ip) => ip,
            Err(_) => continue,
        };

        // Configure sandbox:
        // Remove and re-add the address so repeated binds to the
        // same address cannot overflow the vector.
        let addr = IpNet::new_assert(src_ip, 32);
        let addr = AddressPattern {
            addr,
            port: port.into(),
        };
        info!("ctx": "connect", "op": "allow_safe_bind",
            "sys": "sendmmsg", "pid": request.scmpreq.pid().as_raw(),
            "rule": &addr,
            "msg": format!("add rule `allow/net/connect+{addr}' after sendmmsg"));

        let rule = CidrRule {
            act: Action::Allow,
            cap: Capability::CAP_NET_CONNECT,
            pat: addr,
        };

        match sandbox.cidr_rules.iter().position(|r| *r == rule) {
            Some(0) => {} // No need to re-add.
            Some(idx) => {
                sandbox.cidr_rules.remove(idx);
                sandbox.cidr_rules.push_front(rule)?;
            }
            None => sandbox.cidr_rules.push_front(rule)?,
        }
    }

    Ok(())
}

// Handle allow_safe_bind for sendmmsg on AF_INET6 sockets.
#[expect(clippy::cognitive_complexity)]
pub(crate) fn handle_safe_bind3_v6<'a, I>(
    request: &UNotifyEventRequest,
    port: u16,
    dsts: I,
) -> Result<(), Errno>
where
    I: Iterator<Item = &'a SockaddrStorage>,
{
    let nl = route_open()?;
    let mut ip_set = IpRange::<Ipv6Net>::new();
    let mut sandbox = request.get_mut_sandbox();

    for dst in dsts {
        let ip = match dst.as_sockaddr_in6() {
            Some(addr) => addr.ip(),
            None => continue,
        };

        // Continue if address was seen.
        if ip_set.contains(&ip) {
            continue;
        }
        ip_set.add(Ipv6Net::new_assert(ip, 128));

        // Query source address using netlink.
        let src_ip = match route_query_src(&nl, IpAddr::V6(ip)) {
            Ok(ip) => ip,
            Err(_) => continue,
        };

        // Configure sandbox:
        // Remove and re-add the address so repeated binds to the
        // same address cannot overflow the vector.
        let addr = match src_ip {
            IpAddr::V4(_) => IpNet::new_assert(src_ip, 32),
            IpAddr::V6(ip6) => match ip6.to_ipv4_mapped() {
                Some(ip4) => IpNet::new_assert(IpAddr::V4(ip4), 32),
                None => IpNet::new_assert(src_ip, 128),
            },
        };

        let addr = AddressPattern {
            addr,
            port: port.into(),
        };
        info!("ctx": "connect", "op": "allow_safe_bind",
            "sys": "sendmmsg", "pid": request.scmpreq.pid().as_raw(),
            "rule": &addr,
            "msg": format!("add rule `allow/net/connect+{addr}' after sendmmsg"));

        let rule = CidrRule {
            act: Action::Allow,
            cap: Capability::CAP_NET_CONNECT,
            pat: addr,
        };

        match sandbox.cidr_rules.iter().position(|r| *r == rule) {
            Some(0) => {} // No need to re-add.
            Some(idx) => {
                sandbox.cidr_rules.remove(idx);
                sandbox.cidr_rules.push_front(rule)?;
            }
            None => sandbox.cidr_rules.push_front(rule)?,
        }
    }

    Ok(())
}

pub(crate) fn get_port<Fd: AsFd>(fd: Fd) -> Result<u16, Errno> {
    let addr = getsockname::<SockaddrStorage>(fd.as_fd().as_raw_fd())?;
    if let Some(addr) = addr.as_sockaddr_in() {
        Ok(addr.port())
    } else if let Some(addr) = addr.as_sockaddr_in6() {
        Ok(addr.port())
    } else {
        Err(Errno::EINVAL)
    }
}

// Truncate msg_flags to 32 bits and retain unknown flags.
pub(crate) fn to_msgflags(arg: u64) -> MsgFlags {
    #[expect(clippy::cast_possible_truncation)]
    MsgFlags::from_bits_retain(arg as libc::c_int)
}

fn check_socket_ready<Fd: AsFd>(fd: Fd, subcall: SocketCall) -> Result<(), Errno> {
    match subcall {
        SocketCall::Accept
        | SocketCall::Accept4
        | SocketCall::Recv
        | SocketCall::RecvFrom
        | SocketCall::RecvMsg
        | SocketCall::RecvMmsg
        | SocketCall::RecvMmsg64
            if !is_readable(&fd)? =>
        {
            Err(Errno::EAGAIN)
        }
        SocketCall::Send | SocketCall::SendTo | SocketCall::SendMsg | SocketCall::SendMmsg
            if !is_writable(&fd)? =>
        {
            Err(Errno::EAGAIN)
        }
        _ => Ok(()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_to_msgflags_zero_1() {
        let flags = to_msgflags(0);
        assert!(flags.is_empty());
    }

    #[test]
    fn test_to_msgflags_oob_1() {
        let flags = to_msgflags(libc::MSG_OOB as u64);
        assert!(flags.contains(MsgFlags::MSG_OOB));
    }

    #[test]
    fn test_to_msgflags_peek_1() {
        let flags = to_msgflags(libc::MSG_PEEK as u64);
        assert!(flags.contains(MsgFlags::MSG_PEEK));
    }

    #[test]
    fn test_to_msgflags_trunc_1() {
        let flags = to_msgflags(libc::MSG_TRUNC as u64);
        assert!(flags.contains(MsgFlags::MSG_TRUNC));
    }

    #[test]
    fn test_to_msgflags_truncates_high_bits_1() {
        // High bits beyond 32 bits should be truncated.
        let high_bits: u64 = 0x1_0000_0000;
        let flags = to_msgflags(high_bits);
        assert!(flags.is_empty());
    }

    #[test]
    fn test_to_msgflags_retains_unknown_bits_1() {
        // Unknown bits are retained via from_bits_retain.
        let unknown: u64 = 0x8000_0000;
        let flags = to_msgflags(unknown);
        assert_eq!(flags.bits(), unknown as i32);
    }
}