relswap 0.0.6

Signed-release install/update engine with durable activation and crash recovery
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
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
//! Durable executable and selector operations used by managed installations.
//!
//! This module is deliberately small.  It owns the operations whose correctness depends on the
//! host filesystem (temporary files, durable replacement, executable permissions, and Unix
//! symlinks); the installation module owns the policy about which paths may be changed.

use std::fs::{self, File, OpenOptions};
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);

/// Return the executable that started the current process, after resolving a launcher symlink when
/// the platform can do so.  A regular file is required: an installer must never copy a directory,
/// FIFO, or another indirection as its own payload.
pub fn current_exe() -> io::Result<PathBuf> {
    let path = std::env::current_exe()?;
    let path = fs::canonicalize(path)?;
    ensure_regular_file(&path)?;
    Ok(path)
}

/// Descriptive alias for [`current_exe`].
pub fn current_executable() -> io::Result<PathBuf> {
    current_exe()
}

/// Resolve the launcher-v1 payload from the launcher's own location and an `active` file value.
///
/// This parser is platform-neutral so the path and semantic-version contract is unit tested on
/// every host. The launcher accepts no path from state: the only inputs are a canonical semantic
/// version and the product payload basename, so the payload path is always derived as
/// `versions/<version>/<payload_name>`.
pub fn resolve_launcher_v1_payload(
    launcher: &Path,
    active: &[u8],
    payload_name: &str,
) -> io::Result<PathBuf> {
    let bin = launcher.parent().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            "launcher has no parent directory",
        )
    })?;
    if !bin
        .file_name()
        .and_then(|name| name.to_str())
        .is_some_and(|name| name.eq_ignore_ascii_case("bin"))
    {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "launcher must be installed directly under the managed bin directory",
        ));
    }
    let root = bin.parent().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            "launcher bin directory has no install root",
        )
    })?;
    let raw = std::str::from_utf8(active)
        .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "active is not UTF-8"))?;
    if raw.is_empty() || raw.len() > 128 || raw.trim() != raw {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "active must contain only a canonical semantic version",
        ));
    }
    let version = semver::Version::parse(raw).map_err(|error| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            format!("active does not contain a semantic version: {error}"),
        )
    })?;
    if version.to_string() != raw {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "active version is not canonical",
        ));
    }
    if !is_safe_basename(payload_name, true) {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "managed payload name must be a plain basename",
        ));
    }
    Ok(root
        .join("versions")
        .join(version.to_string())
        .join(payload_name))
}

/// Execute the immutable Windows launcher-v1 protocol and return the payload exit code.
#[cfg(windows)]
pub fn run_windows_launcher(payload_name: &str) -> io::Result<i32> {
    use std::io::Read;

    let launcher = std::env::current_exe()?;
    let bin = launcher.parent().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            "launcher has no parent directory",
        )
    })?;
    if windows_handle::directory_is_case_sensitive(&windows_handle::open_directory(bin, false)?)?
        && bin.file_name() != Some(std::ffi::OsStr::new("bin"))
    {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "launcher bin directory casing is noncanonical",
        ));
    }
    let root = launcher
        .parent()
        .and_then(Path::parent)
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "invalid launcher location"))?;
    let active_path = root.join("active");
    let mut active_lock = windows_handle::lock_regular(&active_path)?;
    let mut active = Vec::new();
    Read::take(&mut active_lock.file, 129).read_to_end(&mut active)?;
    if active.len() > 128 {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "active selector is too large",
        ));
    }
    let payload = resolve_launcher_v1_payload(&launcher, &active, payload_name)?;
    let payload_lock = windows_handle::lock_regular(&payload)?;

    // Command inherits the exact environment, working directory, standard handles, and attached
    // console. Only argv[0] changes from the stable launcher to the selected payload.
    let mut child = std::process::Command::new(payload)
        .args(std::env::args_os().skip(1))
        .spawn()?;
    drop(payload_lock);
    drop(active_lock);
    let status = child.wait()?;
    status.code().ok_or_else(|| {
        io::Error::other("managed payload exited without a Windows process exit code")
    })
}

/// The launcher artifact is Windows-only; keeping a stub lets all-target checks build the named
/// binary without pretending it can launch on another platform.
#[cfg(not(windows))]
pub fn run_windows_launcher(payload_name: &str) -> io::Result<i32> {
    let _ = payload_name;
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "relswap launcher is only supported on Windows",
    ))
}

/// Reject a path which is not a regular, non-link file.
pub fn ensure_regular_file(path: &Path) -> io::Result<()> {
    let metadata = fs::symlink_metadata(path)?;
    if metadata.file_type().is_symlink() || !metadata.is_file() || is_reparse_point(path)? {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!("{} is not a regular file", path.display()),
        ));
    }
    Ok(())
}

/// Open a regular file without following a final symlink or Windows reparse point.
///
/// Callers must validate untrusted ancestor directories separately. This closes the common
/// `metadata`-then-`open` race for files in an already trusted directory.
pub fn open_regular_file(path: &Path) -> io::Result<File> {
    let mut options = OpenOptions::new();
    options.read(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC);
    }
    #[cfg(windows)]
    {
        use std::os::windows::fs::OpenOptionsExt;
        const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
        options.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT);
    }
    let file = options.open(path)?;
    let metadata = file.metadata()?;
    if !metadata.is_file() {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!("{} is not a regular file", path.display()),
        ));
    }
    #[cfg(windows)]
    {
        use std::os::windows::fs::MetadataExt;
        const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
        if metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                format!("{} is a reparse point", path.display()),
            ));
        }
    }
    Ok(file)
}

/// Open a regular file while refusing symlink/reparse-point ancestors.
pub fn open_regular_file_secure(path: &Path) -> io::Result<File> {
    #[cfg(not(windows))]
    let parent = path.parent().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("{} has no parent directory", path.display()),
        )
    })?;
    #[cfg(not(windows))]
    let parent = if parent.as_os_str().is_empty() {
        Path::new(".")
    } else {
        parent
    };
    #[cfg(unix)]
    {
        use std::ffi::CString;
        use std::os::fd::{AsRawFd, FromRawFd};
        use std::os::unix::ffi::OsStrExt;

        let directory = open_directory_tree(parent, false)?;
        let filename = path.file_name().ok_or_else(|| {
            io::Error::new(io::ErrorKind::InvalidInput, "file path has no basename")
        })?;
        let filename = CString::new(filename.as_bytes())
            .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "filename contains NUL"))?;
        let descriptor = unsafe {
            libc::openat(
                directory.as_raw_fd(),
                filename.as_ptr(),
                libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_CLOEXEC | libc::O_NONBLOCK,
            )
        };
        if descriptor < 0 {
            return Err(io::Error::last_os_error());
        }
        let file = unsafe { File::from_raw_fd(descriptor) };
        if !file.metadata()?.is_file() {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                format!("{} is not a regular file", path.display()),
            ));
        }
        Ok(file)
    }
    #[cfg(windows)]
    {
        windows_handle::open_regular(path)
    }
    #[cfg(not(any(unix, windows)))]
    {
        ensure_directory_tree_by_path(parent, false)?;
        open_regular_file(path)
    }
}

/// Create or validate every component of a directory path without traversing a Unix symlink.
///
/// Unix uses `openat(O_NOFOLLOW)` and Windows uses root-directory handles with `NtCreateFile`.
pub fn ensure_directory_tree(path: &Path) -> io::Result<()> {
    #[cfg(unix)]
    {
        open_directory_tree(path, true).map(drop)
    }
    #[cfg(windows)]
    {
        windows_handle::open_directory(path, true).map(drop)
    }
    #[cfg(not(any(unix, windows)))]
    {
        ensure_directory_tree_by_path(path, true)
    }
}

#[cfg(windows)]
pub(crate) fn open_directory_handle(path: &Path) -> io::Result<File> {
    windows_handle::open_directory(path, false)
}

#[cfg(windows)]
pub(crate) fn create_private_directory_handle(
    path: &Path,
    security_descriptor: *mut core::ffi::c_void,
) -> io::Result<File> {
    windows_handle::create_private_directory(path, security_descriptor)
}

#[cfg(windows)]
pub(crate) fn same_directory_object(left: &Path, right: &Path) -> io::Result<bool> {
    let left = windows_handle::open_directory(left, false)?;
    let right = windows_handle::open_directory(right, false)?;
    windows_handle::same_object(&left, &right)
}

#[cfg(windows)]
pub(crate) fn same_regular_file_object(left: &Path, right: &Path) -> io::Result<bool> {
    let left = windows_handle::lock_regular(left)?;
    let right = windows_handle::lock_regular(right)?;
    windows_handle::same_object(&left.file, &right.file)
}

pub(crate) struct OpenDirectory {
    handle: File,
    path: PathBuf,
}

impl OpenDirectory {
    pub(crate) fn create_new_file(
        &self,
        filename: &str,
        bytes: &[u8],
        mode: Option<u32>,
    ) -> io::Result<PathBuf> {
        create_new_file_at(&self.handle, &self.path, filename, bytes, mode)
    }

    pub(crate) fn remove_file(&self, filename: &str) -> io::Result<()> {
        remove_file_at(&self.handle, filename)
    }

    pub(crate) fn path_still_identifies_directory(&self) -> io::Result<bool> {
        let reopened = open_output_directory(&self.path, false)?;
        same_directory_handle(&self.handle, &reopened.handle)
    }
}

fn same_directory_handle(left: &File, right: &File) -> io::Result<bool> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        let left = left.metadata()?;
        let right = right.metadata()?;
        Ok(left.dev() == right.dev() && left.ino() == right.ino())
    }
    #[cfg(windows)]
    {
        windows_handle::same_object(left, right)
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = (left, right);
        Ok(true)
    }
}

#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) fn open_private_directory(path: &Path) -> io::Result<OpenDirectory> {
    crate::fs::security::ensure_private_dir(path)?;
    let directory = open_output_directory(path, false)?;
    #[cfg(unix)]
    crate::fs::security::validate_private_dir(path, &directory.handle.metadata()?)?;
    #[cfg(windows)]
    crate::fs::security::validate_private_dir_handle(&directory.handle)?;
    Ok(directory)
}

pub(crate) fn open_extraction_directory(path: &Path) -> io::Result<OpenDirectory> {
    #[cfg(windows)]
    {
        open_private_directory(path)
    }
    #[cfg(not(windows))]
    {
        open_output_directory(path, false)
    }
}

fn open_output_directory(path: &Path, create: bool) -> io::Result<OpenDirectory> {
    #[cfg(unix)]
    let handle = open_directory_tree(path, create)?;
    #[cfg(windows)]
    let handle = windows_handle::open_directory(path, create)?;
    #[cfg(not(any(unix, windows)))]
    let handle = {
        ensure_directory_tree_by_path(path, create)?;
        File::open(path)?
    };
    Ok(OpenDirectory {
        handle,
        path: path.to_path_buf(),
    })
}

/// Create one new file in `directory`, without replacing an existing name or following links.
///
/// On Unix both the create and cleanup are relative to an open directory handle. Permissions,
/// size, and bytes are checked through the opened file handle.
pub fn create_new_file_in_directory(
    directory: &Path,
    filename: &str,
    bytes: &[u8],
    mode: Option<u32>,
) -> io::Result<PathBuf> {
    #[cfg(windows)]
    let directory = open_private_directory(directory)?;
    #[cfg(not(windows))]
    let directory = open_output_directory(directory, true)?;
    directory.create_new_file(filename, bytes, mode)
}

pub(crate) fn is_safe_basename(value: &str, windows_semantics: bool) -> bool {
    if value.is_empty() || matches!(value, "." | "..") || value.contains(['/', '\\', '\0', ':']) {
        return false;
    }
    if !windows_semantics {
        return true;
    }
    if value.ends_with([' ', '.'])
        || value.bytes().any(|byte| byte < b' ')
        || value.contains(['"', '<', '>', '|', '?', '*'])
    {
        return false;
    }
    let stem = value.split('.').next().unwrap_or_default();
    !matches!(
        stem.to_ascii_uppercase().as_str(),
        "CON"
            | "PRN"
            | "AUX"
            | "NUL"
            | "COM1"
            | "COM2"
            | "COM3"
            | "COM4"
            | "COM5"
            | "COM6"
            | "COM7"
            | "COM8"
            | "COM9"
            | "COM¹"
            | "COM²"
            | "COM³"
            | "LPT1"
            | "LPT2"
            | "LPT3"
            | "LPT4"
            | "LPT5"
            | "LPT6"
            | "LPT7"
            | "LPT8"
            | "LPT9"
            | "LPT¹"
            | "LPT²"
            | "LPT³"
            | "CONIN$"
            | "CONOUT$"
    )
}

/// Whether `path` is a Windows reparse point.  Unix has no equivalent indirection bit; symlink
/// checks use `symlink_metadata` at every policy boundary instead.
pub fn is_reparse_point(path: &Path) -> io::Result<bool> {
    #[cfg(windows)]
    {
        use std::os::windows::fs::MetadataExt;
        const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
        Ok(fs::symlink_metadata(path)?.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0)
    }
    #[cfg(not(windows))]
    {
        let _ = path;
        Ok(false)
    }
}

/// Read a Unix selector symlink without following it.  On Windows this returns `None`; managed
/// installations use the UTF-8 `active` file instead.
#[cfg(unix)]
pub fn read_symlink(path: &Path) -> io::Result<Option<PathBuf>> {
    match fs::symlink_metadata(path) {
        Ok(metadata) if metadata.file_type().is_symlink() => fs::read_link(path).map(Some),
        Ok(_) => Err(io::Error::new(
            io::ErrorKind::InvalidData,
            format!("{} is not a symbolic link", path.display()),
        )),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
        Err(error) => Err(error),
    }
}

/// The non-Unix selector shape is intentionally represented by an absent symlink.
#[cfg(not(unix))]
pub fn read_symlink(path: &Path) -> io::Result<Option<PathBuf>> {
    match fs::symlink_metadata(path) {
        Ok(_) => Err(io::Error::new(
            io::ErrorKind::InvalidData,
            format!("{} is not a symbolic link on this platform", path.display()),
        )),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
        Err(error) => Err(error),
    }
}

/// Replace a regular file atomically and durably.  The temporary file is created beside the
/// destination, written and synced before the final replace, so a crash exposes either the old
/// complete file or the new complete file.
pub fn atomic_replace_file(path: &Path, bytes: &[u8]) -> io::Result<()> {
    atomic_replace_file_with_mode(path, bytes, None)
}

/// [`atomic_replace_file`] with an optional Unix mode for the newly-created file.
pub fn atomic_replace_file_with_mode(
    path: &Path,
    bytes: &[u8],
    mode: Option<u32>,
) -> io::Result<()> {
    let parent = path.parent().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("{} has no parent directory", path.display()),
        )
    })?;
    ensure_directory(parent)?;
    reject_reparse(path)?;

    let temporary = create_temporary_file(path, mode)?;
    let result = (|| {
        let mut file = temporary.file;
        file.write_all(bytes)?;
        file.flush()?;
        file.sync_all()?;
        drop(file);
        replace_existing(&temporary.path, path)?;
        sync_dir(parent)
    })();
    if result.is_err() {
        let _ = fs::remove_file(&temporary.path);
    }
    result
}

/// Create a regular file without replacing an existing path, write it fully, and sync it.  This
/// is used for the Windows launcher, whose ownership contract forbids self-updating an existing
/// launcher.
pub fn create_new_file(path: &Path, bytes: &[u8], mode: Option<u32>) -> io::Result<()> {
    let parent = path.parent().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("{} has no parent directory", path.display()),
        )
    })?;
    ensure_directory(parent)?;
    match fs::symlink_metadata(path) {
        Ok(_) => {
            return Err(io::Error::new(
                io::ErrorKind::AlreadyExists,
                format!("destination already exists: {}", path.display()),
            ));
        }
        Err(error) if error.kind() == io::ErrorKind::NotFound => {}
        Err(error) => return Err(error),
    }
    let temporary = create_temporary_file(path, mode)?;
    let result = (|| {
        let mut file = temporary.file;
        file.write_all(bytes)?;
        file.flush()?;
        #[cfg(unix)]
        if let Some(mode) = mode {
            set_mode(&file, mode)?;
        }
        file.sync_all()?;
        drop(file);
        rename_new(&temporary.path, path)
    })();
    if result.is_err() {
        let _ = fs::remove_file(&temporary.path);
    }
    result
}

/// Change a payload into an executable without following a link.
pub fn set_executable(path: &Path) -> io::Result<()> {
    ensure_regular_file(path)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt};
        let mut options = OpenOptions::new();
        options.read(true).custom_flags(libc::O_NOFOLLOW);
        let file = options.open(path)?;
        let metadata = file.metadata()?;
        if !metadata.is_file() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("{} is not a regular file", path.display()),
            ));
        }
        if metadata.nlink() > 1 {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                format!(
                    "refusing to change a hard-linked executable {}",
                    path.display()
                ),
            ));
        }
        let mode = metadata.mode() | 0o755;
        file.set_permissions(fs::Permissions::from_mode(mode))?;
    }
    Ok(())
}

/// Atomically switch a Unix selector symlink to an absolute target.  This is not available on
/// Windows because the managed selector there is a regular UTF-8 file.
#[cfg(unix)]
pub fn atomic_switch_symlink(path: &Path, target: &Path) -> io::Result<()> {
    if !target.is_absolute() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "managed selector targets must be absolute",
        ));
    }
    let parent = path.parent().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("{} has no parent directory", path.display()),
        )
    })?;
    ensure_directory(parent)?;
    match fs::symlink_metadata(path) {
        Ok(metadata) if metadata.file_type().is_symlink() => {}
        Ok(_) => {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("{} is not an existing selector symlink", path.display()),
            ));
        }
        Err(error) if error.kind() == io::ErrorKind::NotFound => {}
        Err(error) => return Err(error),
    }

    let temporary = temporary_path(path, "symlink");
    std::os::unix::fs::symlink(target, &temporary)?;
    let result = (|| {
        replace_existing(&temporary, path)?;
        sync_dir(parent)
    })();
    if result.is_err() {
        let _ = fs::remove_file(&temporary);
    }
    result
}

/// Sync a directory after a rename or replacement.  Directory fsync is available on Unix; Windows
/// does not provide a portable directory handle contract, while `MOVEFILE_WRITE_THROUGH` and the
/// synced file cover the supported atomic-replacement path.
pub fn sync_dir(path: &Path) -> io::Result<()> {
    #[cfg(unix)]
    {
        File::open(path)?.sync_all()
    }
    #[cfg(windows)]
    {
        // Windows does not expose a portable directory-fsync operation.  The file itself is
        // flushed before replacement and MoveFileExW uses MOVEFILE_WRITE_THROUGH for the rename;
        // attempting FlushFileBuffers on a directory handle would fail on supported filesystems.
        let _ = path;
        Ok(())
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = path;
        Ok(())
    }
}

/// Rename a newly-created directory without intentionally replacing a prior version.  Callers
/// still check for existence first; the platform-specific no-replace operation prevents ordinary
/// races from silently merging or overwriting a retained version.
pub fn rename_new(source: &Path, destination: &Path) -> io::Result<()> {
    let parent = destination.parent().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("{} has no parent directory", destination.display()),
        )
    })?;
    ensure_directory(parent)?;
    reject_reparse(source)?;
    reject_reparse(destination)?;
    #[cfg(windows)]
    {
        use windows_sys::Win32::Storage::FileSystem::{MOVEFILE_WRITE_THROUGH, MoveFileExW};
        let source_wide = wide_path(source);
        let destination_wide = wide_path(destination);
        let ok = unsafe {
            MoveFileExW(
                source_wide.as_ptr(),
                destination_wide.as_ptr(),
                MOVEFILE_WRITE_THROUGH,
            )
        };
        if ok == 0 {
            return Err(io::Error::last_os_error());
        }
        return sync_dir(parent);
    }
    #[cfg(target_os = "linux")]
    {
        use std::ffi::CString;
        use std::os::unix::ffi::OsStrExt;
        let source_c = CString::new(source.as_os_str().as_bytes())
            .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "source path contains NUL"))?;
        let destination_c = CString::new(destination.as_os_str().as_bytes()).map_err(|_| {
            io::Error::new(io::ErrorKind::InvalidInput, "destination path contains NUL")
        })?;
        let result = unsafe {
            libc::renameat2(
                libc::AT_FDCWD,
                source_c.as_ptr(),
                libc::AT_FDCWD,
                destination_c.as_ptr(),
                libc::RENAME_NOREPLACE,
            )
        };
        if result != 0 {
            let error = io::Error::last_os_error();
            if matches!(
                error.raw_os_error(),
                Some(libc::ENOSYS) | Some(libc::EINVAL)
            ) {
                return Err(io::Error::new(
                    io::ErrorKind::Unsupported,
                    format!("atomic no-replace rename is unavailable: {error}"),
                ));
            }
            return Err(error);
        }
    }
    #[cfg(target_os = "macos")]
    {
        use std::ffi::CString;
        use std::os::unix::ffi::OsStrExt;
        let source_c = CString::new(source.as_os_str().as_bytes())
            .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "source path contains NUL"))?;
        let destination_c = CString::new(destination.as_os_str().as_bytes()).map_err(|_| {
            io::Error::new(io::ErrorKind::InvalidInput, "destination path contains NUL")
        })?;
        let result = unsafe {
            libc::renameatx_np(
                libc::AT_FDCWD,
                source_c.as_ptr(),
                libc::AT_FDCWD,
                destination_c.as_ptr(),
                libc::RENAME_EXCL,
            )
        };
        if result != 0 {
            return Err(io::Error::last_os_error());
        }
    }
    #[cfg(all(unix, not(target_os = "linux"), not(target_os = "macos")))]
    return Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "this Unix target has no supported atomic no-replace rename",
    ));
    #[cfg(unix)]
    {
        sync_dir(parent)?;
        if let Some(source_parent) = source.parent()
            && source_parent != parent
        {
            sync_dir(source_parent)?;
        }
        Ok(())
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = (source, destination, parent);
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "this target has no supported atomic no-replace rename",
        ))
    }
}

fn ensure_directory(path: &Path) -> io::Result<()> {
    let metadata = fs::symlink_metadata(path)?;
    if !metadata.is_dir() || metadata.file_type().is_symlink() || is_reparse_point(path)? {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!("{} is not a real directory", path.display()),
        ));
    }
    Ok(())
}

fn reject_reparse(path: &Path) -> io::Result<()> {
    match fs::symlink_metadata(path) {
        Ok(metadata) if metadata.file_type().is_symlink() || is_reparse_point(path)? => {
            Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                format!("refusing to replace indirection {}", path.display()),
            ))
        }
        Ok(_) => Ok(()),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
        Err(error) => Err(error),
    }
}

#[cfg(windows)]
mod windows_handle {
    use super::*;
    use std::ffi::{OsStr, OsString};
    use std::mem::{size_of, zeroed};
    use std::os::windows::ffi::OsStrExt;
    use std::os::windows::io::{AsRawHandle, FromRawHandle};
    use windows_sys::Wdk::Foundation::OBJECT_ATTRIBUTES;
    use windows_sys::Wdk::Storage::FileSystem::{
        FILE_CREATE, FILE_DIRECTORY_FILE, FILE_NON_DIRECTORY_FILE, FILE_OPEN, FILE_OPEN_IF,
        FILE_OPEN_REPARSE_POINT, FILE_SYNCHRONOUS_IO_NONALERT, NtCreateFile,
    };
    use windows_sys::Win32::Foundation::{
        HANDLE, INVALID_HANDLE_VALUE, RtlNtStatusToDosError, UNICODE_STRING,
    };
    use windows_sys::Win32::Storage::FileSystem::{
        CreateFileW, DELETE, FILE_ATTRIBUTE_NORMAL, FILE_DISPOSITION_INFO,
        FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_GENERIC_READ,
        FILE_GENERIC_WRITE, FILE_ID_INFO, FILE_LIST_DIRECTORY, FILE_READ_ATTRIBUTES,
        FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, FileCaseSensitiveInfo,
        FileDispositionInfo, FileIdInfo, GetFileInformationByHandleEx, OPEN_EXISTING, READ_CONTROL,
        SYNCHRONIZE, SetFileInformationByHandle,
    };
    use windows_sys::Win32::System::IO::IO_STATUS_BLOCK;

    const OBJ_CASE_INSENSITIVE: u32 = 0x40;
    const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
    const SHARE_ALL: u32 = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;

    pub(super) struct LockedRegularFile {
        pub(super) file: File,
        _directories: Vec<File>,
    }

    pub(super) fn open_directory(path: &Path, create: bool) -> io::Result<File> {
        open_directory_with_descriptor(path, create, std::ptr::null_mut())
    }

    /// Walk `path`, optionally creating missing components.
    ///
    /// `security_descriptor` applies to components this call *creates*; Windows ignores it when
    /// `FILE_OPEN_IF` opens an object that already exists, so directories already on disk keep the
    /// permissions they have. That distinction is the point: creating an ancestor with the default
    /// inheritable ACEs, on the way to creating a private leaf, left the engine having built a
    /// directory its own privacy check would later reject - and on Windows the managed root is
    /// exactly such an ancestor the first time anything else under it is created.
    pub(super) fn open_directory_with_descriptor(
        path: &Path,
        create: bool,
        security_descriptor: *mut core::ffi::c_void,
    ) -> io::Result<File> {
        let path = absolute_normalized(path)?;
        let (root, components) = split_root(&path)?;
        let mut directory = open_root(&root, SHARE_ALL)?;
        for component in components {
            directory = open_relative(
                &directory,
                &component,
                FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES | READ_CONTROL | SYNCHRONIZE,
                SHARE_ALL,
                if create { FILE_OPEN_IF } else { FILE_OPEN },
                FILE_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT | FILE_SYNCHRONOUS_IO_NONALERT,
                security_descriptor,
            )?;
            validate_directory(&directory)?;
        }
        Ok(directory)
    }

    pub(super) fn create_private_directory(
        path: &Path,
        security_descriptor: *mut core::ffi::c_void,
    ) -> io::Result<File> {
        let path = absolute_normalized(path)?;
        let parent = path.parent().ok_or_else(|| {
            io::Error::new(io::ErrorKind::InvalidInput, "directory path has no parent")
        })?;
        let filename = path.file_name().ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidInput,
                "directory path has no basename",
            )
        })?;
        // Missing ancestors are created with the same protected descriptor as the leaf. Without it
        // the parent chain lands with the inheritable ACEs of whatever contains it, which is how
        // `%LOCALAPPDATA%\<app>` ended up unprotected the first time an app created a private
        // directory *inside* it.
        let parent = open_directory_with_descriptor(parent, true, security_descriptor)?;
        let directory = open_relative(
            &parent,
            filename,
            FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES | READ_CONTROL | SYNCHRONIZE,
            SHARE_ALL,
            FILE_CREATE,
            FILE_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT | FILE_SYNCHRONOUS_IO_NONALERT,
            security_descriptor,
        )?;
        validate_directory(&directory)?;
        Ok(directory)
    }

    pub(super) fn open_regular(path: &Path) -> io::Result<File> {
        let parent = path
            .parent()
            .filter(|path| !path.as_os_str().is_empty())
            .unwrap_or(Path::new("."));
        let filename = path.file_name().ok_or_else(|| {
            io::Error::new(io::ErrorKind::InvalidInput, "file path has no basename")
        })?;
        let directory = open_directory(parent, false)?;
        let file = open_relative(
            &directory,
            filename,
            FILE_GENERIC_READ | SYNCHRONIZE,
            SHARE_ALL,
            FILE_OPEN,
            FILE_NON_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT | FILE_SYNCHRONOUS_IO_NONALERT,
            std::ptr::null_mut(),
        )?;
        validate_regular(&file)?;
        Ok(file)
    }

    pub(super) fn create_file(directory: &File, filename: &str) -> io::Result<File> {
        let file = open_relative(
            directory,
            OsStr::new(filename),
            FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE | SYNCHRONIZE,
            SHARE_ALL,
            FILE_CREATE,
            FILE_NON_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT | FILE_SYNCHRONOUS_IO_NONALERT,
            std::ptr::null_mut(),
        )?;
        validate_regular(&file)?;
        Ok(file)
    }

    pub(super) fn remove_file(directory: &File, filename: &str) -> io::Result<()> {
        let file = open_relative(
            directory,
            OsStr::new(filename),
            DELETE | SYNCHRONIZE,
            SHARE_ALL,
            FILE_OPEN,
            FILE_NON_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT | FILE_SYNCHRONOUS_IO_NONALERT,
            std::ptr::null_mut(),
        )?;
        validate_regular(&file)?;
        delete_open_file(&file)
    }

    pub(super) fn delete_open_file(file: &File) -> io::Result<()> {
        let disposition = FILE_DISPOSITION_INFO { DeleteFile: 1 };
        let ok = unsafe {
            SetFileInformationByHandle(
                file.as_raw_handle() as HANDLE,
                FileDispositionInfo,
                (&raw const disposition).cast(),
                size_of::<FILE_DISPOSITION_INFO>() as u32,
            )
        };
        if ok == 0 {
            Err(io::Error::last_os_error())
        } else {
            Ok(())
        }
    }

    pub(super) fn lock_regular(path: &Path) -> io::Result<LockedRegularFile> {
        let path = absolute_normalized(path)?;
        let (root, mut components) = split_root(&path)?;
        let filename = components.pop().ok_or_else(|| {
            io::Error::new(io::ErrorKind::InvalidInput, "file path has no basename")
        })?;
        let mut directories = vec![open_root(&root, FILE_SHARE_READ | FILE_SHARE_WRITE)?];
        for component in components {
            let parent = directories.last().expect("root directory handle exists");
            let directory = open_relative(
                parent,
                &component,
                FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES | READ_CONTROL | SYNCHRONIZE,
                FILE_SHARE_READ | FILE_SHARE_WRITE,
                FILE_OPEN,
                FILE_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT | FILE_SYNCHRONOUS_IO_NONALERT,
                std::ptr::null_mut(),
            )?;
            validate_directory(&directory)?;
            directories.push(directory);
        }
        let parent = directories.last().expect("root directory handle exists");
        let file = open_relative(
            parent,
            &filename,
            FILE_GENERIC_READ | SYNCHRONIZE,
            FILE_SHARE_READ,
            FILE_OPEN,
            FILE_NON_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT | FILE_SYNCHRONOUS_IO_NONALERT,
            std::ptr::null_mut(),
        )?;
        validate_regular(&file)?;
        Ok(LockedRegularFile {
            file,
            _directories: directories,
        })
    }

    pub(super) fn same_object(left: &File, right: &File) -> io::Result<bool> {
        fn identity(file: &File) -> io::Result<FILE_ID_INFO> {
            let mut info: FILE_ID_INFO = unsafe { zeroed() };
            let ok = unsafe {
                GetFileInformationByHandleEx(
                    file.as_raw_handle() as HANDLE,
                    FileIdInfo,
                    (&raw mut info).cast(),
                    size_of::<FILE_ID_INFO>() as u32,
                )
            };
            if ok == 0 {
                Err(io::Error::last_os_error())
            } else {
                Ok(info)
            }
        }

        let left = identity(left)?;
        let right = identity(right)?;
        Ok(left.VolumeSerialNumber == right.VolumeSerialNumber
            && left.FileId.Identifier == right.FileId.Identifier)
    }

    pub(super) fn directory_is_case_sensitive(directory: &File) -> io::Result<bool> {
        #[repr(C)]
        struct CaseSensitiveInfo {
            flags: u32,
        }

        let mut info = CaseSensitiveInfo { flags: 0 };
        let ok = unsafe {
            GetFileInformationByHandleEx(
                directory.as_raw_handle() as HANDLE,
                FileCaseSensitiveInfo,
                (&raw mut info).cast(),
                size_of::<CaseSensitiveInfo>() as u32,
            )
        };
        if ok == 0 {
            let error = io::Error::last_os_error();
            if matches!(error.raw_os_error(), Some(50) | Some(87)) {
                return Ok(false);
            }
            return Err(error);
        }
        Ok(info.flags & 1 != 0)
    }

    fn open_relative(
        directory: &File,
        name: &OsStr,
        access: u32,
        share: u32,
        disposition: u32,
        options: u32,
        security_descriptor: *mut core::ffi::c_void,
    ) -> io::Result<File> {
        let mut name = name.encode_wide().collect::<Vec<_>>();
        let byte_len = name
            .len()
            .checked_mul(size_of::<u16>())
            .and_then(|length| u16::try_from(length).ok())
            .ok_or_else(|| {
                io::Error::new(io::ErrorKind::InvalidInput, "path component is too long")
            })?;
        let unicode = UNICODE_STRING {
            Length: byte_len,
            MaximumLength: byte_len,
            Buffer: name.as_mut_ptr(),
        };
        let object_flags = if directory_is_case_sensitive(directory)? {
            0
        } else {
            OBJ_CASE_INSENSITIVE
        };
        let attributes = OBJECT_ATTRIBUTES {
            Length: size_of::<OBJECT_ATTRIBUTES>() as u32,
            RootDirectory: directory.as_raw_handle() as HANDLE,
            ObjectName: &raw const unicode,
            Attributes: object_flags,
            SecurityDescriptor: security_descriptor,
            SecurityQualityOfService: std::ptr::null_mut(),
        };
        let mut status_block: IO_STATUS_BLOCK = unsafe { zeroed() };
        let mut handle: HANDLE = std::ptr::null_mut();
        let status = unsafe {
            NtCreateFile(
                &mut handle,
                access,
                &attributes,
                &mut status_block,
                std::ptr::null(),
                FILE_ATTRIBUTE_NORMAL,
                share,
                disposition,
                options,
                std::ptr::null(),
                0,
            )
        };
        if status < 0 {
            return Err(nt_error(status));
        }
        Ok(unsafe { File::from_raw_handle(handle as _) })
    }

    fn open_root(root: &Path, share: u32) -> io::Result<File> {
        let wide = root
            .as_os_str()
            .encode_wide()
            .chain(std::iter::once(0))
            .collect::<Vec<_>>();
        let handle = unsafe {
            CreateFileW(
                wide.as_ptr(),
                FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES | READ_CONTROL | SYNCHRONIZE,
                share,
                std::ptr::null(),
                OPEN_EXISTING,
                FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
                std::ptr::null_mut(),
            )
        };
        if handle == INVALID_HANDLE_VALUE {
            return Err(io::Error::last_os_error());
        }
        let file = unsafe { File::from_raw_handle(handle as _) };
        validate_directory(&file)?;
        Ok(file)
    }

    fn validate_directory(file: &File) -> io::Result<()> {
        use std::os::windows::fs::MetadataExt;
        let metadata = file.metadata()?;
        if !metadata.is_dir() || metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                "path component is not a real directory",
            ));
        }
        Ok(())
    }

    fn validate_regular(file: &File) -> io::Result<()> {
        use std::os::windows::fs::MetadataExt;
        let metadata = file.metadata()?;
        if !metadata.is_file() || metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                "path is not a regular non-reparse file",
            ));
        }
        Ok(())
    }

    fn absolute_normalized(path: &Path) -> io::Result<PathBuf> {
        use std::path::Component;
        let absolute = if path.is_absolute() {
            path.to_path_buf()
        } else {
            std::env::current_dir()?.join(path)
        };
        let mut normalized = PathBuf::new();
        for component in absolute.components() {
            match component {
                Component::CurDir => {}
                Component::ParentDir => {
                    normalized.pop();
                }
                Component::Prefix(_) | Component::RootDir | Component::Normal(_) => {
                    normalized.push(component.as_os_str());
                }
            }
        }
        Ok(normalized)
    }

    fn split_root(path: &Path) -> io::Result<(PathBuf, Vec<OsString>)> {
        use std::path::Component;
        let mut root = PathBuf::new();
        let mut components = Vec::new();
        for component in path.components() {
            match component {
                Component::Prefix(_) | Component::RootDir if components.is_empty() => {
                    root.push(component.as_os_str());
                }
                Component::Normal(name) => components.push(name.to_os_string()),
                Component::CurDir => {}
                Component::ParentDir => {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "path must not contain '..'",
                    ));
                }
                Component::Prefix(_) | Component::RootDir => {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "invalid rooted path",
                    ));
                }
            }
        }
        if root.as_os_str().is_empty() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "path has no filesystem root",
            ));
        }
        Ok((root, components))
    }

    fn nt_error(status: i32) -> io::Error {
        let code = unsafe { RtlNtStatusToDosError(status) };
        io::Error::from_raw_os_error(code as i32)
    }
}

#[cfg(unix)]
fn open_directory_tree(path: &Path, create: bool) -> io::Result<File> {
    use std::ffi::CString;
    use std::os::fd::{AsRawFd, FromRawFd};
    use std::os::unix::ffi::OsStrExt;
    use std::os::unix::fs::OpenOptionsExt;

    let start = if path.is_absolute() {
        Path::new("/")
    } else {
        Path::new(".")
    };
    let mut directory = OpenOptions::new()
        .read(true)
        .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC)
        .open(start)?;
    for component in path.components() {
        use std::path::Component;
        let name = match component {
            Component::RootDir | Component::CurDir => continue,
            Component::Normal(name) => name,
            Component::ParentDir => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "directory path must not contain '..'",
                ));
            }
            Component::Prefix(_) => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "unsupported directory path prefix",
                ));
            }
        };
        let name = CString::new(name.as_bytes()).map_err(|_| {
            io::Error::new(
                io::ErrorKind::InvalidInput,
                "directory component contains NUL",
            )
        })?;
        let flags = libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC;
        let mut descriptor = unsafe { libc::openat(directory.as_raw_fd(), name.as_ptr(), flags) };
        if descriptor < 0 {
            let error = io::Error::last_os_error();
            if !create || error.kind() != io::ErrorKind::NotFound {
                return Err(error);
            }
            let created = unsafe { libc::mkdirat(directory.as_raw_fd(), name.as_ptr(), 0o700) };
            if created != 0 {
                let create_error = io::Error::last_os_error();
                if create_error.kind() != io::ErrorKind::AlreadyExists {
                    return Err(create_error);
                }
            }
            descriptor = unsafe { libc::openat(directory.as_raw_fd(), name.as_ptr(), flags) };
            if descriptor < 0 {
                return Err(io::Error::last_os_error());
            }
        }
        directory = unsafe { File::from_raw_fd(descriptor) };
        if !directory.metadata()?.is_dir() {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                "directory component is not a directory",
            ));
        }
    }
    Ok(directory)
}

#[cfg(not(any(unix, windows)))]
fn ensure_directory_tree_by_path(path: &Path, create: bool) -> io::Result<()> {
    use std::path::Component;

    let mut current = PathBuf::new();
    for component in path.components() {
        match component {
            Component::Prefix(_) => {
                current.push(component.as_os_str());
                continue;
            }
            Component::RootDir | Component::Normal(_) => current.push(component.as_os_str()),
            Component::CurDir => continue,
            Component::ParentDir => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "directory path must not contain '..'",
                ));
            }
        }
        match fs::symlink_metadata(&current) {
            Ok(metadata)
                if metadata.is_dir()
                    && !metadata.file_type().is_symlink()
                    && !is_reparse_point(&current)? => {}
            Ok(_) => {
                return Err(io::Error::new(
                    io::ErrorKind::PermissionDenied,
                    format!("{} is not a real directory", current.display()),
                ));
            }
            Err(error) if create && error.kind() == io::ErrorKind::NotFound => {
                match fs::create_dir(&current) {
                    Ok(()) => {}
                    Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
                    Err(error) => return Err(error),
                }
                ensure_directory(&current)?;
            }
            Err(error) => return Err(error),
        }
    }
    ensure_directory(path)
}

fn create_new_file_at(
    directory_handle: &File,
    directory: &Path,
    filename: &str,
    bytes: &[u8],
    mode: Option<u32>,
) -> io::Result<PathBuf> {
    if !is_safe_basename(filename, cfg!(windows)) {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "output filename must be a plain basename",
        ));
    }
    #[cfg(unix)]
    {
        create_new_file_at_unix(directory_handle, directory, filename, bytes, mode)
    }
    #[cfg(windows)]
    {
        let _ = mode;
        let output = directory.join(filename);
        let mut file = windows_handle::create_file(directory_handle, filename)?;
        let result = verify_new_file_contents(&mut file, bytes, None);
        if let Err(error) = result {
            let cleanup = windows_handle::delete_open_file(&file);
            return match cleanup {
                Ok(()) => Err(error),
                Err(cleanup) => Err(io::Error::new(
                    error.kind(),
                    format!("{error}; cleanup failed: {cleanup}"),
                )),
            };
        }
        Ok(output)
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = (directory_handle, mode);
        let output = directory.join(filename);
        let mut file = OpenOptions::new()
            .read(true)
            .write(true)
            .create_new(true)
            .open(&output)?;
        verify_new_file_contents(&mut file, bytes, None)?;
        Ok(output)
    }
}

fn remove_file_at(directory: &File, filename: &str) -> io::Result<()> {
    if !is_safe_basename(filename, cfg!(windows)) {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "output filename must be a plain basename",
        ));
    }
    #[cfg(unix)]
    {
        use std::ffi::CString;
        use std::os::fd::AsRawFd;

        let filename = CString::new(filename)
            .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "filename contains NUL"))?;
        if unsafe { libc::unlinkat(directory.as_raw_fd(), filename.as_ptr(), 0) } != 0 {
            return Err(io::Error::last_os_error());
        }
        directory.sync_all()
    }
    #[cfg(windows)]
    {
        windows_handle::remove_file(directory, filename)
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = directory;
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "handle-relative removal is not supported",
        ))
    }
}

#[cfg(unix)]
fn create_new_file_at_unix(
    directory_handle: &File,
    directory: &Path,
    filename: &str,
    bytes: &[u8],
    mode: Option<u32>,
) -> io::Result<PathBuf> {
    use std::ffi::CString;
    use std::os::fd::{AsRawFd, FromRawFd};
    use std::os::unix::fs::{MetadataExt, PermissionsExt};

    let filename_c = CString::new(filename)
        .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "filename contains NUL"))?;
    let descriptor = unsafe {
        libc::openat(
            directory_handle.as_raw_fd(),
            filename_c.as_ptr(),
            libc::O_RDWR | libc::O_CREAT | libc::O_EXCL | libc::O_NOFOLLOW | libc::O_CLOEXEC,
            mode.unwrap_or(0o600),
        )
    };
    if descriptor < 0 {
        return Err(io::Error::last_os_error());
    }
    let mut file = unsafe { File::from_raw_fd(descriptor) };
    let result = (|| {
        let metadata = file.metadata()?;
        if !metadata.is_file() || metadata.nlink() != 1 {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                "new output is not a singly linked regular file",
            ));
        }
        if let Some(mode) = mode {
            file.set_permissions(fs::Permissions::from_mode(mode))?;
        }
        verify_new_file_contents(&mut file, bytes, None)?;
        directory_handle.sync_all()
    })();
    if result.is_err() {
        unsafe {
            libc::unlinkat(directory_handle.as_raw_fd(), filename_c.as_ptr(), 0);
        }
    }
    result.map(|()| directory.join(filename))
}

fn verify_new_file_contents(file: &mut File, bytes: &[u8], mode: Option<u32>) -> io::Result<()> {
    file.write_all(bytes)?;
    file.flush()?;
    #[cfg(unix)]
    if let Some(mode) = mode {
        set_mode(file, mode)?;
    }
    #[cfg(not(unix))]
    let _ = mode;
    file.sync_all()?;
    if file.metadata()?.len() != bytes.len() as u64 {
        return Err(io::Error::other("written file size mismatch"));
    }
    file.seek(SeekFrom::Start(0))?;
    let mut offset = 0;
    let mut buffer = [0u8; 64 * 1024];
    loop {
        let read = file.read(&mut buffer)?;
        if read == 0 {
            break;
        }
        let end = offset + read;
        if bytes.get(offset..end) != Some(&buffer[..read]) {
            return Err(io::Error::other("written file content mismatch"));
        }
        offset = end;
    }
    if offset != bytes.len() {
        return Err(io::Error::other("written file content mismatch"));
    }
    Ok(())
}

struct TemporaryFile {
    path: PathBuf,
    file: File,
}

fn create_temporary_file(path: &Path, mode: Option<u32>) -> io::Result<TemporaryFile> {
    #[cfg(not(unix))]
    let _ = mode;
    let mut last_error = None;
    for _ in 0..32 {
        let temporary = temporary_path(path, "file");
        let mut options = OpenOptions::new();
        options.write(true).create_new(true);
        #[cfg(unix)]
        if let Some(mode) = mode {
            use std::os::unix::fs::OpenOptionsExt;
            options.mode(mode);
        }
        match options.open(&temporary) {
            Ok(file) => {
                return Ok(TemporaryFile {
                    path: temporary,
                    file,
                });
            }
            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => last_error = Some(error),
            Err(error) => return Err(error),
        }
    }
    Err(last_error.unwrap_or_else(|| {
        io::Error::new(
            io::ErrorKind::AlreadyExists,
            format!(
                "could not allocate a temporary path beside {}",
                path.display()
            ),
        )
    }))
}

fn temporary_path(path: &Path, kind: &str) -> PathBuf {
    let counter = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
    let pid = std::process::id();
    let name = path
        .file_name()
        .and_then(|value| value.to_str())
        .unwrap_or("file");
    path.with_file_name(format!(".{name}.{kind}.{pid}.{counter}.tmp"))
}

#[cfg(unix)]
fn set_mode(file: &File, mode: u32) -> io::Result<()> {
    use std::os::unix::fs::PermissionsExt;
    file.set_permissions(fs::Permissions::from_mode(mode))
}

#[cfg(windows)]
fn wide_path(path: &Path) -> Vec<u16> {
    use std::os::windows::ffi::OsStrExt;
    path.as_os_str()
        .encode_wide()
        .chain(std::iter::once(0))
        .collect()
}

#[cfg(windows)]
fn replace_existing(source: &Path, destination: &Path) -> io::Result<()> {
    use std::os::windows::ffi::OsStrExt;
    use windows_sys::Win32::Storage::FileSystem::{
        MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH, MoveFileExW,
    };
    let source_wide = source
        .as_os_str()
        .encode_wide()
        .chain(std::iter::once(0))
        .collect::<Vec<_>>();
    let destination_wide = destination
        .as_os_str()
        .encode_wide()
        .chain(std::iter::once(0))
        .collect::<Vec<_>>();
    let flags = MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH;
    if unsafe { MoveFileExW(source_wide.as_ptr(), destination_wide.as_ptr(), flags) } == 0 {
        Err(io::Error::last_os_error())
    } else {
        Ok(())
    }
}

#[cfg(not(windows))]
fn replace_existing(source: &Path, destination: &Path) -> io::Result<()> {
    fs::rename(source, destination)
}

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

    fn test_temp_dir() -> PathBuf {
        std::env::temp_dir()
            .canonicalize()
            .expect("canonical temporary directory")
    }

    #[test]
    fn atomic_replacement_is_durable_and_replaces_only_regular_files() {
        let root = test_temp_dir().join(format!(
            "hyprmux-executable-test-{}-{}",
            std::process::id(),
            TEMP_COUNTER.fetch_add(1, Ordering::Relaxed)
        ));
        let _ = fs::remove_dir_all(&root);
        fs::create_dir_all(&root).unwrap();
        let path = root.join("state.json");
        atomic_replace_file(&path, b"one").unwrap();
        atomic_replace_file(&path, b"two").unwrap();
        assert_eq!(fs::read(&path).unwrap(), b"two");
        let _ = fs::remove_dir_all(root);
    }

    #[test]
    fn create_new_file_never_replaces_an_existing_path() {
        let root = test_temp_dir().join(format!(
            "hyprmux-executable-create-new-test-{}-{}",
            std::process::id(),
            TEMP_COUNTER.fetch_add(1, Ordering::Relaxed)
        ));
        let _ = fs::remove_dir_all(&root);
        fs::create_dir_all(&root).unwrap();
        let path = root.join("launcher");
        fs::write(&path, b"original").unwrap();

        let error = create_new_file(&path, b"replacement", None).unwrap_err();

        assert_eq!(error.kind(), io::ErrorKind::AlreadyExists);
        assert_eq!(fs::read(&path).unwrap(), b"original");
        let _ = fs::remove_dir_all(root);
    }

    #[test]
    fn rename_new_never_replaces_an_existing_destination() {
        let root = test_temp_dir().join(format!(
            "relswap-executable-rename-new-test-{}-{}",
            std::process::id(),
            TEMP_COUNTER.fetch_add(1, Ordering::Relaxed)
        ));
        let _ = fs::remove_dir_all(&root);
        fs::create_dir_all(&root).unwrap();
        let source = root.join("source");
        let destination = root.join("destination");
        fs::write(&source, b"new").unwrap();
        fs::write(&destination, b"original").unwrap();

        let error = rename_new(&source, &destination).unwrap_err();

        #[cfg(any(windows, target_os = "linux", target_os = "macos"))]
        assert_ne!(error.kind(), io::ErrorKind::Unsupported);
        assert!(
            matches!(
                error.kind(),
                io::ErrorKind::AlreadyExists
                    | io::ErrorKind::PermissionDenied
                    | io::ErrorKind::Unsupported
            ),
            "{error}"
        );
        assert_eq!(fs::read(&destination).unwrap(), b"original");
        assert_eq!(fs::read(&source).unwrap(), b"new");
        let _ = fs::remove_dir_all(root);
    }

    #[cfg(unix)]
    #[test]
    fn handle_relative_create_rejects_symlink_ancestors_and_outputs() {
        use std::os::unix::fs::symlink;

        let root = test_temp_dir().join(format!(
            "relswap-executable-openat-test-{}-{}",
            std::process::id(),
            TEMP_COUNTER.fetch_add(1, Ordering::Relaxed)
        ));
        let _ = fs::remove_dir_all(&root);
        fs::create_dir_all(root.join("real")).unwrap();
        symlink(root.join("real"), root.join("link")).unwrap();
        assert!(
            create_new_file_in_directory(&root.join("link"), "payload", b"new", Some(0o755))
                .is_err()
        );
        assert!(!root.join("real/payload").exists());

        fs::write(root.join("victim"), b"original").unwrap();
        symlink(root.join("victim"), root.join("real/payload")).unwrap();
        assert!(
            create_new_file_in_directory(&root.join("real"), "payload", b"new", Some(0o755))
                .is_err()
        );
        assert_eq!(fs::read(root.join("victim")).unwrap(), b"original");
        let _ = fs::remove_dir_all(root);
    }

    #[cfg(unix)]
    #[test]
    fn retained_directory_detects_path_replacement_and_cleans_original() {
        let root = test_temp_dir().join(format!(
            "relswap-directory-identity-test-{}-{}",
            std::process::id(),
            TEMP_COUNTER.fetch_add(1, Ordering::Relaxed)
        ));
        let destination = root.join("destination");
        let moved = root.join("moved");
        let _ = fs::remove_dir_all(&root);
        fs::create_dir_all(&destination).unwrap();
        let directory = open_output_directory(&destination, false).unwrap();
        fs::rename(&destination, &moved).unwrap();
        fs::create_dir(&destination).unwrap();

        directory
            .create_new_file("payload", b"data", Some(0o755))
            .unwrap();
        assert!(!directory.path_still_identifies_directory().unwrap());
        assert!(moved.join("payload").exists());
        assert!(!destination.join("payload").exists());
        directory.remove_file("payload").unwrap();
        assert!(!moved.join("payload").exists());
        let _ = fs::remove_dir_all(root);
    }

    #[test]
    fn launcher_v1_derives_only_a_canonical_versioned_payload() {
        let launcher = Path::new("/managed/hyprmux/bin/hyprmux.exe");
        assert_eq!(
            resolve_launcher_v1_payload(launcher, b"0.2.0", "hyprmux.exe").unwrap(),
            PathBuf::from("/managed/hyprmux/versions/0.2.0/hyprmux.exe")
        );
        assert!(
            resolve_launcher_v1_payload(
                Path::new("/managed/hyprmux/BIN/hyprmux.exe"),
                b"0.2.0",
                "hyprmux.exe"
            )
            .is_ok()
        );
        for invalid in [
            b"v0.2.0".as_slice(),
            b"0.2.0\n".as_slice(),
            b"../payload".as_slice(),
            b"0.2".as_slice(),
            b"".as_slice(),
        ] {
            assert!(resolve_launcher_v1_payload(launcher, invalid, "hyprmux.exe").is_err());
        }
        assert!(
            resolve_launcher_v1_payload(Path::new("/managed/hyprmux.exe"), b"0.2.0", "hyprmux.exe")
                .is_err()
        );
        assert!(resolve_launcher_v1_payload(launcher, b"0.2.0", "../escape").is_err());
    }

    #[test]
    fn windows_basename_validation_rejects_devices_and_invalid_characters() {
        assert!(is_safe_basename("hyprmux-launcher.exe", true));
        for invalid in [
            "CON.exe",
            "com1",
            "LPT².txt",
            "name:stream",
            "bad?.exe",
            "trailing.",
            "../escape",
        ] {
            assert!(!is_safe_basename(invalid, true), "{invalid}");
        }
    }

    #[test]
    fn secure_open_accepts_a_relative_basename() {
        let file = open_regular_file_secure(Path::new("Cargo.toml")).unwrap();
        assert!(file.metadata().unwrap().is_file());
    }

    #[cfg(unix)]
    #[test]
    fn secure_open_rejects_a_fifo_without_blocking() {
        use std::ffi::CString;
        use std::os::unix::ffi::OsStrExt;

        let path = test_temp_dir().join(format!(
            "relswap-executable-fifo-test-{}-{}",
            std::process::id(),
            TEMP_COUNTER.fetch_add(1, Ordering::Relaxed)
        ));
        let path_c = CString::new(path.as_os_str().as_bytes()).unwrap();
        assert_eq!(unsafe { libc::mkfifo(path_c.as_ptr(), 0o600) }, 0);
        let started = std::time::Instant::now();

        assert!(open_regular_file_secure(&path).is_err());
        assert!(started.elapsed() < std::time::Duration::from_secs(1));
        let _ = fs::remove_file(path);
    }

    #[cfg(unix)]
    #[test]
    fn symlink_switch_is_absolute_and_atomic() {
        let root = test_temp_dir().join(format!(
            "hyprmux-executable-link-test-{}-{}",
            std::process::id(),
            TEMP_COUNTER.fetch_add(1, Ordering::Relaxed)
        ));
        let _ = fs::remove_dir_all(&root);
        fs::create_dir_all(&root).unwrap();
        let target = root.join("payload");
        fs::write(&target, b"payload").unwrap();
        let pointer = root.join("hyprmux");
        atomic_switch_symlink(&pointer, &target).unwrap();
        assert_eq!(read_symlink(&pointer).unwrap(), Some(target));
        let _ = fs::remove_dir_all(root);
    }
}