nlink 0.25.0

Async netlink library for Linux network configuration
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
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
//! Network namespace utilities.
//!
//! This module provides utilities for working with Linux network namespaces,
//! including executing operations in specific namespaces and managing namespace
//! file descriptors.
//!
//! [`create`]/[`delete`] persist a netns at the `ip netns` convention
//! `/var/run/netns/<name>`. [`create_path`]/[`delete_path`] persist it at any
//! caller-chosen path, so an application can own its netns directory (clearer
//! ownership, no collisions with operator `ip netns add`).
//!
//! # Example
//!
//! ```ignore
//! use nlink::netlink::namespace;
//! use nlink::netlink::{Connection, Route, Generic};
//!
//! // Get a Route connection for a named namespace
//! let conn: Connection<Route> = namespace::connection_for("myns")?;
//! let links = conn.get_links().await?;
//!
//! // Or a Generic connection for WireGuard in a namespace
//! let conn: Connection<Generic> = namespace::connection_for("myns")?;
//!
//! // Or use a path directly
//! let conn: Connection<Route> = namespace::connection_for_path("/proc/1234/ns/net")?;
//!
//! // Or use NamespaceSpec for a unified API
//! use nlink::netlink::namespace::NamespaceSpec;
//!
//! let spec = NamespaceSpec::Named("myns");
//! let conn: Connection<Route> = spec.connection()?;
//! ```

use std::{
    fs::File,
    os::unix::{ffi::OsStrExt, io::{AsRawFd, RawFd}},
    path::{Path, PathBuf},
};

use super::{
    connection::Connection,
    error::{Error, Result},
    protocol::{
        construction::{AsyncConstructible, SyncConstructible},
        AsyncProtocolInit, ProtocolState,
    },
    socket::NetlinkSocket,
};

/// Specification for which network namespace to use.
///
/// This enum provides a unified way to specify a network namespace,
/// whether it's the default namespace, a named namespace, a path,
/// or a process's namespace.
///
/// # Example
///
/// ```ignore
/// use nlink::netlink::{Connection, Route};
/// use nlink::netlink::namespace::NamespaceSpec;
///
/// // Different ways to specify a namespace
/// let default = NamespaceSpec::Default;
/// let named = NamespaceSpec::Named("myns");
/// let by_path = NamespaceSpec::Path(Path::new("/proc/1234/ns/net"));
/// let by_pid = NamespaceSpec::Pid(1234);
///
/// // Create connections (generic over protocol type)
/// let conn: Connection<Route> = named.connection()?;
/// ```
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum NamespaceSpec<'a> {
    /// Use the current/default namespace.
    Default,
    /// Use a named namespace (from /var/run/netns/).
    Named(&'a str),
    /// Use a namespace specified by path.
    Path(&'a Path),
    /// Use a process's namespace by PID.
    Pid(u32),
}

impl<'a> NamespaceSpec<'a> {
    /// Create a connection for this namespace specification.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use nlink::netlink::namespace::NamespaceSpec;
    /// use nlink::netlink::protocol::Route;
    ///
    /// let spec = NamespaceSpec::Named("myns");
    /// let conn: Connection<Route> = spec.connection()?;
    /// let links = conn.get_links().await?;
    /// ```
    pub fn connection<P: ProtocolState + Default + SyncConstructible>(&self) -> Result<Connection<P>> {
        match self {
            NamespaceSpec::Default => Connection::<P>::new(),
            NamespaceSpec::Named(name) => connection_for(name),
            NamespaceSpec::Path(path) => connection_for_path(path),
            NamespaceSpec::Pid(pid) => connection_for_pid(*pid),
        }
    }

    /// Create an async-initialized connection (GENL families that
    /// need family-ID resolution — WireGuard, MACsec, …) for this
    /// namespace specification. Async counterpart of
    /// [`connection`](Self::connection) (#169).
    pub async fn connection_async<P: AsyncProtocolInit + AsyncConstructible>(
        &self,
    ) -> Result<Connection<P>> {
        match self {
            NamespaceSpec::Default => Connection::<P>::new_async().await,
            NamespaceSpec::Named(name) => connection_for_async(name).await,
            NamespaceSpec::Path(path) => connection_for_path_async(path).await,
            NamespaceSpec::Pid(pid) => connection_for_pid_async(*pid).await,
        }
    }

    /// Check if this refers to the default namespace.
    #[inline]
    pub fn is_default(&self) -> bool {
        matches!(self, NamespaceSpec::Default)
    }

    /// Spawn a process in this namespace.
    ///
    /// For [`NamespaceSpec::Default`], the command is spawned normally without
    /// any namespace switching.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use nlink::netlink::namespace::NamespaceSpec;
    /// use std::process::Command;
    ///
    /// let spec = NamespaceSpec::Named("myns");
    /// let mut child = spec.spawn(Command::new("ip").arg("link"))?;
    /// child.wait()?;
    /// ```
    pub fn spawn(&self, cmd: std::process::Command) -> Result<std::process::Child> {
        match self {
            NamespaceSpec::Default => {
                let mut cmd = cmd;
                cmd.spawn().map_err(Error::Io)
            }
            NamespaceSpec::Named(name) => spawn(name, cmd),
            NamespaceSpec::Path(path) => spawn_path(path, cmd),
            NamespaceSpec::Pid(pid) => {
                let path = format!("/proc/{}/ns/net", pid);
                spawn_path(&path, cmd)
            }
        }
    }

    /// Spawn a process and collect its output in this namespace.
    ///
    /// See [`spawn_output`] for details.
    pub fn spawn_output(&self, cmd: std::process::Command) -> Result<std::process::Output> {
        match self {
            NamespaceSpec::Default => {
                let mut cmd = cmd;
                cmd.stdout(std::process::Stdio::piped());
                cmd.stderr(std::process::Stdio::piped());
                let child = cmd.spawn().map_err(Error::Io)?;
                child.wait_with_output().map_err(Error::Io)
            }
            NamespaceSpec::Named(name) => spawn_output(name, cmd),
            NamespaceSpec::Path(path) => spawn_output_path(path, cmd),
            NamespaceSpec::Pid(pid) => {
                let path = format!("/proc/{}/ns/net", pid);
                spawn_output_path(&path, cmd)
            }
        }
    }

    /// Spawn a process with `/etc/netns/` file overlays.
    ///
    /// See [`spawn_with_etc`] for details. For [`NamespaceSpec::Path`] and
    /// [`NamespaceSpec::Pid`], falls back to regular [`spawn_path`] (no overlay).
    pub fn spawn_with_etc(&self, cmd: std::process::Command) -> Result<std::process::Child> {
        match self {
            NamespaceSpec::Default => {
                let mut cmd = cmd;
                cmd.spawn().map_err(Error::Io)
            }
            NamespaceSpec::Named(name) => spawn_with_etc(name, cmd),
            NamespaceSpec::Path(path) => spawn_path(path, cmd),
            NamespaceSpec::Pid(pid) => {
                let path = format!("/proc/{}/ns/net", pid);
                spawn_path(&path, cmd)
            }
        }
    }

    /// Spawn a process and collect its output with `/etc/netns/` file overlays.
    ///
    /// See [`spawn_with_etc`] for details. For [`NamespaceSpec::Path`] and
    /// [`NamespaceSpec::Pid`], falls back to regular [`spawn_output_path`] (no overlay).
    pub fn spawn_output_with_etc(
        &self,
        cmd: std::process::Command,
    ) -> Result<std::process::Output> {
        match self {
            NamespaceSpec::Default => {
                let mut cmd = cmd;
                cmd.stdout(std::process::Stdio::piped());
                cmd.stderr(std::process::Stdio::piped());
                let child = cmd.spawn().map_err(Error::Io)?;
                child.wait_with_output().map_err(Error::Io)
            }
            NamespaceSpec::Named(name) => spawn_output_with_etc(name, cmd),
            NamespaceSpec::Path(path) => spawn_output_path(path, cmd),
            NamespaceSpec::Pid(pid) => {
                let path = format!("/proc/{}/ns/net", pid);
                spawn_output_path(&path, cmd)
            }
        }
    }
}

/// The runtime directory where named network namespaces are stored.
pub const NETNS_RUN_DIR: &str = "/var/run/netns";

/// Get a connection for a named network namespace.
///
/// Named namespaces are those created via `ip netns add <name>` and stored
/// in `/var/run/netns/`.
///
/// # Example
///
/// ```ignore
/// use nlink::netlink::namespace;
/// use nlink::netlink::protocol::Route;
///
/// // Create a connection to work in the "production" namespace
/// let conn: Connection<Route> = namespace::connection_for("production")?;
/// let links = conn.get_links().await?;
/// ```
pub fn connection_for<P: ProtocolState + Default + SyncConstructible>(name: &str) -> Result<Connection<P>> {
    let path = PathBuf::from(NETNS_RUN_DIR).join(name);
    connection_for_path(&path)
}

/// Get a connection for a network namespace specified by path.
///
/// This works with any namespace file path, including:
/// - Named namespaces: `/var/run/netns/<name>`
/// - Process namespaces: `/proc/<pid>/ns/net`
/// - Container namespaces: `/proc/<container_init_pid>/ns/net`
///
/// # Example
///
/// ```ignore
/// use nlink::netlink::namespace;
/// use nlink::netlink::protocol::Route;
///
/// // For a container's namespace
/// let conn: Connection<Route> = namespace::connection_for_path("/proc/1234/ns/net")?;
/// let links = conn.get_links().await?;
/// ```
pub fn connection_for_path<P: ProtocolState + Default + SyncConstructible, T: AsRef<Path>>(
    path: T,
) -> Result<Connection<P>> {
    Connection::<P>::new_in_namespace_path(path)
}

/// Get a connection for a process's network namespace.
///
/// # Example
///
/// ```ignore
/// use nlink::netlink::namespace;
/// use nlink::netlink::protocol::Route;
///
/// // Get interfaces visible to process 1234
/// let conn: Connection<Route> = namespace::connection_for_pid(1234)?;
/// let links = conn.get_links().await?;
/// ```
pub fn connection_for_pid<P: ProtocolState + Default + SyncConstructible>(pid: u32) -> Result<Connection<P>> {
    let path = format!("/proc/{}/ns/net", pid);
    connection_for_path(&path)
}

/// Get an async-initialized connection for a named network namespace.
///
/// This is for GENL protocols (WireGuard, MACsec, MPTCP, Ethtool, nl80211, Devlink)
/// that need async family ID resolution after socket creation. The socket is created
/// in the target namespace, then the GENL family is resolved through that socket.
///
/// # Example
///
/// ```ignore
/// use nlink::netlink::{Connection, Wireguard, namespace};
///
/// let conn: Connection<Wireguard> = namespace::connection_for_async("myns").await?;
/// let device = conn.get_device("wg0").await?;
/// ```
pub async fn connection_for_async<P: AsyncProtocolInit + AsyncConstructible>(name: &str) -> Result<Connection<P>> {
    let path = PathBuf::from(NETNS_RUN_DIR).join(name);
    connection_for_path_async(&path).await
}

/// Get an async-initialized connection for a namespace specified by path.
///
/// See [`connection_for_async`] for details.
pub async fn connection_for_path_async<P: AsyncProtocolInit + AsyncConstructible, T: AsRef<Path>>(
    path: T,
) -> Result<Connection<P>> {
    let socket = NetlinkSocket::new_in_namespace_path(P::PROTOCOL, path)?;
    let state = P::resolve_async(&socket).await?;
    Ok(Connection::from_parts(socket, state))
}

/// Get an async-initialized connection for a process's network namespace.
///
/// See [`connection_for_async`] for details.
pub async fn connection_for_pid_async<P: AsyncProtocolInit + AsyncConstructible>(pid: u32) -> Result<Connection<P>> {
    let path = format!("/proc/{}/ns/net", pid);
    connection_for_path_async(&path).await
}

/// Open a namespace file and return its file descriptor.
///
/// The returned `NamespaceFd` keeps the file open and can be used with
/// [`Connection::new_in_namespace`] or [`enter`].
///
/// # Example
///
/// ```ignore
/// use nlink::netlink::namespace;
/// use nlink::netlink::{Connection, Protocol};
///
/// let ns = namespace::open("myns")?;
/// let conn = Connection::new_in_namespace(Protocol::Route, ns.as_raw_fd())?;
/// ```
pub fn open(name: &str) -> Result<NamespaceFd> {
    let path = PathBuf::from(NETNS_RUN_DIR).join(name);
    open_path(&path)
}

/// Map a failed open of a namespace path to a classifiable error (#184):
/// ENOENT becomes `Error::NamespaceNotFound` — matching `is_not_found()`
/// and carrying the path in `name`, the same shape [`delete_path`] uses —
/// and everything else passes through as `Error::Io`, preserving the raw
/// errno so `is_permission_denied()` & co. keep working. Never wrap these
/// opens in stringly `InvalidMessage`: it defeats every recovery predicate.
pub(crate) fn namespace_open_error(path: &Path, e: std::io::Error) -> Error {
    if e.kind() == std::io::ErrorKind::NotFound {
        Error::NamespaceNotFound {
            name: path.display().to_string(),
        }
    } else {
        Error::Io(e)
    }
}

/// Open a namespace file by path and return its file descriptor.
///
/// # Errors
///
/// Returns [`Error::NamespaceNotFound`] if the path doesn't exist
/// (matchable via [`Error::is_not_found`]); other open failures surface
/// as [`Error::Io`] with their errno intact (e.g. for
/// [`Error::is_permission_denied`]).
pub fn open_path<P: AsRef<Path>>(path: P) -> Result<NamespaceFd> {
    let file =
        File::open(path.as_ref()).map_err(|e| namespace_open_error(path.as_ref(), e))?;
    Ok(NamespaceFd { file })
}

/// Open a process's namespace and return its file descriptor.
pub fn open_pid(pid: u32) -> Result<NamespaceFd> {
    let path = format!("/proc/{}/ns/net", pid);
    open_path(&path)
}

/// A handle to an open namespace file.
///
/// This keeps the namespace file open so it can be used multiple times
/// with [`Connection::new_in_namespace`].
#[derive(Debug)]
pub struct NamespaceFd {
    file: File,
}

impl NamespaceFd {
    /// Get the raw file descriptor.
    pub fn as_raw_fd(&self) -> RawFd {
        self.file.as_raw_fd()
    }
}

impl AsRawFd for NamespaceFd {
    fn as_raw_fd(&self) -> RawFd {
        self.file.as_raw_fd()
    }
}

/// Enter a network namespace temporarily.
///
/// This function switches the current thread to the specified network namespace.
/// Use [`NamespaceGuard::restore`] or drop the guard to return to the original namespace.
///
/// # Warning
///
/// This affects the entire thread. In async contexts, prefer using
/// [`connection_for`] or [`Connection::new_in_namespace_path`] instead,
/// which create a socket in the namespace without affecting the thread.
///
/// If the guard's restore fails (`setns` back errors), the calling thread
/// stays in the target namespace — on a tokio worker that silently poisons
/// every task later scheduled there. The guard is `!Send`, so it cannot
/// leave the entering thread, but the restore-failure hazard is inherent
/// to switching a shared thread; APIs that need a namespace only briefly
/// should follow the dedicated-worker-thread pattern instead (see
/// [`get_sysctl`] and `NetlinkSocket::new_in_namespace`, #185).
///
/// # Example
///
/// ```ignore
/// use nlink::netlink::namespace;
///
/// let guard = namespace::enter("myns")?;
/// // Now in "myns" namespace
/// // ... do something ...
/// guard.restore()?;  // Or just drop it
/// ```
pub fn enter(name: &str) -> Result<NamespaceGuard> {
    let path = PathBuf::from(NETNS_RUN_DIR).join(name);
    enter_path(&path)
}

/// Enter a network namespace by path.
///
/// # Errors
///
/// Returns [`Error::NamespaceNotFound`] if the path doesn't exist; other
/// failures (open or `setns`) surface as [`Error::Io`] with errno intact.
pub fn enter_path<P: AsRef<Path>>(path: P) -> Result<NamespaceGuard> {
    // Save the current namespace
    let original = File::open("/proc/thread-self/ns/net")
        .map_err(|e| Error::InvalidMessage(format!("cannot open current namespace: {}", e)))?;

    // Open and enter the target namespace
    let target =
        File::open(path.as_ref()).map_err(|e| namespace_open_error(path.as_ref(), e))?;

    // SAFETY: libc::setns is a standard Linux syscall for switching namespaces.
    // target.as_raw_fd() is a valid fd to a namespace file, CLONE_NEWNET
    // specifies we're switching the network namespace.
    let ret = unsafe { libc::setns(target.as_raw_fd(), libc::CLONE_NEWNET) };
    if ret < 0 {
        return Err(Error::Io(std::io::Error::last_os_error()));
    }

    Ok(NamespaceGuard {
        original: Some(original),
        _thread_pinned: std::marker::PhantomData,
    })
}

/// A guard that restores the original namespace when dropped.
///
/// The guard is `!Send` (#185): namespace membership is **per-thread**, so a
/// guard dropped on a different thread than the one that called [`enter`]
/// would `setns` the wrong thread — switching that thread's namespace while
/// leaving the entering thread stuck in the target. Moving the guard across
/// threads (including holding it across an `.await` in a multi-threaded
/// runtime, which requires the future — and thus the guard — to be `Send`)
/// is therefore a compile error:
///
/// ```compile_fail
/// fn assert_send<T: Send>(_: T) {}
/// let guard = nlink::netlink::namespace::enter("myns").unwrap();
/// assert_send(guard); // NamespaceGuard is deliberately !Send
/// ```
#[derive(Debug)]
pub struct NamespaceGuard {
    /// `Some` while the guard is armed; [`Self::restore`] takes it out so
    /// `Drop` doesn't run a second, redundant restore after an explicit one.
    original: Option<File>,
    /// `*mut ()` is `!Send + !Sync`, pinning the guard to the entering thread.
    _thread_pinned: std::marker::PhantomData<*mut ()>,
}

impl NamespaceGuard {
    /// Restore the original namespace explicitly.
    ///
    /// This is called automatically on drop, but calling it explicitly
    /// allows you to handle errors. After this call the guard is disarmed:
    /// `Drop` will not attempt a second restore.
    pub fn restore(mut self) -> Result<()> {
        let result = self.do_restore();
        // Disarm: Drop must not re-run the restore the explicit call just
        // performed (pre-#185 it did, harmlessly but redundantly — and a
        // failed explicit restore also fired a second attempt + error log).
        self.original = None;
        result
    }

    fn do_restore(&self) -> Result<()> {
        let Some(original) = &self.original else {
            return Ok(());
        };
        // SAFETY: libc::setns restores the original namespace. The fd is valid
        // (opened from /proc/thread-self/ns/net when the guard was created).
        let ret = unsafe { libc::setns(original.as_raw_fd(), libc::CLONE_NEWNET) };
        if ret < 0 {
            return Err(Error::Io(std::io::Error::last_os_error()));
        }
        Ok(())
    }
}

impl Drop for NamespaceGuard {
    fn drop(&mut self) {
        if self.original.is_none() {
            return; // explicitly restored already
        }
        if let Err(e) = self.do_restore() {
            // We cannot return an error from Drop. Emit a structured
            // tracing event so observers see the failure (replaces the
            // pre-0.16.0 `eprintln!` — consistent with the broader
            // eprintln→tracing audit in Plan 147 §9.2). Callers that
            // need explicit detection should restore the namespace via
            // an explicit call before dropping the guard.
            tracing::error!(
                error = %e,
                "NamespaceGuard::drop: failed to restore original namespace; thread may be stuck"
            );
        }
    }
}

/// Check if a named namespace exists.
///
/// # Example
///
/// ```ignore
/// use nlink::netlink::{Connection, Route, namespace};
///
/// if namespace::exists("myns") {
///     let conn: Connection<Route> = namespace::connection_for("myns")?;
///     // ...
/// }
/// ```
pub fn exists(name: &str) -> bool {
    let path = PathBuf::from(NETNS_RUN_DIR).join(name);
    path.exists()
}

/// Convert a filesystem path to a `CString`, preserving its exact bytes.
/// Linux paths aren't necessarily UTF-8, so this goes through `OsStr` bytes
/// rather than `to_string_lossy` (which would mangle non-UTF-8 paths into a
/// different path than the one on disk). Errors only on an interior NUL.
fn path_to_cstring(path: &Path) -> Result<std::ffi::CString> {
    std::ffi::CString::new(path.as_os_str().as_bytes())
        .map_err(|_| Error::InvalidMessage(format!("invalid namespace path '{}'", path.display())))
}

/// `nsfs` superblock magic (`NSFS_MAGIC` from `<linux/magic.h>` — ASCII
/// "nsfs"). Backs `/proc/<pid>/ns/*` and bind-mounts of them. Not exported by
/// the `libc` crate, so defined here. Compared as `u64`: `statfs.f_type`
/// varies in type across libc/arch (`__fsword_t` on glibc x86_64, `c_ulong`
/// on musl, `c_uint` on s390x), so we widen at the comparison rather than pin
/// a type the field doesn't always have.
const NSFS_MAGIC: u64 = 0x6e_73_66_73;

/// Return `true` if `path` is a *live* network-namespace bind-mount.
///
/// A persistent netns (see [`create_path`]) is a bind-mount of an `nsfs` inode
/// onto a marker file. After an unclean shutdown the marker can linger as an
/// ordinary file with the bind-mount gone — present on disk but no longer a
/// namespace. This distinguishes the two via `statfs(2)`: a live netns
/// bind-mount sits on the `nsfs` pseudo-filesystem; a stale marker sits on
/// whatever backs its parent directory (typically `tmpfs`).
///
/// Returns `false` (never errors) when the path is absent, unreadable, or
/// backed by any non-`nsfs` filesystem, mirroring [`exists`].
///
/// `/proc/mounts` is deliberately **not** consulted: mount-namespace
/// propagation can hide a working bind-mount from it. `statfs` reflects the
/// actual backing filesystem regardless of propagation.
///
/// **Caveat**: `NSFS_MAGIC` identifies the nsfs filesystem, not the
/// namespace *type* — a bind-mount of any namespace (PID, mount, UTS, …)
/// also returns `true` (as does e.g. `/proc/self/ns/pid`). Distinguishing
/// types would need `ioctl(NS_GET_NSTYPE)`; for the stale-marker workflow
/// this predicate exists for, the distinction doesn't arise.
pub fn is_namespace_path<P: AsRef<Path>>(path: P) -> bool {
    let Ok(c_path) = path_to_cstring(path.as_ref()) else {
        return false; // interior NUL — cannot be a real path
    };
    // SAFETY: `c_path` outlives the call, so the path pointer stays valid;
    // `f_type` is read only when `rc == 0`.
    let mut buf: libc::statfs = unsafe { std::mem::zeroed() };
    let rc = unsafe { libc::statfs(c_path.as_ptr(), &mut buf) };
    rc == 0 && buf.f_type as u64 == NSFS_MAGIC
}

/// Named-namespace counterpart to [`is_namespace_path`], resolving against the
/// `ip netns` convention `/var/run/netns/<name>`.
///
/// Pairs with [`exists`]: `exists` only checks the marker is present; this
/// checks it is a live netns.
pub fn is_namespace(name: &str) -> bool {
    is_namespace_path(PathBuf::from(NETNS_RUN_DIR).join(name))
}

/// Create a named network namespace.
///
/// This is equivalent to `ip netns add <name>`. It creates the namespace
/// directory if needed, creates a new network namespace, and bind-mounts
/// it to `/var/run/netns/<name>`.
///
/// # Errors
///
/// Returns an error if:
/// - The namespace already exists
/// - Permission is denied (requires root or CAP_SYS_ADMIN)
/// - The namespace directory cannot be created
///
/// # Example
///
/// ```ignore
/// use nlink::netlink::namespace;
///
/// namespace::create("myns")?;
/// // Now "myns" exists and can be used
/// let conn = namespace::connection_for("myns")?;
/// ```
///
/// See also [`create_path`] to persist a netns at an arbitrary path.
pub fn create(name: &str) -> Result<()> {
    create_path(PathBuf::from(NETNS_RUN_DIR).join(name))
}

/// The EEXIST-shaped error [`create_path`] returns for an already-present
/// path. Built as `ErrorKind::AlreadyExists` (rather than a stringly
/// `InvalidMessage`) so callers can classify it with
/// [`Error::is_already_exists`] — the detect-stale-and-retry loop around
/// [`is_namespace_path`] depends on that.
fn already_exists_error(path: &Path) -> Error {
    Error::Io(std::io::Error::new(
        std::io::ErrorKind::AlreadyExists,
        format!("namespace '{}' already exists", path.display()),
    ))
}

/// Highest ancestor of `dir` that does not yet exist — the directory that
/// `create_dir_all(dir)` will materialize first. Removing it on rollback
/// undoes exactly what we created and nothing pre-existing.
fn topmost_missing_ancestor(dir: &Path) -> PathBuf {
    let mut topmost = dir.to_path_buf();
    let mut cursor = dir;
    while let Some(parent) = cursor.parent() {
        if parent.exists() {
            break;
        }
        topmost = parent.to_path_buf();
        cursor = parent;
    }
    topmost
}

/// Rollback counterpart to the `create_dir_all` in [`create_path`]: remove
/// the directories it materialized, walking upward from `parent` to
/// `topmost` (inclusive) with `remove_dir`, which only deletes *empty*
/// directories. `remove_dir_all` would be wrong here: a concurrent
/// `create_path` under a shared ancestor may have installed its own marker
/// since we created the tree — `remove_dir` stops at the first non-empty
/// (or already-removed) directory instead of deleting a sibling's namespace
/// out from under it.
fn remove_empty_dirs_upward(parent: &Path, topmost: &Path) {
    let mut cursor = parent;
    loop {
        if std::fs::remove_dir(cursor).is_err() {
            // Non-empty (a sibling moved in) or already gone (a racing
            // rollback) — every ancestor is non-empty too, so stop.
            return;
        }
        if cursor == topmost {
            return;
        }
        let Some(next) = cursor.parent() else { return };
        cursor = next;
    }
}

/// Create a persistent network namespace bind-mounted at an arbitrary `path`.
///
/// Like [`create`], but the namespace lives at the caller's path instead of
/// the `ip netns` convention `/var/run/netns/<name>`. The parent directory is
/// created if needed.
///
/// `path` should be absolute. A relative path resolves against the current
/// working directory, which a multi-threaded program can change mid-call —
/// surprising for both the bind mount and the parent-rollback target.
///
/// # Errors
///
/// Returns an error if the path already exists (EEXIST-shaped — matchable
/// via [`Error::is_already_exists`]), the parent cannot be created, or the
/// unshare/mount sequence fails (requires root or CAP_SYS_ADMIN).
pub fn create_path<P: AsRef<Path>>(path: P) -> Result<()> {
    let ns_path = path.as_ref().to_path_buf();

    // Check if namespace already exists
    if ns_path.exists() {
        return Err(already_exists_error(&ns_path));
    }

    // Remember the created directory span (deepest, topmost) so a later
    // failure can roll back the tree instead of leaking it.
    let created_dirs = match ns_path.parent() {
        Some(parent) if !parent.exists() => {
            let topmost = topmost_missing_ancestor(parent);
            std::fs::create_dir_all(parent).map_err(|e| {
                Error::InvalidMessage(format!("cannot create {}: {}", parent.display(), e))
            })?;
            Some((parent.to_path_buf(), topmost))
        }
        _ => None,
    };

    let rollback_dirs = |created: &Option<(PathBuf, PathBuf)>| {
        if let Some((parent, topmost)) = created {
            remove_empty_dirs_upward(parent, topmost);
        }
    };

    // Create an empty file for the bind mount. `create_new` closes the
    // TOCTOU on the exists() check above: if a concurrent create_path (or an
    // operator `ip netns add`) won the race since, this fails with EEXIST
    // instead of truncating the winner's marker.
    std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&ns_path)
        .map_err(|e| {
            rollback_dirs(&created_dirs);
            if e.kind() == std::io::ErrorKind::AlreadyExists {
                already_exists_error(&ns_path)
            } else {
                Error::InvalidMessage(format!(
                    "cannot create namespace file '{}': {}",
                    ns_path.display(),
                    e
                ))
            }
        })?;

    // 0.19 N1 fix — isolate the unshare+mount+setns sequence on
    // a dedicated OS thread.
    //
    // The kernel scopes `unshare(CLONE_NEWNET)` to the *calling
    // thread*, not the process. When this function is called from
    // an async context (tokio `LabNamespace::new`, integration
    // test setup), the calling thread is a tokio worker. Until
    // the matching `setns()` restores the original netns, every
    // other tokio task scheduled on that worker temporarily
    // observes the new (empty) namespace — including any
    // `Connection<P>` they construct in that window, which
    // silently binds to the wrong netns. The same mechanism
    // affects sync callers from a multi-threaded program because
    // `mount(2)` can block on disk I/O long enough for any other
    // thread to be scheduled.
    //
    // The fix: do the unshare+mount+setns on a freshly-spawned
    // `std::thread`, then `join()`. The dedicated thread has no
    // co-scheduled work, and its destructor is the only observer
    // of the transient netns membership; we wait for setns to
    // complete before returning.
    let ns_path_owned = ns_path.clone();
    let label = ns_path.display().to_string();
    let thread_result = std::thread::spawn(move || -> Result<()> {
        create_namespace_in_current_thread(&label, &ns_path_owned)
    })
    .join();

    match thread_result {
        Ok(Ok(())) => Ok(()),
        Ok(Err(e)) => {
            // Worker already tore down its marker (and any live mount) on every
            // error path; retry here in case it raced, then roll back parent dirs.
            let _ = std::fs::remove_file(&ns_path);
            rollback_dirs(&created_dirs);
            Err(e)
        }
        Err(_panic) => {
            // Worker panicked — leaves the bind mount in an
            // undefined state. Remove the file so we don't leak
            // an empty netns marker.
            let _ = std::fs::remove_file(&ns_path);
            rollback_dirs(&created_dirs);
            Err(Error::InvalidMessage(format!(
                "namespace '{}' worker thread panicked during create",
                ns_path.display()
            )))
        }
    }
}

/// Inner half of [`create`] — runs on a dedicated `std::thread`
/// so the `unshare(CLONE_NEWNET)` + `mount(MS_BIND)` + `setns()`
/// sequence is isolated from tokio worker threads. See [`create`]
/// for the rationale.
fn create_namespace_in_current_thread(name: &str, ns_path: &Path) -> Result<()> {
    // Save the current namespace so we can restore after unshare.
    // Without this, unshare(CLONE_NEWNET) permanently changes the calling
    // thread's namespace, breaking subsequent namespace operations.
    let original_ns = File::open("/proc/thread-self/ns/net").map_err(|e| {
        let _ = std::fs::remove_file(ns_path);
        Error::InvalidMessage(format!("cannot save current namespace: {}", e))
    })?;

    // Create a new network namespace
    // SAFETY: unshare is a standard Linux syscall. CLONE_NEWNET creates a new
    // network namespace for the current process.
    let ret = unsafe { libc::unshare(libc::CLONE_NEWNET) };
    if ret < 0 {
        // Clean up the file we created
        let _ = std::fs::remove_file(ns_path);
        return Err(Error::Io(std::io::Error::last_os_error()));
    }

    // Bind mount the namespace to the file
    let ns_path_cstr = path_to_cstring(ns_path).inspect_err(|_| {
        let _ = std::fs::remove_file(ns_path);
    })?;

    let self_ns = std::ffi::CString::new("/proc/thread-self/ns/net").unwrap();

    // SAFETY: mount is a standard Linux syscall. We're bind-mounting the current
    // process's network namespace (which we just created) to the namespace file.
    let ret = unsafe {
        libc::mount(
            self_ns.as_ptr(),
            ns_path_cstr.as_ptr(),
            std::ptr::null(),
            libc::MS_BIND,
            std::ptr::null(),
        )
    };

    if ret < 0 {
        let err = std::io::Error::last_os_error();
        // Try to restore original namespace before returning
        unsafe { libc::setns(original_ns.as_raw_fd(), libc::CLONE_NEWNET) };
        let _ = std::fs::remove_file(ns_path);
        return Err(Error::Io(err));
    }

    // Restore the calling thread to its original namespace.
    // SAFETY: setns is a standard Linux syscall. original_ns is a valid FD
    // to the namespace we opened before unshare().
    let ret = unsafe { libc::setns(original_ns.as_raw_fd(), libc::CLONE_NEWNET) };
    if ret < 0 {
        let restore_err = std::io::Error::last_os_error();
        // Bind mount is live but we couldn't restore the caller's netns, so the
        // create has failed as a whole. Tear down the mount + marker here so the
        // caller's rollback isn't racing a pinned mount.
        if let Ok(c) = path_to_cstring(ns_path) {
            unsafe { libc::umount2(c.as_ptr(), libc::MNT_DETACH) };
        }
        let _ = std::fs::remove_file(ns_path);
        return Err(Error::InvalidMessage(format!(
            "namespace '{}' failed to restore original namespace: {}",
            name, restore_err
        )));
    }

    Ok(())
}

/// Delete a named network namespace.
///
/// This is equivalent to `ip netns del <name>`. It unmounts and removes
/// the namespace file from `/var/run/netns/<name>`.
///
/// # Errors
///
/// Returns an error if:
/// - The namespace doesn't exist
/// - Permission is denied
/// - The unmount fails (e.g., namespace is in use)
///
/// # Example
///
/// ```ignore
/// use nlink::netlink::namespace;
///
/// namespace::delete("myns")?;
/// ```
///
/// See also [`delete_path`] to delete a netns at an arbitrary path.
pub fn delete(name: &str) -> Result<()> {
    delete_path(PathBuf::from(NETNS_RUN_DIR).join(name))
}

/// Delete a persistent network namespace at an arbitrary `path`.
///
/// The path-based counterpart to [`delete`], for namespaces created via
/// [`create_path`]. Lazily unmounts the bind mount (`MNT_DETACH`) and removes
/// the marker file.
///
/// Removes only the marker file and bind mount; parent directories that
/// [`create_path`] created are left in place — delete cannot know which
/// ancestors were pre-existing. The caller owns teardown of its directory
/// tree.
///
/// # Errors
///
/// Returns an error if:
/// - The path doesn't exist — `Error::NamespaceNotFound`, whose `name` field
///   carries the path string for path-based deletes.
/// - The unmount fails with anything other than `EINVAL` (which covers the
///   "not a mount point" case — a stale marker with no live bind mount).
/// - The marker file cannot be removed.
pub fn delete_path<P: AsRef<Path>>(path: P) -> Result<()> {
    let ns_path = path.as_ref();

    if !ns_path.exists() {
        return Err(Error::NamespaceNotFound {
            name: ns_path.display().to_string(),
        });
    }

    let ns_path_cstr = path_to_cstring(ns_path)?;

    // Unmount the namespace
    // SAFETY: umount2 is a standard Linux syscall. MNT_DETACH allows lazy
    // unmounting which succeeds even if the mount is busy.
    let ret = unsafe { libc::umount2(ns_path_cstr.as_ptr(), libc::MNT_DETACH) };
    if ret < 0 {
        let err = std::io::Error::last_os_error();
        // EINVAL means it's not a mount point (maybe already unmounted)
        if err.raw_os_error() != Some(libc::EINVAL) {
            return Err(Error::Io(err));
        }
    }

    // Remove the file
    std::fs::remove_file(ns_path)
        .map_err(|e| Error::InvalidMessage(format!("cannot remove namespace file: {}", e)))?;

    Ok(())
}

/// Execute a function in a network namespace and return to the original.
///
/// This is a convenience wrapper around [`enter`] that ensures the original
/// namespace is restored even if the function panics.
///
/// # Warning
///
/// This affects the entire thread. In async contexts, prefer using
/// [`connection_for`] which creates a socket in the namespace without
/// affecting the thread state.
///
/// The closure runs on the **calling** thread; if the restore afterwards
/// fails, that thread stays in the target namespace (see [`enter`]'s
/// warning). When the closure is `Send + 'static`, prefer spawning a
/// scoped thread that enters the namespace and exits without restoring —
/// the pattern the [`get_sysctl`]-family helpers use internally (#185).
///
/// # Example
///
/// ```ignore
/// use nlink::netlink::namespace;
///
/// let result = namespace::execute_in("myns", || {
///     // Code here runs in "myns" namespace
///     std::fs::read_to_string("/proc/net/dev")
/// })??;
/// // Back in original namespace
/// ```
pub fn execute_in<F, T>(name: &str, f: F) -> Result<T>
where
    F: FnOnce() -> T,
{
    let guard = enter(name)?;
    let result = f();
    guard.restore()?;
    Ok(result)
}

/// Execute a function in a network namespace specified by path.
///
/// See [`execute_in`] for details.
pub fn execute_in_path<F, T, P: AsRef<Path>>(path: P, f: F) -> Result<T>
where
    F: FnOnce() -> T,
{
    let guard = enter_path(path)?;
    let result = f();
    guard.restore()?;
    Ok(result)
}

/// List all named network namespaces.
///
/// Returns the names of namespaces in `/var/run/netns/`.
///
/// # Example
///
/// ```ignore
/// use nlink::netlink::namespace;
///
/// for ns in namespace::list()? {
///     println!("Namespace: {}", ns);
/// }
/// ```
pub fn list() -> Result<Vec<String>> {
    let dir = match std::fs::read_dir(NETNS_RUN_DIR) {
        Ok(d) => d,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            // No namespaces directory means no namespaces
            return Ok(Vec::new());
        }
        Err(e) => {
            return Err(Error::Io(e));
        }
    };

    let mut names = Vec::new();
    for entry in dir {
        let entry = entry.map_err(Error::Io)?;
        let name = entry.file_name().to_string_lossy().to_string();
        if name != "." && name != ".." {
            names.push(name);
        }
    }

    names.sort();
    Ok(names)
}

// ─────────────────────────────────────────────────
// Sysctl operations (namespace-aware)
// ─────────────────────────────────────────────────

/// Run `f` on a dedicated worker thread that has entered the namespace at
/// `path`, joining before return.
///
/// The worker exits **without restoring** — a thread's netns membership dies
/// with it — so there is no restore step that can fail and leave a shared
/// (e.g. tokio worker) thread stuck in the target namespace (#185). This is
/// the same thread discipline as [`create_path`] and
/// `NetlinkSocket::new_in_namespace`. Contrast with [`execute_in`], which
/// runs `f` on the *calling* thread and carries that hazard.
fn run_in_namespace_thread<T, F>(path: PathBuf, f: F) -> Result<T>
where
    F: FnOnce() -> Result<T> + Send + 'static,
    T: Send + 'static,
{
    let thread_result = std::thread::spawn(move || -> Result<T> {
        let target = File::open(&path).map_err(|e| namespace_open_error(&path, e))?;
        // SAFETY: setns switches only this freshly-spawned worker thread,
        // which exits right after `f` returns.
        let ret = unsafe { libc::setns(target.as_raw_fd(), libc::CLONE_NEWNET) };
        if ret < 0 {
            return Err(Error::Io(std::io::Error::last_os_error()));
        }
        f()
    })
    .join();

    match thread_result {
        Ok(result) => result,
        Err(_panic) => Err(Error::InvalidMessage(
            "namespace worker thread panicked".to_string(),
        )),
    }
}

/// Read a sysctl value inside a named namespace.
///
/// Reads the value from `/proc/sys/` on a dedicated worker thread entered
/// into the namespace; the calling thread's namespace is untouched (#185).
///
/// # Example
///
/// ```ignore
/// use nlink::netlink::namespace;
///
/// let val = namespace::get_sysctl("myns", "net.ipv4.ip_forward")?;
/// assert!(val == "0" || val == "1");
/// ```
pub fn get_sysctl(ns_name: &str, key: &str) -> Result<String> {
    get_sysctl_path(PathBuf::from(NETNS_RUN_DIR).join(ns_name), key)
}

/// Set a sysctl value inside a named namespace.
///
/// Writes the value to `/proc/sys/` on a dedicated worker thread entered
/// into the namespace; the calling thread's namespace is untouched (#185).
/// Requires root or `CAP_SYS_ADMIN`.
///
/// # Example
///
/// ```ignore
/// use nlink::netlink::namespace;
///
/// namespace::set_sysctl("myns", "net.ipv4.ip_forward", "1")?;
/// ```
pub fn set_sysctl(ns_name: &str, key: &str, value: &str) -> Result<()> {
    set_sysctl_path(PathBuf::from(NETNS_RUN_DIR).join(ns_name), key, value)
}

/// Set multiple sysctl values inside a named namespace.
///
/// Enters the namespace once (on a dedicated worker thread) and applies all
/// entries. If any entry fails, returns the error immediately without
/// applying remaining entries.
///
/// # Example
///
/// ```ignore
/// use nlink::netlink::namespace;
///
/// namespace::set_sysctls("myns", &[
///     ("net.ipv4.ip_forward", "1"),
///     ("net.ipv6.conf.all.forwarding", "1"),
/// ])?;
/// ```
pub fn set_sysctls(ns_name: &str, entries: &[(&str, &str)]) -> Result<()> {
    set_sysctls_path(PathBuf::from(NETNS_RUN_DIR).join(ns_name), entries)
}

/// Read a sysctl value inside a namespace specified by path.
///
/// See [`get_sysctl`] for details.
pub fn get_sysctl_path<P: AsRef<Path>>(path: P, key: &str) -> Result<String> {
    let key = key.to_owned();
    run_in_namespace_thread(path.as_ref().to_path_buf(), move || {
        super::sysctl::get(&key)
    })
}

/// Set a sysctl value inside a namespace specified by path.
///
/// See [`set_sysctl`] for details.
pub fn set_sysctl_path<P: AsRef<Path>>(path: P, key: &str, value: &str) -> Result<()> {
    let (key, value) = (key.to_owned(), value.to_owned());
    run_in_namespace_thread(path.as_ref().to_path_buf(), move || {
        super::sysctl::set(&key, &value)
    })
}

/// Set multiple sysctl values inside a namespace specified by path.
///
/// See [`set_sysctls`] for details.
pub fn set_sysctls_path<P: AsRef<Path>>(path: P, entries: &[(&str, &str)]) -> Result<()> {
    let entries: Vec<(String, String)> = entries
        .iter()
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .collect();
    run_in_namespace_thread(path.as_ref().to_path_buf(), move || {
        let borrowed: Vec<(&str, &str)> = entries
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect();
        super::sysctl::set_many(&borrowed)
    })
}

// ─────────────────────────────────────────────────
// Process spawning (namespace-aware)
// ─────────────────────────────────────────────────

/// Spawn a process inside a named network namespace.
///
/// Uses `pre_exec` + `setns()` to switch the child process into the target
/// namespace between `fork()` and `exec()`. The parent process is unaffected.
///
/// # Example
///
/// ```ignore
/// use nlink::netlink::namespace;
/// use std::process::Command;
///
/// let mut child = namespace::spawn("myns", Command::new("ip").arg("link"))?;
/// child.wait()?;
/// ```
pub fn spawn(ns_name: &str, cmd: std::process::Command) -> Result<std::process::Child> {
    let path = PathBuf::from(NETNS_RUN_DIR).join(ns_name);
    if !path.exists() {
        return Err(Error::NamespaceNotFound {
            name: ns_name.to_string(),
        });
    }
    spawn_path(&path, cmd)
}

/// Spawn a process and collect its output inside a named namespace.
///
/// This is a convenience wrapper that spawns the process with stdout and
/// stderr captured, waits for it to complete, and returns the output.
///
/// # Example
///
/// ```ignore
/// use nlink::netlink::namespace;
/// use std::process::Command;
///
/// let output = namespace::spawn_output("myns", Command::new("ip").arg("addr"))?;
/// println!("{}", String::from_utf8_lossy(&output.stdout));
/// ```
pub fn spawn_output(ns_name: &str, mut cmd: std::process::Command) -> Result<std::process::Output> {
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());
    let child = spawn(ns_name, cmd)?;
    child.wait_with_output().map_err(Error::Io)
}

/// Spawn a process inside a namespace specified by path.
///
/// See [`spawn`] for details.
///
/// # Example
///
/// ```ignore
/// use nlink::netlink::namespace;
/// use std::process::Command;
///
/// let child = namespace::spawn_path(
///     "/proc/1234/ns/net",
///     Command::new("ip").arg("link"),
/// )?;
/// ```
pub fn spawn_path<P: AsRef<Path>>(
    path: P,
    mut cmd: std::process::Command,
) -> Result<std::process::Child> {
    use std::os::unix::process::CommandExt;

    let ns_fd = open_path(path)?;
    let raw_fd = ns_fd.as_raw_fd();

    // SAFETY: setns is async-signal-safe (it's a syscall). pre_exec runs in
    // the child process after fork() but before exec(). The fd is valid
    // because ns_fd is kept alive until after spawn() returns — the closure
    // captures raw_fd by value, and ns_fd is dropped only after spawn().
    unsafe {
        cmd.pre_exec(move || {
            if libc::setns(raw_fd, libc::CLONE_NEWNET) != 0 {
                return Err(std::io::Error::last_os_error());
            }
            Ok(())
        });
    }

    let child = cmd.spawn().map_err(Error::Io)?;
    drop(ns_fd);
    Ok(child)
}

/// Spawn a process and collect its output inside a namespace specified by path.
///
/// See [`spawn_output`] for details.
pub fn spawn_output_path<P: AsRef<Path>>(
    path: P,
    mut cmd: std::process::Command,
) -> Result<std::process::Output> {
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());
    let child = spawn_path(path, cmd)?;
    child.wait_with_output().map_err(Error::Io)
}

// ============================================================================
// Process spawning with /etc/netns/ overlay (mirrors `ip netns exec`)
// ============================================================================

/// Pre-compute bind mount pairs from `/etc/netns/<name>/`.
///
/// This runs in the parent process where memory allocation is safe.
/// The returned `CString` pairs are captured by the `pre_exec` closure
/// so that only raw syscalls (no allocations) happen after fork.
fn prepare_etc_binds(ns_name: &str) -> Result<Vec<(std::ffi::CString, std::ffi::CString)>> {
    let etc_netns = PathBuf::from("/etc/netns").join(ns_name);

    let entries = match std::fs::read_dir(&etc_netns) {
        Ok(entries) => entries,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(Error::Io(e)),
    };

    let mut binds = Vec::new();
    for entry in entries {
        let entry = entry.map_err(Error::Io)?;
        let file_name = entry.file_name();
        let src = entry.path();
        let dst = Path::new("/etc").join(&file_name);

        // Only overlay if the target exists (can't bind-mount over nothing)
        if !dst.exists() {
            continue;
        }

        let src_c = std::ffi::CString::new(src.as_os_str().as_encoded_bytes())
            .map_err(|_| Error::InvalidMessage("null byte in path".into()))?;
        let dst_c = std::ffi::CString::new(dst.as_os_str().as_encoded_bytes())
            .map_err(|_| Error::InvalidMessage("null byte in path".into()))?;

        binds.push((src_c, dst_c));
    }

    Ok(binds)
}

/// Spawn a process in a network namespace with `/etc/netns/` file overlays.
///
/// Like [`spawn`], but also creates a private mount namespace in the child and:
/// 1. Bind-mounts files from `/etc/netns/<ns_name>/` over `/etc/`
/// 2. Remounts `/sys` (sysfs) to reflect the new network namespace
///
/// This mirrors the behavior of `ip netns exec <name> <cmd>`.
///
/// If `/etc/netns/<ns_name>/` does not exist, the mount overlay step is skipped
/// and behavior is identical to [`spawn`].
///
/// Requires `CAP_SYS_ADMIN` (for `unshare(CLONE_NEWNS)`).
///
/// # Example
///
/// ```ignore
/// use nlink::netlink::namespace;
/// use std::process::Command;
///
/// // Create /etc/netns/myns/hosts with custom DNS entries, then:
/// let output = namespace::spawn_output_with_etc("myns", Command::new("cat").arg("/etc/hosts"))?;
/// // The process sees the custom /etc/hosts, not the host's
/// ```
pub fn spawn_with_etc(ns_name: &str, cmd: std::process::Command) -> Result<std::process::Child> {
    let path = PathBuf::from(NETNS_RUN_DIR).join(ns_name);
    if !path.exists() {
        return Err(Error::NamespaceNotFound {
            name: ns_name.to_string(),
        });
    }
    spawn_path_with_etc(&path, ns_name, cmd)
}

/// Spawn a process and collect its output with `/etc/netns/` file overlays.
///
/// See [`spawn_with_etc`] for details.
pub fn spawn_output_with_etc(
    ns_name: &str,
    mut cmd: std::process::Command,
) -> Result<std::process::Output> {
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());
    let child = spawn_with_etc(ns_name, cmd)?;
    child.wait_with_output().map_err(Error::Io)
}

/// Spawn a process in a namespace specified by path with `/etc/netns/` file overlays.
///
/// The `ns_name` parameter is needed to locate the `/etc/netns/<name>/` directory.
///
/// See [`spawn_with_etc`] for details.
pub fn spawn_path_with_etc<P: AsRef<Path>>(
    path: P,
    ns_name: &str,
    mut cmd: std::process::Command,
) -> Result<std::process::Child> {
    use std::os::unix::process::CommandExt;

    let ns_fd = open_path(path)?;
    let raw_fd = ns_fd.as_raw_fd();

    // Pre-compute ALL data before fork — no allocations in pre_exec.
    let bind_mounts = prepare_etc_binds(ns_name)?;
    let ns_name_c = std::ffi::CString::new(ns_name)
        .map_err(|_| Error::InvalidMessage("null byte in namespace name".into()))?;

    // Pre-computed string literals for syscalls (avoid allocation after fork).
    let c_root = std::ffi::CString::new("/").unwrap();
    let c_none = std::ffi::CString::new("none").unwrap();
    let c_sys = std::ffi::CString::new("/sys").unwrap();
    let c_sysfs = std::ffi::CString::new("sysfs").unwrap();

    // SAFETY: All operations in pre_exec use only raw syscalls (setns, unshare,
    // mount, umount2). No memory allocation occurs — all CStrings are pre-computed
    // above and captured by the closure. This is async-signal-safe.
    unsafe {
        cmd.pre_exec(move || {
            // 1. Enter network namespace
            if libc::setns(raw_fd, libc::CLONE_NEWNET) != 0 {
                return Err(std::io::Error::last_os_error());
            }

            // 2. If no /etc overlay files, skip mount namespace setup entirely
            if bind_mounts.is_empty() {
                return Ok(());
            }

            // 3. Create private mount namespace for the child
            if libc::unshare(libc::CLONE_NEWNS) != 0 {
                return Err(std::io::Error::last_os_error());
            }

            // 4. Make mount tree slave to prevent propagation back to host.
            //    MS_SLAVE (not MS_PRIVATE) so parent->child propagation still works.
            if libc::mount(
                c_none.as_ptr(),
                c_root.as_ptr(),
                std::ptr::null(),
                libc::MS_SLAVE | libc::MS_REC,
                std::ptr::null(),
            ) != 0
            {
                return Err(std::io::Error::last_os_error());
            }

            // 5. Remount /sys so sysfs reflects the new network namespace.
            //    Without this, /sys/class/net/ shows the host's interfaces.
            libc::umount2(c_sys.as_ptr(), libc::MNT_DETACH);
            if libc::mount(
                ns_name_c.as_ptr(),
                c_sys.as_ptr(),
                c_sysfs.as_ptr(),
                0,
                std::ptr::null(),
            ) != 0
            {
                // Non-fatal: sysfs remount may fail in nested namespaces
                // or restricted environments. Continue with /etc overlays.
            }

            // 6. Apply pre-computed /etc bind mounts
            for (src, dst) in &bind_mounts {
                if libc::mount(
                    src.as_ptr(),
                    dst.as_ptr(),
                    std::ptr::null(),
                    libc::MS_BIND,
                    std::ptr::null(),
                ) != 0
                {
                    return Err(std::io::Error::last_os_error());
                }
            }

            Ok(())
        });
    }

    let child = cmd.spawn().map_err(Error::Io)?;
    drop(ns_fd);
    Ok(child)
}

/// Spawn a process and collect output in a namespace by path with `/etc/netns/` overlays.
///
/// See [`spawn_path_with_etc`] for details.
pub fn spawn_output_path_with_etc<P: AsRef<Path>>(
    path: P,
    ns_name: &str,
    mut cmd: std::process::Command,
) -> Result<std::process::Output> {
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());
    let child = spawn_path_with_etc(path, ns_name, cmd)?;
    child.wait_with_output().map_err(Error::Io)
}

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

    #[test]
    fn test_netns_run_dir() {
        assert_eq!(NETNS_RUN_DIR, "/var/run/netns");
    }

    #[test]
    fn test_list_namespaces() {
        // This should not fail even if the directory doesn't exist
        let result = list();
        assert!(result.is_ok());
    }

    #[test]
    fn test_exists_nonexistent() {
        assert!(!exists("definitely_does_not_exist_12345"));
    }

    #[test]
    fn test_topmost_missing_ancestor() {
        let base = std::env::temp_dir().join(format!("nlink-tma-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        // base does not exist; the topmost missing ancestor of base/a/b is base.
        assert_eq!(topmost_missing_ancestor(&base.join("a/b")), base);

        std::fs::create_dir_all(&base).unwrap();
        // base exists now; the topmost missing ancestor of base/a/b is base/a.
        assert_eq!(topmost_missing_ancestor(&base.join("a/b")), base.join("a"));
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn test_create_path_rejects_existing_marker() {
        // The already-exists check runs before any privileged syscall, so this
        // exercises the error path without root.
        let path = std::env::temp_dir().join(format!("nlink-exists-{}", std::process::id()));
        std::fs::File::create(&path).unwrap();
        let err = create_path(&path).expect_err("existing path must be rejected");
        assert!(err.to_string().contains("already exists"));
        assert!(
            err.is_already_exists(),
            "rejection must be classifiable via is_already_exists()"
        );
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn test_remove_empty_dirs_upward_full_chain() {
        let base = std::env::temp_dir().join(format!("nlink-rb-full-{}", std::process::id()));
        let parent = base.join("a/b");
        std::fs::create_dir_all(&parent).unwrap();
        remove_empty_dirs_upward(&parent, &base);
        assert!(!base.exists(), "empty chain should be removed up to topmost");
    }

    #[test]
    fn test_remove_empty_dirs_upward_stops_at_nonempty() {
        // Simulates a concurrent create_path having installed its own marker
        // under a shared ancestor: rollback must stop at the non-empty
        // directory instead of deleting the sibling.
        let base = std::env::temp_dir().join(format!("nlink-rb-stop-{}", std::process::id()));
        let parent = base.join("a/b");
        std::fs::create_dir_all(&parent).unwrap();
        let sibling = base.join("a/sibling-marker");
        std::fs::File::create(&sibling).unwrap();

        remove_empty_dirs_upward(&parent, &base);

        assert!(!parent.exists(), "empty leaf dir should be removed");
        assert!(sibling.exists(), "sibling marker must survive rollback");
        assert!(base.join("a").exists(), "non-empty ancestor must survive");
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn test_delete_path_missing_is_not_found() {
        let path =
            std::env::temp_dir().join(format!("nlink-missing-del-{}", std::process::id()));
        let _ = std::fs::remove_file(&path);
        let err = delete_path(&path).expect_err("missing path must be rejected");
        assert!(err.is_not_found());
    }

    #[test]
    fn is_namespace_path_false_for_missing() {
        let path =
            std::env::temp_dir().join(format!("nlink-isns-missing-{}", std::process::id()));
        let _ = std::fs::remove_file(&path);
        assert!(!is_namespace_path(&path));
    }

    #[test]
    fn is_namespace_path_false_for_plain_file() {
        // A regular file (the shape of a *stale* marker) is not a live netns.
        let path = std::env::temp_dir().join(format!("nlink-isns-plain-{}", std::process::id()));
        std::fs::File::create(&path).unwrap();
        assert!(!is_namespace_path(&path));
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn is_namespace_false_for_nonexistent_name() {
        assert!(!is_namespace("definitely_does_not_exist_12345"));
    }

    // #184 — missing-namespace opens must classify via is_not_found(),
    // across every entry point that funnels through namespace_open_error.
    #[test]
    fn open_path_missing_is_not_found() {
        let path =
            std::env::temp_dir().join(format!("nlink-open-missing-{}", std::process::id()));
        let _ = std::fs::remove_file(&path);
        let err = open_path(&path).expect_err("missing path must fail");
        assert!(err.is_not_found(), "got unclassifiable error: {err}");
    }

    #[test]
    fn enter_path_missing_is_not_found() {
        let path =
            std::env::temp_dir().join(format!("nlink-enter-missing-{}", std::process::id()));
        let _ = std::fs::remove_file(&path);
        let err = enter_path(&path).expect_err("missing path must fail");
        assert!(err.is_not_found(), "got unclassifiable error: {err}");
    }

    #[test]
    fn connection_for_missing_name_is_not_found() {
        let Err(err) = connection_for::<crate::Route>("definitely_does_not_exist_12345") else {
            panic!("missing namespace must fail");
        };
        assert!(err.is_not_found(), "got unclassifiable error: {err}");
    }

    #[test]
    fn is_namespace_path_true_for_own_net_ns() {
        // /proc/self/ns/net is a live nsfs inode in any process, so this pins
        // NSFS_MAGIC against the kernel's real value without needing root.
        assert!(is_namespace_path("/proc/self/ns/net"));
    }
}