iron-shell 14.0.3

The world's first multi-agent shell with typed functional pipelines and multi-modal AI
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
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
//! systemd service creation and deletion, and non-interactive sudo.
//!
//! Linux, Windows and macOS. Argument validation runs on every platform, so a
//! malformed call is refused the same way everywhere. `svc_create` and
//! `svc_delete` act on systemd units on Linux, Service Control Manager services
//! on Windows, and launchd LaunchDaemons on macOS. For `sudo_exec` on any other
//! platform, a valid call refuses with E_UNIMPLEMENTED and changes nothing.
//!
//! `svc_create` writes `/etc/systemd/system/ironshell-<name>.service`, tagged with a
//! marker line on its first line. `svc_delete` removes only units that carry
//! that marker, so the `ae-` namespace cannot reach hand-written units.
//! `sudo_exec` runs `sudo -n -- argv...` on Linux and macOS and never prompts
//! for a password. On Windows it runs argv directly, and only when this process
//! is already elevated: Windows can elevate only through a UAC prompt, which
//! IronShell never shows, so a process that is not elevated is refused.

use crate::value::Value;
use anyhow::Result;
use std::collections::BTreeMap;

/// Written as the first line of every unit this module creates.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
const MARKER: &str =
    "# Created by IronShell svc_create; svc_delete removes only units carrying this line";
const UNIT_PREFIX: &str = "ironshell-";
const MAX_ARGV: usize = 256;
const MAX_ARG_BYTES: usize = 4096;
const MAX_DESCRIPTION_BYTES: usize = 256;
const SUDO_TIMEOUT_MIN_MS: i64 = 100;
const SUDO_TIMEOUT_MAX_MS: i64 = 600_000;
const SUDO_TIMEOUT_DEFAULT_MS: u64 = 60_000;
/// Each of stdout and stderr keeps only its last this many bytes.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
const OUTPUT_TAIL_BYTES: usize = 64 * 1024;

const NAME_RULE: &str = "a name matching ^[a-z0-9][a-z0-9_-]{0,63}$";

fn valid_name(name: &str) -> bool {
    let bytes = name.as_bytes();
    !bytes.is_empty()
        && bytes.len() <= 64
        && (bytes[0].is_ascii_lowercase() || bytes[0].is_ascii_digit())
        && bytes[1..]
            .iter()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'_' || *c == b'-')
}

fn name_arg(builtin: &str, value: &Value) -> Result<String> {
    match value {
        Value::Str(s) if valid_name(s) => Ok(s.clone()),
        Value::Str(s) => Err(crate::safety::bad_arg(
            builtin,
            NAME_RULE,
            &format!("{s:?}"),
        )),
        other => Err(crate::safety::bad_arg(
            builtin,
            "a String name",
            other.type_name(),
        )),
    }
}

fn arity(builtin: &str, args: &[Value], min: usize, max: usize, shape: &str) -> Result<()> {
    if args.len() < min || args.len() > max {
        return Err(crate::safety::bad_arg(
            builtin,
            shape,
            &format!("{} arguments", args.len()),
        ));
    }
    Ok(())
}

fn no_pipeline_input(builtin: &str, input: &Option<Value>) -> Result<()> {
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            builtin,
            "no pipeline input",
            "pipeline input",
        ));
    }
    Ok(())
}

/// Options must be a Record whose keys are all in `allowed`. Absent options
/// are an empty map.
fn options_arg(
    builtin: &str,
    value: Option<&Value>,
    allowed: &[&str],
    shape: &str,
) -> Result<BTreeMap<String, Value>> {
    match value {
        None => Ok(BTreeMap::new()),
        Some(Value::Record(map)) => {
            if let Some(key) = map.keys().find(|k| !allowed.contains(&k.as_str())) {
                return Err(crate::safety::bad_arg(
                    builtin,
                    shape,
                    &format!("unknown option {key:?}"),
                ));
            }
            Ok(map.clone())
        }
        Some(other) => Err(crate::safety::bad_arg(builtin, shape, other.type_name())),
    }
}

fn bool_option(builtin: &str, map: &BTreeMap<String, Value>, key: &str) -> Result<bool> {
    match map.get(key) {
        None => Ok(false),
        Some(Value::Bool(b)) => Ok(*b),
        Some(other) => Err(crate::safety::bad_arg(
            builtin,
            &format!("{key} as a Bool"),
            other.type_name(),
        )),
    }
}

/// Parse an argv Array. `argv[0]` is validated by the caller; every element
/// must be a String without NUL, and within the length limits.
fn argv_arg(builtin: &str, value: &Value, shape: &str) -> Result<Vec<String>> {
    let Value::Array(items) = value else {
        return Err(crate::safety::bad_arg(builtin, shape, value.type_name()));
    };
    if items.is_empty() || items.len() > MAX_ARGV {
        return Err(crate::safety::bad_arg(
            builtin,
            &format!("{shape} with 1 to {MAX_ARGV} elements"),
            &format!("{} elements", items.len()),
        ));
    }
    let mut argv = Vec::with_capacity(items.len());
    for item in items {
        let Value::Str(s) = item else {
            return Err(crate::safety::bad_arg(
                builtin,
                "String elements",
                item.type_name(),
            ));
        };
        if s.contains('\0') || s.len() > MAX_ARG_BYTES {
            return Err(crate::safety::bad_arg(
                builtin,
                &format!("arguments without NUL and at most {MAX_ARG_BYTES} bytes"),
                &format!("an argument of {} bytes", s.len()),
            ));
        }
        argv.push(s.clone());
    }
    Ok(argv)
}

/// Transactions cannot roll back a service or privilege change, so a call
/// inside one is refused before it does anything.
fn refuse_in_transaction(builtin: &str) -> Result<()> {
    if crate::tx::is_active() {
        return Err(crate::safety::policy_deny(
            builtin,
            format!(
                "{builtin}: refusing inside a transaction: service and sudo effects cannot be rolled back"
            ),
            "run it outside the transaction, after commit or rollback",
        ));
    }
    Ok(())
}

#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
fn not_linux(builtin: &str) -> anyhow::Error {
    crate::safety::unimplemented(
        builtin,
        "service creation, service deletion and sudo_exec are implemented on Linux, macOS and Windows only; NOTHING WAS CHANGED",
        "use the platform's own service manager or `sudo` directly",
    )
}

// ── svc_create ───────────────────────────────────────────────────────────────

#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
struct CreateSpec {
    name: String,
    argv: Vec<String>,
    description: String,
    user: Option<String>,
    restart: &'static str,
    enable: bool,
    start: bool,
}

fn parse_create(args: &[Value], input: &Option<Value>) -> Result<CreateSpec> {
    const BUILTIN: &str = "svc_create";
    arity(
        BUILTIN,
        args,
        2,
        3,
        "2 or 3 arguments (name, command, options?)",
    )?;
    no_pipeline_input(BUILTIN, input)?;
    let name = name_arg(BUILTIN, &args[0])?;
    let argv = argv_arg(BUILTIN, &args[1], "an Array of String argv")?;
    let first = &argv[0];
    if !absolute_program(first) {
        return Err(crate::safety::bad_arg(
            BUILTIN,
            "an absolute path as argv[0]",
            &format!("{first:?}"),
        ));
    }
    windows_program_alone(BUILTIN, &argv)?;
    for arg in &argv {
        if arg.contains(['\n', '\r', '%']) {
            return Err(crate::safety::bad_arg(
                BUILTIN,
                "arguments without newline, carriage return or '%'",
                &format!("{arg:?}"),
            ));
        }
    }
    let map = options_arg(
        BUILTIN,
        args.get(2),
        &["description", "user", "restart", "enable", "start"],
        "options {description?, user?, restart?, enable?, start?}",
    )?;
    let description = match map.get("description") {
        None => format!("IronShell service {UNIT_PREFIX}{name}"),
        Some(Value::Str(d))
            if !d.is_empty()
                && d.len() <= MAX_DESCRIPTION_BYTES
                && !d.contains(['\n', '\r', '\0']) =>
        {
            d.clone()
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                BUILTIN,
                "description as a non-empty single-line String of at most 256 bytes",
                other.type_name(),
            ))
        }
    };
    let user = match map.get("user") {
        None => None,
        Some(Value::Str(u)) if valid_account_name(u) => Some(u.clone()),
        Some(Value::Str(u)) => {
            return Err(crate::safety::bad_arg(
                BUILTIN,
                "user as an account name (^[a-z_][a-z0-9_-]{0,31}$)",
                &format!("{u:?}"),
            ))
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                BUILTIN,
                "user as an account name (^[a-z_][a-z0-9_-]{0,31}$)",
                other.type_name(),
            ))
        }
    };
    let restart = match map.get("restart") {
        None => "no",
        Some(Value::Str(r)) if r == "no" => "no",
        Some(Value::Str(r)) if r == "on-failure" => "on-failure",
        Some(Value::Str(r)) if r == "always" => "always",
        Some(Value::Str(r)) => {
            return Err(crate::safety::bad_arg(
                BUILTIN,
                "restart as \"no\", \"on-failure\" or \"always\"",
                &format!("{r:?}"),
            ))
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                BUILTIN,
                "restart as \"no\", \"on-failure\" or \"always\"",
                other.type_name(),
            ))
        }
    };
    Ok(CreateSpec {
        name,
        argv,
        description,
        user,
        restart,
        enable: bool_option(BUILTIN, &map, "enable")?,
        start: bool_option(BUILTIN, &map, "start")?,
    })
}

/// Whether argv[0] is an absolute program path on this platform: a leading `/`
/// on Unix, a drive-letter or UNC path on Windows. On Windows a path containing
/// a double quote is refused, since the quote is what delimits the binary path.
fn absolute_program(path: &str) -> bool {
    if cfg!(windows) {
        std::path::Path::new(path).is_absolute() && !path.contains('"')
    } else {
        path.starts_with('/') && path.len() >= 2
    }
}

/// A Windows service runs one program. Its binary path is built from argv[0]
/// alone, so extra arguments are refused rather than joined into a command line.
fn windows_program_alone(builtin: &str, argv: &[String]) -> Result<()> {
    if cfg!(windows) && argv.len() > 1 {
        return Err(crate::safety::bad_arg(
            builtin,
            "argv holding the program alone on Windows: a service takes no arguments in this release",
            &format!("{} elements", argv.len()),
        ));
    }
    Ok(())
}

fn valid_account_name(name: &str) -> bool {
    let bytes = name.as_bytes();
    !bytes.is_empty()
        && bytes.len() <= 32
        && (bytes[0].is_ascii_lowercase() || bytes[0] == b'_')
        && bytes[1..]
            .iter()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'_' || *c == b'-')
}

#[cfg(target_os = "linux")]
pub(crate) fn svc_create(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let spec = parse_create(&args, &input)?;
    refuse_in_transaction("svc_create")?;
    linux::create(spec)
}

#[cfg(windows)]
pub(crate) fn svc_create(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let spec = parse_create(&args, &input)?;
    refuse_in_transaction("svc_create")?;
    scm::create(spec)
}

#[cfg(target_os = "macos")]
pub(crate) fn svc_create(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let spec = parse_create(&args, &input)?;
    refuse_in_transaction("svc_create")?;
    launchd::create(spec)
}

#[cfg(not(any(target_os = "linux", windows, target_os = "macos")))]
pub(crate) fn svc_create(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    parse_create(&args, &input)?;
    refuse_in_transaction("svc_create")?;
    Err(not_linux("svc_create"))
}

// ── svc_delete ───────────────────────────────────────────────────────────────

fn parse_delete(args: &[Value], input: &Option<Value>) -> Result<String> {
    const BUILTIN: &str = "svc_delete";
    arity(BUILTIN, args, 1, 1, "1 argument (name)")?;
    no_pipeline_input(BUILTIN, input)?;
    name_arg(BUILTIN, &args[0])
}

#[cfg(target_os = "linux")]
pub(crate) fn svc_delete(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let name = parse_delete(&args, &input)?;
    refuse_in_transaction("svc_delete")?;
    linux::delete(name)
}

#[cfg(windows)]
pub(crate) fn svc_delete(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let name = parse_delete(&args, &input)?;
    refuse_in_transaction("svc_delete")?;
    scm::delete(name)
}

#[cfg(target_os = "macos")]
pub(crate) fn svc_delete(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let name = parse_delete(&args, &input)?;
    refuse_in_transaction("svc_delete")?;
    launchd::delete(name)
}

#[cfg(not(any(target_os = "linux", windows, target_os = "macos")))]
pub(crate) fn svc_delete(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    parse_delete(&args, &input)?;
    refuse_in_transaction("svc_delete")?;
    Err(not_linux("svc_delete"))
}

// ── sudo_exec ────────────────────────────────────────────────────────────────

#[cfg_attr(
    not(any(target_os = "linux", target_os = "macos", windows)),
    allow(dead_code)
)]
struct SudoSpec {
    argv: Vec<String>,
    timeout_ms: u64,
}

fn parse_sudo(args: &[Value], input: &Option<Value>) -> Result<SudoSpec> {
    const BUILTIN: &str = "sudo_exec";
    arity(BUILTIN, args, 1, 2, "1 or 2 arguments (command, options?)")?;
    no_pipeline_input(BUILTIN, input)?;
    let argv = argv_arg(BUILTIN, &args[0], "an Array of String argv")?;
    if argv[0].is_empty() || argv[0].starts_with('-') {
        return Err(crate::safety::bad_arg(
            BUILTIN,
            "an argv[0] that is non-empty and does not start with '-'",
            &format!("{:?}", argv[0]),
        ));
    }
    let map = options_arg(
        BUILTIN,
        args.get(1),
        &["timeout_ms"],
        "options {timeout_ms?}",
    )?;
    let timeout_ms = match map.get("timeout_ms") {
        None => SUDO_TIMEOUT_DEFAULT_MS,
        Some(Value::Int(n)) if (SUDO_TIMEOUT_MIN_MS..=SUDO_TIMEOUT_MAX_MS).contains(n) => *n as u64,
        Some(Value::Int(n)) => {
            return Err(crate::safety::bad_arg(
                BUILTIN,
                "timeout_ms as an Int from 100 to 600000",
                &n.to_string(),
            ))
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                BUILTIN,
                "timeout_ms as an Int from 100 to 600000",
                other.type_name(),
            ))
        }
    };
    Ok(SudoSpec { argv, timeout_ms })
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
pub(crate) fn sudo_exec(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let spec = parse_sudo(&args, &input)?;
    refuse_in_transaction("sudo_exec")?;
    unix_sudo::sudo(spec)
}

#[cfg(windows)]
pub(crate) fn sudo_exec(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let spec = parse_sudo(&args, &input)?;
    refuse_in_transaction("sudo_exec")?;
    win_sudo::sudo(spec)
}

#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
pub(crate) fn sudo_exec(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    parse_sudo(&args, &input)?;
    refuse_in_transaction("sudo_exec")?;
    Err(not_linux("sudo_exec"))
}

// ── sudo_exec (Linux and macOS) ─────────────────────────────────────────────

/// `sudo -n` with a deadline, in its own process group so a timeout kill also
/// reaches the command sudo ran. The same code serves Linux and macOS, whose
/// sudo is at the same path and words the password refusal the same way.
#[cfg(any(target_os = "linux", target_os = "macos"))]
mod unix_sudo {
    use super::*;
    use crate::safety::{policy_deny, spawn_error};
    use std::io::{ErrorKind, Read};
    use std::process::Stdio;
    use std::sync::{Arc, Mutex, MutexGuard};
    use std::time::{Duration, Instant};

    const SUDO: &str = "/usr/bin/sudo";

    /// True when sudo refused because it would have to ask for a password.
    /// Matched on a whole line, so a command that merely mentions the phrase
    /// inside a longer message does not trip it.
    pub(super) fn sudo_password_required(stderr: &str) -> bool {
        stderr
            .lines()
            .any(|line| line.trim() == "sudo: a password is required")
    }

    #[derive(Default)]
    struct Capture {
        bytes: Vec<u8>,
        finished: bool,
    }

    type Shared = Arc<Mutex<Capture>>;

    fn lock(shared: &Shared) -> MutexGuard<'_, Capture> {
        shared
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    /// Reads a pipe until EOF, keeping only the most recent output. The
    /// buffer is shared so the caller can read it even when a grandchild
    /// holds the pipe open after the timeout kill.
    fn spawn_reader<R: Read + Send + 'static>(mut pipe: R, shared: Shared) {
        std::thread::spawn(move || {
            let mut chunk = [0u8; 8192];
            loop {
                match pipe.read(&mut chunk) {
                    Ok(0) => break,
                    Ok(n) => {
                        let mut capture = lock(&shared);
                        capture.bytes.extend_from_slice(&chunk[..n]);
                        if capture.bytes.len() > 2 * OUTPUT_TAIL_BYTES {
                            let cut = capture.bytes.len() - OUTPUT_TAIL_BYTES;
                            capture.bytes.drain(..cut);
                        }
                    }
                    Err(e) if e.kind() == ErrorKind::Interrupted => continue,
                    Err(_) => break,
                }
            }
            lock(&shared).finished = true;
        });
    }

    fn tail_text(shared: &Shared) -> String {
        let capture = lock(shared);
        let start = capture.bytes.len().saturating_sub(OUTPUT_TAIL_BYTES);
        String::from_utf8_lossy(&capture.bytes[start..]).into_owned()
    }

    fn finished(shared: &Shared) -> bool {
        lock(shared).finished
    }

    /// SIGKILL the child's whole process group. The child was started as a
    /// group leader, so this also reaches the command that sudo ran.
    fn kill_group(pid: u32) {
        // SAFETY: plain libc call with a negated pid; it signals a process group
        // this function created, and has no memory effects.
        unsafe {
            libc::kill(-(pid as libc::pid_t), libc::SIGKILL);
        }
    }

    pub(super) fn sudo(spec: SudoSpec) -> Result<Value> {
        use std::os::unix::process::CommandExt;

        const BUILTIN: &str = "sudo_exec";
        let mut cmd = crate::safety::child_command(SUDO);
        crate::safety::strip_ironshell_env(&mut cmd);
        cmd.arg("-n")
            .arg("--")
            .args(&spec.argv)
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .process_group(0);
        let mut child = cmd.spawn().map_err(|e| spawn_error(BUILTIN, "sudo", &e))?;

        let stdout = Arc::new(Mutex::new(Capture::default()));
        let stderr = Arc::new(Mutex::new(Capture::default()));
        if let Some(pipe) = child.stdout.take() {
            spawn_reader(pipe, Arc::clone(&stdout));
        } else {
            lock(&stdout).finished = true;
        }
        if let Some(pipe) = child.stderr.take() {
            spawn_reader(pipe, Arc::clone(&stderr));
        } else {
            lock(&stderr).finished = true;
        }

        let deadline = Instant::now() + Duration::from_millis(spec.timeout_ms);
        let (status, timed_out) = loop {
            match child.try_wait() {
                Ok(Some(status)) => break (Some(status), false),
                Ok(None) if Instant::now() >= deadline => {
                    kill_group(child.id());
                    let _ = child.kill();
                    break (child.wait().ok(), true);
                }
                Ok(None) => std::thread::sleep(Duration::from_millis(10)),
                Err(e) => {
                    kill_group(child.id());
                    let _ = child.kill();
                    return Err(spawn_error(BUILTIN, "sudo", &e));
                }
            }
        };

        // Give the readers a moment to reach EOF. A grandchild that keeps a pipe
        // open must not hold the call indefinitely.
        let grace = Instant::now() + Duration::from_secs(2);
        while !(finished(&stdout) && finished(&stderr)) && Instant::now() < grace {
            std::thread::sleep(Duration::from_millis(10));
        }

        let stdout_text = tail_text(&stdout);
        let stderr_text = tail_text(&stderr);
        if !timed_out && sudo_password_required(&stderr_text) {
            return Err(policy_deny(
                BUILTIN,
                format!("{BUILTIN}: sudo needs a password for this user, so the command was not run"),
                "run it as root, or grant this command NOPASSWD in sudoers; IronShell never supplies a password",
            ));
        }

        let exit_code = match status.and_then(|s| s.code()) {
            Some(code) if !timed_out => Value::Int(i64::from(code)),
            _ => Value::Null,
        };
        let mut record = BTreeMap::new();
        record.insert("exit_code".to_string(), exit_code);
        record.insert("stdout".to_string(), Value::Str(stdout_text));
        record.insert("stderr".to_string(), Value::Str(stderr_text));
        record.insert("timed_out".to_string(), Value::Bool(timed_out));
        Ok(Value::Record(record))
    }

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

        #[test]
        fn password_prompt_is_recognised_only_as_a_whole_line() {
            assert!(sudo_password_required("sudo: a password is required\n"));
            assert!(sudo_password_required("  sudo: a password is required  \n"));
            assert!(!sudo_password_required(
                "the tool said: sudo: a password is required, really\n"
            ));
            assert!(!sudo_password_required(
                "sudo: a terminal is required to read the password\n"
            ));
            assert!(!sudo_password_required(""));
        }
    }
}

// ── sudo_exec (Windows) ─────────────────────────────────────────────────────

/// Runs argv directly, and only in a process that is already elevated. Windows
/// has no `sudo -n`: a process gets an elevated token only through a UAC consent
/// prompt, and IronShell never prompts, so an unelevated process is refused
/// before anything runs. Nothing here starts `runas`, `Start-Process -Verb
/// RunAs` or `sudo.exe`. The run goes through the bounded tree runner the
/// builtins share, so a timeout kills the command's descendants too (a job
/// object, then `taskkill /T`).
#[cfg(windows)]
mod win_sudo {
    use super::*;
    use crate::builtins::{run_tree_cmd, windows_is_admin, Keep, TreeError};
    use crate::safety::{policy_deny, spawn_error};
    use std::path::Path;
    use std::time::Duration;

    pub(super) fn sudo(spec: SudoSpec) -> Result<Value> {
        const BUILTIN: &str = "sudo_exec";
        let program = spec.argv[0].clone();
        if !Path::new(&program).is_absolute() {
            return Err(crate::safety::bad_arg(
                BUILTIN,
                r"an argv[0] that is an absolute path, such as C:\Windows\System32\whoami.exe",
                &format!("{program:?}"),
            ));
        }
        // Rust starts a .bat or .cmd file through cmd.exe, which re-parses its
        // arguments: a shell after all, and the BatBadBut injection class. A
        // batch file is refused; run cmd.exe by its path to mean it.
        let batch = Path::new(&program)
            .extension()
            .and_then(|e| e.to_str())
            .is_some_and(|e| e.eq_ignore_ascii_case("bat") || e.eq_ignore_ascii_case("cmd"));
        if batch {
            return Err(crate::safety::bad_arg(
                BUILTIN,
                r"an argv[0] that is a program, not a .bat or .cmd file (run C:\Windows\System32\cmd.exe with /c to mean a batch file)",
                &format!("{program:?}"),
            ));
        }
        if !windows_is_admin(BUILTIN)? {
            return Err(policy_deny(
                BUILTIN,
                "sudo_exec: this process is not elevated and Windows elevates only through a UAC prompt, so the command was not run",
                "start ish from an elevated terminal (Run as administrator); IronShell never shows a UAC prompt",
            ));
        }

        let mut command = crate::safety::child_command(&program);
        command.args(&spec.argv[1..]);
        let run = run_tree_cmd(
            command,
            None,
            Duration::from_millis(spec.timeout_ms),
            Keep::Tail(OUTPUT_TAIL_BYTES),
            Keep::Tail(OUTPUT_TAIL_BYTES),
        )
        .map_err(|e| match e {
            TreeError::Spawn(e) | TreeError::Wait(e) => spawn_error(BUILTIN, &program, &e),
        })?;

        let exit_code = match run.code {
            Some(code) if !run.timed_out => Value::Int(i64::from(code)),
            _ => Value::Null,
        };
        let mut record = BTreeMap::new();
        record.insert("exit_code".to_string(), exit_code);
        record.insert(
            "stdout".to_string(),
            Value::Str(String::from_utf8_lossy(&run.stdout).into_owned()),
        );
        record.insert(
            "stderr".to_string(),
            Value::Str(String::from_utf8_lossy(&run.stderr).into_owned()),
        );
        record.insert("timed_out".to_string(), Value::Bool(run.timed_out));
        Ok(Value::Record(record))
    }
}

// ── Windows backend ─────────────────────────────────────────────────────────

/// The Service Control Manager, called through advapi32. A service has no unit
/// file, so the marker `svc_delete` checks for is the start of the service's
/// description: every description this module writes begins with it.
#[cfg(windows)]
mod scm {
    use super::*;
    use crate::safety::{bad_state_with_hint, budget_exceeded, not_found, os_denied, policy_deny};
    use std::ffi::c_void;
    use std::ptr::{null, null_mut};
    use std::time::{Duration, Instant};

    const WIN_MARKER: &str = "[IronShell svc_create] ";
    /// How long `svc_delete` waits for a running service to report stopped.
    const STOP_WAIT: Duration = Duration::from_secs(30);
    /// Delay before each of the three restarts that `restart: "on-failure"` sets.
    const RESTART_DELAY_MS: u32 = 60_000;
    /// Delay before each of the three restarts that `restart: "always"` sets. The
    /// Linux unit sets no RestartSec, so systemd's default applies there; the
    /// same 1000 ms is used here.
    const ALWAYS_RESTART_DELAY_MS: u32 = 1_000;
    /// The failure count starts again after a day without a failure.
    const RESET_PERIOD_SECS: u32 = 86_400;

    #[link(name = "advapi32")]
    extern "system" {
        fn OpenSCManagerW(machine: *const u16, database: *const u16, access: u32) -> *mut c_void;
        fn OpenServiceW(scm: *mut c_void, name: *const u16, access: u32) -> *mut c_void;
        #[allow(clippy::too_many_arguments)]
        fn CreateServiceW(
            scm: *mut c_void,
            name: *const u16,
            display: *const u16,
            access: u32,
            service_type: u32,
            start_type: u32,
            error_control: u32,
            binary_path: *const u16,
            load_order_group: *const u16,
            tag_id: *mut u32,
            dependencies: *const u16,
            start_name: *const u16,
            password: *const u16,
        ) -> *mut c_void;
        fn ChangeServiceConfig2W(service: *mut c_void, level: u32, info: *mut c_void) -> i32;
        fn QueryServiceConfigW(
            service: *mut c_void,
            config: *mut c_void,
            size: u32,
            needed: *mut u32,
        ) -> i32;
        fn QueryServiceConfig2W(
            service: *mut c_void,
            level: u32,
            buffer: *mut c_void,
            size: u32,
            needed: *mut u32,
        ) -> i32;
        fn QueryServiceStatusEx(
            service: *mut c_void,
            level: u32,
            buffer: *mut c_void,
            size: u32,
            needed: *mut u32,
        ) -> i32;
        fn StartServiceW(service: *mut c_void, argc: u32, argv: *const *const u16) -> i32;
        fn ControlService(service: *mut c_void, control: u32, status: *mut c_void) -> i32;
        fn DeleteService(service: *mut c_void) -> i32;
        fn CloseServiceHandle(handle: *mut c_void) -> i32;
    }

    const SC_MANAGER_CONNECT: u32 = 0x0001;
    const SC_MANAGER_CREATE_SERVICE: u32 = 0x0002;
    const SERVICE_QUERY_CONFIG: u32 = 0x0001;
    const SERVICE_CHANGE_CONFIG: u32 = 0x0002;
    const SERVICE_QUERY_STATUS: u32 = 0x0004;
    const SERVICE_START: u32 = 0x0010;
    const SERVICE_STOP: u32 = 0x0020;
    const DELETE: u32 = 0x0001_0000;
    /// The access a created service's handle needs for the calls that follow.
    const SERVICE_RIGHTS: u32 =
        SERVICE_CHANGE_CONFIG | SERVICE_QUERY_STATUS | SERVICE_START | SERVICE_STOP | DELETE;
    const SERVICE_WIN32_OWN_PROCESS: u32 = 0x10;
    const SERVICE_AUTO_START: u32 = 2;
    const SERVICE_DEMAND_START: u32 = 3;
    const SERVICE_DISABLED: u32 = 4;
    const SERVICE_ERROR_NORMAL: u32 = 1;
    const SERVICE_CONTROL_STOP: u32 = 1;
    const SERVICE_STOPPED: u32 = 1;
    const SC_STATUS_PROCESS_INFO: u32 = 0;
    const SERVICE_CONFIG_DESCRIPTION: u32 = 1;
    const SERVICE_CONFIG_FAILURE_ACTIONS: u32 = 2;
    const SERVICE_CONFIG_FAILURE_ACTIONS_FLAG: u32 = 4;
    const SC_ACTION_RESTART: u32 = 1;

    const ERROR_ACCESS_DENIED: u32 = 5;
    const ERROR_INSUFFICIENT_BUFFER: u32 = 122;
    const ERROR_SERVICE_DOES_NOT_EXIST: u32 = 1060;
    const ERROR_SERVICE_CANNOT_ACCEPT_CTRL: u32 = 1061;
    const ERROR_SERVICE_NOT_ACTIVE: u32 = 1062;
    const ERROR_SERVICE_MARKED_FOR_DELETE: u32 = 1072;
    const ERROR_SERVICE_EXISTS: u32 = 1073;
    const ERROR_DUPLICATE_SERVICE_NAME: u32 = 1078;
    const ERROR_INVALID_SERVICE_ACCOUNT: u32 = 1057;
    const ERROR_SERVICE_LOGON_FAILED: u32 = 1069;
    const ERROR_LOGON_FAILURE: u32 = 1326;

    /// SERVICE_STATUS_PROCESS, the buffer QueryServiceStatusEx fills.
    #[allow(dead_code)]
    #[derive(Default)]
    #[repr(C)]
    struct ServiceStatusProcess {
        service_type: u32,
        current_state: u32,
        controls_accepted: u32,
        win32_exit_code: u32,
        service_specific_exit_code: u32,
        check_point: u32,
        wait_hint: u32,
        process_id: u32,
        service_flags: u32,
    }

    /// The start of QUERY_SERVICE_CONFIGW; only the start type is read.
    #[allow(dead_code)]
    #[repr(C)]
    struct QueryConfig {
        service_type: u32,
        start_type: u32,
        error_control: u32,
        binary_path: *mut u16,
        load_order_group: *mut u16,
        tag_id: u32,
        dependencies: *mut u16,
        start_name: *mut u16,
        display_name: *mut u16,
    }

    #[allow(dead_code)]
    #[repr(C)]
    struct ServiceDescriptionW {
        description: *mut u16,
    }

    #[allow(dead_code)]
    #[derive(Clone, Copy)]
    #[repr(C)]
    struct ScAction {
        kind: u32,
        delay_ms: u32,
    }

    #[allow(dead_code)]
    #[repr(C)]
    struct ServiceFailureActionsW {
        reset_period: u32,
        reboot_message: *mut u16,
        command: *mut u16,
        count: u32,
        actions: *mut ScAction,
    }

    #[allow(dead_code)]
    #[repr(C)]
    struct ServiceFailureFlag {
        on_non_crash_failures: i32,
    }

    /// An open SCM or service handle, closed when it goes out of scope.
    struct Handle(*mut c_void);

    impl Drop for Handle {
        fn drop(&mut self) {
            // SAFETY: the handle came from a successful Open or Create call and
            // is closed exactly once, here.
            unsafe { CloseServiceHandle(self.0) };
        }
    }

    fn wide(text: &str) -> Vec<u16> {
        text.encode_utf16().chain(std::iter::once(0)).collect()
    }

    fn last_error() -> u32 {
        std::io::Error::last_os_error().raw_os_error().unwrap_or(0) as u32
    }

    /// Maps a failed service-control call to a coded error. Nothing is changed
    /// by a call that fails, so each arm only names the cause.
    fn scm_error(builtin: &str, call: &str, code: u32, service: &str) -> anyhow::Error {
        let win = std::io::Error::from_raw_os_error(code as i32);
        match code {
            ERROR_ACCESS_DENIED => os_denied(
                builtin,
                format!("{builtin}: the service control manager refused {call} for '{service}' (access denied)"),
                "run as an administrator; the shell did not refuse this",
            ),
            ERROR_SERVICE_DOES_NOT_EXIST => not_found(builtin, "service", service),
            ERROR_SERVICE_EXISTS | ERROR_DUPLICATE_SERVICE_NAME => bad_state_with_hint(
                builtin,
                &format!("{service} already exists, or its display name is taken; a service is never overwritten"),
                "choose another name",
            ),
            ERROR_SERVICE_MARKED_FOR_DELETE => bad_state_with_hint(
                builtin,
                &format!("{service} is marked for deletion and goes when the machine restarts"),
                "restart the machine, then retry",
            ),
            ERROR_INVALID_SERVICE_ACCOUNT | ERROR_SERVICE_LOGON_FAILED | ERROR_LOGON_FAILURE => {
                os_denied(
                    builtin,
                    format!("{builtin}: {call} could not log on the account of '{service}' ({win})"),
                    "use a built-in or virtual account such as LocalSystem; IronShell never supplies a password",
                )
            }
            _ => bad_state_with_hint(
                builtin,
                &format!("{call} failed for '{service}': {win} (Win32 error {code})"),
                "check the service with `sc.exe query`, then retry",
            ),
        }
    }

    fn open_scm(builtin: &str, access: u32) -> Result<Handle> {
        // SAFETY: null machine and database names select the local machine's
        // active service database; nothing is retained past the call.
        let raw = unsafe { OpenSCManagerW(null(), null(), access) };
        if raw.is_null() {
            return Err(scm_error(builtin, "OpenSCManagerW", last_error(), ""));
        }
        Ok(Handle(raw))
    }

    fn open_service(builtin: &str, scm: &Handle, service: &str, access: u32) -> Result<Handle> {
        let name = wide(service);
        // SAFETY: `name` is NUL-terminated and lives until the call returns.
        let raw = unsafe { OpenServiceW(scm.0, name.as_ptr(), access) };
        if raw.is_null() {
            return Err(scm_error(builtin, "OpenServiceW", last_error(), service));
        }
        Ok(Handle(raw))
    }

    /// The program must be an existing .exe file: the path is the service's
    /// binary, and the manager runs nothing else.
    fn check_executable(argv0: &str) -> Result<()> {
        let refuse = |why: &str| {
            crate::safety::bad_arg(
                "svc_create",
                "an existing .exe file as argv[0]",
                &format!("{argv0:?} ({why})"),
            )
        };
        let meta = std::fs::metadata(argv0).map_err(|_| refuse("does not exist"))?;
        if !meta.is_file() {
            return Err(refuse("not a regular file"));
        }
        let is_exe = std::path::Path::new(argv0)
            .extension()
            .is_some_and(|ext| ext.eq_ignore_ascii_case("exe"));
        if !is_exe {
            return Err(refuse("not an .exe file"));
        }
        Ok(())
    }

    fn change_config2(
        builtin: &str,
        svc: &Handle,
        service: &str,
        level: u32,
        info: *mut c_void,
    ) -> Result<()> {
        // SAFETY: `info` points at the structure `level` names, and the caller
        // keeps that structure and every pointer in it alive for the call.
        if unsafe { ChangeServiceConfig2W(svc.0, level, info) } == 0 {
            return Err(scm_error(
                builtin,
                "ChangeServiceConfig2W",
                last_error(),
                service,
            ));
        }
        Ok(())
    }

    /// The settings a new service gets after CreateServiceW: description,
    /// restart actions, and the start when asked. Any failure here is undone by
    /// the caller.
    fn configure_new(
        svc: &Handle,
        spec: &CreateSpec,
        service: &str,
        description: &str,
    ) -> Result<()> {
        const BUILTIN: &str = "svc_create";
        let mut text = wide(description);
        let mut info = ServiceDescriptionW {
            description: text.as_mut_ptr(),
        };
        change_config2(
            BUILTIN,
            svc,
            service,
            SERVICE_CONFIG_DESCRIPTION,
            (&mut info as *mut ServiceDescriptionW).cast(),
        )?;
        // "always" and "on-failure" both set the actions and the flag below; they
        // differ in the delay. On Windows "always" still means restart on any
        // failure, because the SCM never restarts a service that stops cleanly.
        if spec.restart == "on-failure" || spec.restart == "always" {
            let delay_ms = if spec.restart == "always" {
                ALWAYS_RESTART_DELAY_MS
            } else {
                RESTART_DELAY_MS
            };
            let mut actions = [ScAction {
                kind: SC_ACTION_RESTART,
                delay_ms,
            }; 3];
            let mut failure = ServiceFailureActionsW {
                reset_period: RESET_PERIOD_SECS,
                reboot_message: null_mut(),
                command: null_mut(),
                count: actions.len() as u32,
                actions: actions.as_mut_ptr(),
            };
            change_config2(
                BUILTIN,
                svc,
                service,
                SERVICE_CONFIG_FAILURE_ACTIONS,
                (&mut failure as *mut ServiceFailureActionsW).cast(),
            )?;
            // A non-zero exit is a failure as well, as on-failure and always mean on
            // Linux. Without this flag the actions run only after a crash.
            let mut flag = ServiceFailureFlag {
                on_non_crash_failures: 1,
            };
            change_config2(
                BUILTIN,
                svc,
                service,
                SERVICE_CONFIG_FAILURE_ACTIONS_FLAG,
                (&mut flag as *mut ServiceFailureFlag).cast(),
            )?;
        }
        if spec.start {
            // SAFETY: no arguments are passed, so the argument vector is null.
            if unsafe { StartServiceW(svc.0, 0, null()) } == 0 {
                return Err(scm_error(BUILTIN, "StartServiceW", last_error(), service));
            }
        }
        Ok(())
    }

    /// Stops and deletes a service that a failed create left behind. Both calls
    /// are best effort: the caller is already returning an error.
    fn undo_create(svc: &Handle) {
        let mut status = ServiceStatusProcess::default();
        // SAFETY: the status buffer is a SERVICE_STATUS-sized prefix of
        // ServiceStatusProcess, and the handle is open.
        unsafe {
            ControlService(
                svc.0,
                SERVICE_CONTROL_STOP,
                (&mut status as *mut ServiceStatusProcess).cast(),
            );
            DeleteService(svc.0);
        }
    }

    pub(super) fn create(spec: CreateSpec) -> Result<Value> {
        const BUILTIN: &str = "svc_create";
        let service = format!("{UNIT_PREFIX}{}", spec.name);
        check_executable(&spec.argv[0])?;
        if let Some(user) = &spec.user {
            crate::builtins::windows_account_sid(BUILTIN, user)?;
        }

        let scm = open_scm(BUILTIN, SC_MANAGER_CREATE_SERVICE)?;
        let name = wide(&service);
        // The binary path is argv[0] alone, quoted; argument-free by check above.
        let binary = wide(&format!("\"{}\"", spec.argv[0]));
        let account = spec.user.as_deref().map(wide);
        let start_type = if spec.enable {
            SERVICE_AUTO_START
        } else {
            SERVICE_DEMAND_START
        };
        // SAFETY: every string is NUL-terminated and lives until the call returns.
        // Null is the documented value for the load-order group, tag, dependencies
        // and password; a null account means LocalSystem.
        let raw = unsafe {
            CreateServiceW(
                scm.0,
                name.as_ptr(),
                name.as_ptr(),
                SERVICE_RIGHTS,
                SERVICE_WIN32_OWN_PROCESS,
                start_type,
                SERVICE_ERROR_NORMAL,
                binary.as_ptr(),
                null(),
                null_mut(),
                null(),
                account.as_ref().map_or(null(), |w| w.as_ptr()),
                null(),
            )
        };
        if raw.is_null() {
            return Err(scm_error(BUILTIN, "CreateServiceW", last_error(), &service));
        }
        let svc = Handle(raw);
        let description = format!("{WIN_MARKER}{}", spec.description);
        if let Err(e) = configure_new(&svc, &spec, &service, &description) {
            undo_create(&svc);
            return Err(e);
        }

        let mut record = BTreeMap::new();
        record.insert("name".to_string(), Value::Str(service.clone()));
        record.insert(
            "unit_path".to_string(),
            Value::Str(format!(r"HKLM\SYSTEM\CurrentControlSet\Services\{service}")),
        );
        record.insert("enabled".to_string(), Value::Bool(spec.enable));
        record.insert("started".to_string(), Value::Bool(spec.start));
        Ok(Value::Record(record))
    }

    /// Reads a configuration-style buffer through the two-call pattern: a sizing
    /// call that fails with ERROR_INSUFFICIENT_BUFFER, then the call with a
    /// buffer of that size. The buffer is u64-backed, so it is 8-byte aligned.
    fn query_buffer(
        builtin: &str,
        service: &str,
        call: &str,
        mut run: impl FnMut(*mut c_void, u32, *mut u32) -> i32,
    ) -> Result<Vec<u64>> {
        let mut needed: u32 = 0;
        if run(null_mut(), 0, &mut needed) == 0 {
            let code = last_error();
            if code != ERROR_INSUFFICIENT_BUFFER {
                return Err(scm_error(builtin, call, code, service));
            }
        }
        let mut buf = vec![0u64; (needed as usize).div_ceil(8).max(1)];
        if run(buf.as_mut_ptr().cast(), needed, &mut needed) == 0 {
            return Err(scm_error(builtin, call, last_error(), service));
        }
        Ok(buf)
    }

    fn start_type_of(builtin: &str, svc: &Handle, service: &str) -> Result<u32> {
        let buf = query_buffer(
            builtin,
            service,
            "QueryServiceConfigW",
            |p, size, needed| {
                // SAFETY: the buffer and its size are the ones query_buffer passes.
                unsafe { QueryServiceConfigW(svc.0, p, size, needed) }
            },
        )?;
        // SAFETY: a successful call wrote a QUERY_SERVICE_CONFIGW at the start of
        // the buffer, and the buffer outlives this read.
        Ok(unsafe { (*buf.as_ptr().cast::<QueryConfig>()).start_type })
    }

    /// The service description, or an empty string when it has none.
    fn description_of(builtin: &str, svc: &Handle, service: &str) -> Result<String> {
        let buf = query_buffer(
            builtin,
            service,
            "QueryServiceConfig2W",
            |p, size, needed| {
                // SAFETY: the buffer and its size are the ones query_buffer passes.
                unsafe { QueryServiceConfig2W(svc.0, SERVICE_CONFIG_DESCRIPTION, p, size, needed) }
            },
        )?;
        // SAFETY: a successful call wrote a SERVICE_DESCRIPTIONW whose string lies
        // in the same buffer and is NUL-terminated; the buffer outlives the reads.
        unsafe {
            let ptr = (*buf.as_ptr().cast::<ServiceDescriptionW>()).description;
            if ptr.is_null() {
                return Ok(String::new());
            }
            let mut len = 0;
            while *ptr.add(len) != 0 {
                len += 1;
            }
            Ok(String::from_utf16_lossy(std::slice::from_raw_parts(
                ptr, len,
            )))
        }
    }

    fn current_state(builtin: &str, svc: &Handle, service: &str) -> Result<u32> {
        let mut status = ServiceStatusProcess::default();
        let mut needed: u32 = 0;
        // SAFETY: the buffer is a SERVICE_STATUS_PROCESS and its size is passed.
        let ok = unsafe {
            QueryServiceStatusEx(
                svc.0,
                SC_STATUS_PROCESS_INFO,
                (&mut status as *mut ServiceStatusProcess).cast(),
                std::mem::size_of::<ServiceStatusProcess>() as u32,
                &mut needed,
            )
        };
        if ok == 0 {
            return Err(scm_error(
                builtin,
                "QueryServiceStatusEx",
                last_error(),
                service,
            ));
        }
        Ok(status.current_state)
    }

    /// Asks a running service to stop, then waits up to STOP_WAIT for it to
    /// report stopped. A service already stopping is waited for, not refused.
    fn stop_and_wait(builtin: &str, svc: &Handle, service: &str) -> Result<()> {
        let mut status = ServiceStatusProcess::default();
        // SAFETY: the status buffer is a SERVICE_STATUS-sized prefix of
        // ServiceStatusProcess, and the handle has SERVICE_STOP access.
        let ok = unsafe {
            ControlService(
                svc.0,
                SERVICE_CONTROL_STOP,
                (&mut status as *mut ServiceStatusProcess).cast(),
            )
        };
        if ok == 0 {
            let code = last_error();
            if code != ERROR_SERVICE_NOT_ACTIVE && code != ERROR_SERVICE_CANNOT_ACCEPT_CTRL {
                return Err(scm_error(builtin, "ControlService", code, service));
            }
        }
        let deadline = Instant::now() + STOP_WAIT;
        while current_state(builtin, svc, service)? != SERVICE_STOPPED {
            if Instant::now() >= deadline {
                return Err(budget_exceeded(
                    builtin,
                    format!(
                        "{builtin}: service '{service}' did not stop within {}s",
                        STOP_WAIT.as_secs()
                    ),
                    "check it with `sc.exe query`, then retry",
                ));
            }
            std::thread::sleep(Duration::from_millis(250));
        }
        Ok(())
    }

    pub(super) fn delete(name: String) -> Result<Value> {
        const BUILTIN: &str = "svc_delete";
        let service = format!("{UNIT_PREFIX}{name}");
        let scm = open_scm(BUILTIN, SC_MANAGER_CONNECT)?;
        let svc = open_service(
            BUILTIN,
            &scm,
            &service,
            SERVICE_QUERY_CONFIG | SERVICE_QUERY_STATUS | SERVICE_STOP | DELETE,
        )?;

        if !description_of(BUILTIN, &svc, &service)?.starts_with(WIN_MARKER) {
            return Err(policy_deny(
                BUILTIN,
                format!("{BUILTIN}: service '{service}' has no IronShell marker in its description; refusing to remove it"),
                "only services svc_create created can be deleted; remove hand-written services with sc.exe",
            ));
        }
        let start_type = start_type_of(BUILTIN, &svc, &service)?;
        let running = current_state(BUILTIN, &svc, &service)? != SERVICE_STOPPED;
        if running {
            stop_and_wait(BUILTIN, &svc, &service)?;
        }
        // Linux reports whether the unit was enabled. A Windows service counts as
        // enabled unless its start type is demand or disabled.
        let disabled = !matches!(start_type, SERVICE_DEMAND_START | SERVICE_DISABLED);
        // SAFETY: the handle is open with DELETE access.
        if unsafe { DeleteService(svc.0) } == 0 {
            return Err(scm_error(BUILTIN, "DeleteService", last_error(), &service));
        }

        let mut record = BTreeMap::new();
        record.insert("name".to_string(), Value::Str(service));
        record.insert("stopped".to_string(), Value::Bool(running));
        record.insert("disabled".to_string(), Value::Bool(disabled));
        record.insert("removed".to_string(), Value::Bool(true));
        Ok(Value::Record(record))
    }
}

// ── Linux backend ───────────────────────────────────────────────────────────

#[cfg(target_os = "linux")]
mod linux {
    use super::*;
    use crate::safety::{
        budget_exceeded, fs_error, not_found, policy_deny, spawn_error, tool_failed,
    };
    use std::io::{ErrorKind, Write};
    use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
    use std::path::{Path, PathBuf};

    const SYSTEMCTL: &str = "/usr/bin/systemctl";
    const GETENT: &str = "/usr/bin/getent";
    const UNIT_DIR: &str = "/etc/systemd/system";
    /// Bound on each systemctl call, so a stuck manager cannot hang the shell.
    const TOOL_TIMEOUT_SECS: u64 = 60;

    fn unit_name(name: &str) -> String {
        format!("{UNIT_PREFIX}{name}.service")
    }

    fn run_tool(builtin: &str, args: &[&str]) -> Result<std::process::Output> {
        let mut cmd = crate::safety::child_command(SYSTEMCTL);
        cmd.args(args);
        crate::safety::output_with_timeout(cmd, TOOL_TIMEOUT_SECS).map_err(|e| {
            if e.kind() == ErrorKind::TimedOut {
                budget_exceeded(
                    builtin,
                    format!(
                        "`systemctl {}` did not finish within {TOOL_TIMEOUT_SECS}s",
                        args.join(" ")
                    ),
                    "check the manager with `systemctl status`, then retry",
                )
            } else {
                spawn_error(builtin, SYSTEMCTL, &e)
            }
        })
    }

    fn run_checked(builtin: &str, args: &[&str]) -> Result<()> {
        let out = run_tool(builtin, args)?;
        if out.status.success() {
            return Ok(());
        }
        Err(tool_failed(
            builtin,
            &format!("systemctl {}", args.join(" ")),
            out.status.code(),
            &String::from_utf8_lossy(&out.stderr),
        ))
    }

    /// Quote one ExecStart word in systemd's syntax: double quotes, with
    /// backslash and double quote escaped and `$` doubled so it is not
    /// expanded as a variable. `%` and newlines are refused before this.
    pub(super) fn quote_word(word: &str) -> String {
        let mut quoted = String::with_capacity(word.len() + 2);
        quoted.push('"');
        for c in word.chars() {
            match c {
                '\\' => quoted.push_str("\\\\"),
                '"' => quoted.push_str("\\\""),
                '$' => quoted.push_str("$$"),
                other => quoted.push(other),
            }
        }
        quoted.push('"');
        quoted
    }

    pub(super) fn render_unit(spec: &CreateSpec) -> String {
        let exec: Vec<String> = spec.argv.iter().map(|a| quote_word(a)).collect();
        let mut text = String::new();
        text.push_str(MARKER);
        text.push('\n');
        text.push_str("[Unit]\n");
        // Description undergoes specifier expansion, so a literal % is %%.
        text.push_str(&format!(
            "Description={}\n",
            spec.description.replace('%', "%%")
        ));
        text.push_str("\n[Service]\nType=simple\n");
        text.push_str(&format!("ExecStart={}\n", exec.join(" ")));
        text.push_str(&format!("Restart={}\n", spec.restart));
        if let Some(user) = &spec.user {
            text.push_str(&format!("User={user}\n"));
        }
        text.push_str("\n[Install]\nWantedBy=multi-user.target\n");
        text
    }

    /// Create the file without ever replacing one. The text goes to a temporary
    /// file in the same directory, which is then hard-linked into place. The
    /// link fails with AlreadyExists if a unit appeared meanwhile, which a
    /// rename would silently overwrite.
    fn write_unit_file(path: &Path, text: &str) -> std::io::Result<()> {
        let file = path
            .file_name()
            .unwrap_or_default()
            .to_string_lossy()
            .into_owned();
        let tmp = path.with_file_name(format!(".{file}.tmp-{}", std::process::id()));
        let result: std::io::Result<()> = (|| {
            let mut handle = std::fs::OpenOptions::new()
                .write(true)
                .create_new(true)
                .mode(0o644)
                .open(&tmp)?;
            handle.write_all(text.as_bytes())?;
            handle.sync_all()?;
            drop(handle);
            std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o644))?;
            std::fs::hard_link(&tmp, path)
        })();
        let _ = std::fs::remove_file(&tmp);
        result
    }

    fn account_exists(user: &str) -> Result<()> {
        let mut cmd = crate::safety::child_command(GETENT);
        cmd.args(["passwd", user]);
        let out = crate::safety::output_with_timeout(cmd, TOOL_TIMEOUT_SECS)
            .map_err(|e| spawn_error("svc_create", GETENT, &e))?;
        match out.status.code() {
            Some(0) => Ok(()),
            Some(2) => Err(not_found("svc_create", "account", user)),
            code => Err(tool_failed(
                "svc_create",
                &format!("getent passwd {user}"),
                code,
                &String::from_utf8_lossy(&out.stderr),
            )),
        }
    }

    fn check_executable(argv0: &str) -> Result<()> {
        let refuse = |why: &str| {
            crate::safety::bad_arg(
                "svc_create",
                "an existing executable file as argv[0]",
                &format!("{argv0:?} ({why})"),
            )
        };
        let meta = std::fs::metadata(argv0).map_err(|_| refuse("does not exist"))?;
        if !meta.is_file() {
            return Err(refuse("not a regular file"));
        }
        if meta.permissions().mode() & 0o111 == 0 {
            return Err(refuse("not executable"));
        }
        Ok(())
    }

    pub(super) fn create(spec: CreateSpec) -> Result<Value> {
        const BUILTIN: &str = "svc_create";
        let unit = unit_name(&spec.name);
        let unit_path = PathBuf::from(UNIT_DIR).join(&unit);

        check_executable(&spec.argv[0])?;
        if let Some(user) = &spec.user {
            account_exists(user)?;
        }
        if unit_path.symlink_metadata().is_ok() {
            return Err(policy_deny(
                BUILTIN,
                format!(
                    "{BUILTIN}: {unit_path:?} already exists; a unit file is never overwritten"
                ),
                "choose another name",
            ));
        }

        let text = render_unit(&spec);
        match write_unit_file(&unit_path, &text) {
            Ok(()) => {}
            Err(e) if e.kind() == ErrorKind::AlreadyExists => {
                return Err(policy_deny(
                    BUILTIN,
                    format!("{BUILTIN}: {unit_path:?} appeared while writing; a unit file is never overwritten"),
                    "choose another name",
                ));
            }
            Err(e) => return Err(fs_error(BUILTIN, &unit_path, &e)),
        }

        if let Err(e) = configure(&spec, &unit) {
            // Undo everything this call did, so no half-created service stays.
            if spec.start {
                let _ = run_tool(BUILTIN, &["stop", unit.as_str()]);
            }
            if spec.enable {
                let _ = run_tool(BUILTIN, &["disable", unit.as_str()]);
            }
            let mut e = e;
            if let Err(rm) = std::fs::remove_file(&unit_path) {
                if rm.kind() != std::io::ErrorKind::NotFound {
                    e = crate::safety::with_note(
                        e,
                        &format!(
                            "{} was left behind and could not be removed: {rm}",
                            unit_path.display()
                        ),
                    );
                }
            }
            let _ = run_tool(BUILTIN, &["daemon-reload"]);
            return Err(e);
        }

        let mut record = BTreeMap::new();
        record.insert("name".to_string(), Value::Str(unit));
        record.insert(
            "unit_path".to_string(),
            Value::Str(unit_path.display().to_string()),
        );
        record.insert("enabled".to_string(), Value::Bool(spec.enable));
        record.insert("started".to_string(), Value::Bool(spec.start));
        Ok(Value::Record(record))
    }

    fn configure(spec: &CreateSpec, unit: &str) -> Result<()> {
        const BUILTIN: &str = "svc_create";
        run_checked(BUILTIN, &["daemon-reload"])?;
        if spec.enable {
            run_checked(BUILTIN, &["enable", unit])?;
        }
        if spec.start {
            run_checked(BUILTIN, &["start", unit])?;
        }
        Ok(())
    }

    fn is_running(builtin: &str, unit: &str) -> Result<bool> {
        let out = run_tool(builtin, &["is-active", unit])?;
        let state = String::from_utf8_lossy(&out.stdout).trim().to_string();
        Ok(matches!(
            state.as_str(),
            "active" | "activating" | "reloading" | "deactivating"
        ))
    }

    fn is_enabled(builtin: &str, unit: &str) -> Result<bool> {
        let out = run_tool(builtin, &["is-enabled", unit])?;
        Ok(String::from_utf8_lossy(&out.stdout).trim() == "enabled")
    }

    pub(super) fn delete(name: String) -> Result<Value> {
        const BUILTIN: &str = "svc_delete";
        let unit = unit_name(&name);
        let unit_path = PathBuf::from(UNIT_DIR).join(&unit);

        let meta = match unit_path.symlink_metadata() {
            Ok(meta) => meta,
            Err(e) if e.kind() == ErrorKind::NotFound => {
                return Err(not_found(BUILTIN, "unit", &unit));
            }
            Err(e) => return Err(fs_error(BUILTIN, &unit_path, &e)),
        };
        if !meta.is_file() {
            return Err(policy_deny(
                BUILTIN,
                format!("{BUILTIN}: {unit_path:?} is not a regular file; refusing to remove it"),
                "only unit files svc_create made can be deleted here",
            ));
        }
        let text = std::fs::read(&unit_path).map_err(|e| fs_error(BUILTIN, &unit_path, &e))?;
        let text = String::from_utf8_lossy(&text);
        if !text.lines().any(|line| line == MARKER) {
            return Err(policy_deny(
                BUILTIN,
                format!(
                    "{BUILTIN}: {unit_path:?} has no IronShell marker line; refusing to remove it"
                ),
                "only units svc_create created can be deleted; remove hand-written units by hand",
            ));
        }

        let stopped = if is_running(BUILTIN, &unit)? {
            let out = run_tool(BUILTIN, &["stop", unit.as_str()])?;
            // A stop that fails only because the unit was already down is fine;
            // anything still running afterwards is an error.
            if !out.status.success() && is_running(BUILTIN, &unit)? {
                return Err(tool_failed(
                    BUILTIN,
                    &format!("systemctl stop {unit}"),
                    out.status.code(),
                    &String::from_utf8_lossy(&out.stderr),
                ));
            }
            true
        } else {
            false
        };
        let disabled = if is_enabled(BUILTIN, &unit)? {
            run_checked(BUILTIN, &["disable", unit.as_str()])?;
            true
        } else {
            false
        };
        std::fs::remove_file(&unit_path).map_err(|e| fs_error(BUILTIN, &unit_path, &e))?;
        run_checked(BUILTIN, &["daemon-reload"])?;

        let mut record = BTreeMap::new();
        record.insert("name".to_string(), Value::Str(unit));
        record.insert("stopped".to_string(), Value::Bool(stopped));
        record.insert("disabled".to_string(), Value::Bool(disabled));
        record.insert("removed".to_string(), Value::Bool(true));
        Ok(Value::Record(record))
    }

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

        #[test]
        fn quoting_escapes_backslash_quote_and_dollar() {
            assert_eq!(quote_word(r#"a b"c\d$e"#), r#""a b\"c\\d$$e""#);
            assert_eq!(quote_word(""), "\"\"");
        }
    }
}

// ── macOS backend ───────────────────────────────────────────────────────────

/// launchd, through `launchctl` and a LaunchDaemon property list. A service is
/// `/Library/LaunchDaemons/com.ironshell.<name>.plist`, loaded into the system
/// domain. launchd loads every LaunchDaemon at boot, so `enable` is the
/// plist's `Disabled` key, and `start` is its `RunAtLoad`.
///
/// Options that have no launchd form are refused rather than approximated:
/// `start` without `enable`, since a loaded LaunchDaemon is loaded at every boot.
#[cfg(target_os = "macos")]
mod launchd {
    use super::*;
    use crate::builtins::bounded_cmd_output;
    use crate::safety::{
        bad_state_with_hint, fs_error, not_found, os_denied, policy_deny, tool_failed,
    };
    use std::io::{ErrorKind, Write};
    use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
    use std::path::{Path, PathBuf};

    const LAUNCHCTL: &str = "/bin/launchctl";
    const PLUTIL: &str = "/usr/bin/plutil";
    const ID: &str = "/usr/bin/id";
    const DAEMON_DIR: &str = "/Library/LaunchDaemons";
    const LABEL_PREFIX: &str = "com.ironshell.";
    /// Bound on each launchctl, plutil and id call, so a stuck tool cannot hang the shell.
    const TOOL_TIMEOUT_SECS: u64 = 60;
    /// Written as an XML comment in every plist this module creates.
    const PLIST_MARKER: &str = "<!-- Created by IronShell svc_create; svc_delete removes only plists carrying this line -->";

    fn label_of(name: &str) -> String {
        format!("{LABEL_PREFIX}{name}")
    }

    fn plist_path(label: &str) -> PathBuf {
        Path::new(DAEMON_DIR).join(format!("{label}.plist"))
    }

    fn require_root(builtin: &str) -> Result<()> {
        // SAFETY: geteuid takes no arguments and has no memory effects.
        if unsafe { libc::geteuid() } == 0 {
            return Ok(());
        }
        Err(os_denied(
            builtin,
            format!("{builtin}: writing {DAEMON_DIR} and loading the system domain need root; the shell did not refuse this"),
            "run it as root, for example with sudo",
        ))
    }

    fn check_executable(argv0: &str) -> Result<()> {
        let refuse = |why: &str| {
            crate::safety::bad_arg(
                "svc_create",
                "an existing executable file as argv[0]",
                &format!("{argv0:?} ({why})"),
            )
        };
        let meta = std::fs::metadata(argv0).map_err(|_| refuse("does not exist"))?;
        if !meta.is_file() {
            return Err(refuse("not a regular file"));
        }
        if meta.permissions().mode() & 0o111 == 0 {
            return Err(refuse("not executable"));
        }
        Ok(())
    }

    fn launchctl(builtin: &str, args: &[&str]) -> Result<std::process::Output> {
        let mut cmd = crate::safety::child_command(LAUNCHCTL);
        cmd.args(args);
        bounded_cmd_output(builtin, "launchctl", cmd, TOOL_TIMEOUT_SECS)
    }

    fn launchctl_checked(builtin: &str, args: &[&str]) -> Result<()> {
        let out = launchctl(builtin, args)?;
        if out.status.success() {
            return Ok(());
        }
        Err(tool_failed(
            builtin,
            &format!("launchctl {}", args.join(" ")),
            out.status.code(),
            &String::from_utf8_lossy(&out.stderr),
        ))
    }

    /// The `launchctl print` text when the label is loaded in the system
    /// domain, or None when `print` finds nothing for it.
    fn loaded_print(builtin: &str, label: &str) -> Result<Option<String>> {
        let target = format!("system/{label}");
        let out = launchctl(builtin, &["print", target.as_str()])?;
        if out.status.success() {
            Ok(Some(String::from_utf8_lossy(&out.stdout).into_owned()))
        } else {
            Ok(None)
        }
    }

    fn account_exists(user: &str) -> Result<()> {
        let mut cmd = crate::safety::child_command(ID);
        cmd.args(["-u", user]);
        let out = bounded_cmd_output("svc_create", "id", cmd, TOOL_TIMEOUT_SECS)?;
        match out.status.code() {
            Some(0) => Ok(()),
            Some(1) => Err(not_found("svc_create", "account", user)),
            code => Err(tool_failed(
                "svc_create",
                &format!("id -u {user}"),
                code,
                &String::from_utf8_lossy(&out.stderr),
            )),
        }
    }

    fn xml_escape(text: &str) -> String {
        let mut out = String::with_capacity(text.len());
        for c in text.chars() {
            match c {
                '&' => out.push_str("&amp;"),
                '<' => out.push_str("&lt;"),
                '>' => out.push_str("&gt;"),
                '"' => out.push_str("&quot;"),
                '\'' => out.push_str("&apos;"),
                other => out.push(other),
            }
        }
        out
    }

    fn key_string(text: &mut String, key: &str, value: &str) {
        text.push_str(&format!(
            "\t<key>{key}</key>\n\t<string>{}</string>\n",
            xml_escape(value)
        ));
    }

    pub(super) fn render_plist(spec: &CreateSpec, label: &str) -> String {
        let mut text = String::new();
        text.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        text.push_str("<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n");
        text.push_str("<plist version=\"1.0\">\n");
        text.push_str(PLIST_MARKER);
        text.push('\n');
        text.push_str("<dict>\n");
        key_string(&mut text, "Label", label);
        key_string(&mut text, "IronShellDescription", &spec.description);
        text.push_str("\t<key>ProgramArguments</key>\n\t<array>\n");
        for arg in &spec.argv {
            text.push_str(&format!("\t\t<string>{}</string>\n", xml_escape(arg)));
        }
        text.push_str("\t</array>\n");
        let run_at_load = if spec.start { "true" } else { "false" };
        text.push_str(&format!("\t<key>RunAtLoad</key>\n\t<{run_at_load}/>\n"));
        match spec.restart {
            "always" => text.push_str("\t<key>KeepAlive</key>\n\t<true/>\n"),
            "on-failure" => text.push_str(
                "\t<key>KeepAlive</key>\n\t<dict>\n\t\t<key>SuccessfulExit</key>\n\t\t<false/>\n\t</dict>\n",
            ),
            _ => {}
        }
        if let Some(user) = &spec.user {
            key_string(&mut text, "UserName", user);
        }
        if !spec.enable {
            text.push_str("\t<key>Disabled</key>\n\t<true/>\n");
        }
        text.push_str("</dict>\n</plist>\n");
        text
    }

    /// Create the plist without ever replacing one. The text goes to a
    /// temporary file in the same directory, which `plutil -lint` must accept
    /// before it is hard-linked into place. The link fails with AlreadyExists
    /// if a plist appeared meanwhile, which a rename would silently overwrite.
    /// The file is root:wheel, mode 0644, as launchd requires for a daemon.
    fn write_plist(path: &Path, text: &str) -> Result<()> {
        const BUILTIN: &str = "svc_create";
        let file = path
            .file_name()
            .unwrap_or_default()
            .to_string_lossy()
            .into_owned();
        let tmp = path.with_file_name(format!(".{file}.tmp-{}", std::process::id()));
        let result = (|| -> Result<()> {
            let mut handle = std::fs::OpenOptions::new()
                .write(true)
                .create_new(true)
                .mode(0o644)
                .open(&tmp)
                .map_err(|e| fs_error(BUILTIN, &tmp, &e))?;
            handle
                .write_all(text.as_bytes())
                .map_err(|e| fs_error(BUILTIN, &tmp, &e))?;
            handle.sync_all().map_err(|e| fs_error(BUILTIN, &tmp, &e))?;
            drop(handle);
            std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o644))
                .map_err(|e| fs_error(BUILTIN, &tmp, &e))?;
            std::os::unix::fs::chown(&tmp, Some(0), Some(0))
                .map_err(|e| fs_error(BUILTIN, &tmp, &e))?;

            let mut lint = crate::safety::child_command(PLUTIL);
            lint.arg("-lint").arg(&tmp);
            let out = bounded_cmd_output(BUILTIN, "plutil", lint, TOOL_TIMEOUT_SECS)?;
            if !out.status.success() {
                return Err(tool_failed(
                    BUILTIN,
                    "plutil -lint",
                    out.status.code(),
                    &String::from_utf8_lossy(&out.stderr),
                ));
            }

            std::fs::hard_link(&tmp, path).map_err(|e| {
                if e.kind() == ErrorKind::AlreadyExists {
                    policy_deny(
                        BUILTIN,
                        format!("{BUILTIN}: {path:?} appeared while writing; a plist is never overwritten"),
                        "choose another name",
                    )
                } else {
                    fs_error(BUILTIN, path, &e)
                }
            })
        })();
        let _ = std::fs::remove_file(&tmp);
        result
    }

    pub(super) fn create(spec: CreateSpec) -> Result<Value> {
        const BUILTIN: &str = "svc_create";
        if spec.start && !spec.enable {
            return Err(crate::safety::bad_arg(
                BUILTIN,
                "enable true when start is true: a LaunchDaemon that is loaded is loaded at every boot",
                "enable false with start true",
            ));
        }
        require_root(BUILTIN)?;

        let label = label_of(&spec.name);
        let path = plist_path(&label);
        check_executable(&spec.argv[0])?;
        if let Some(user) = &spec.user {
            account_exists(user)?;
        }
        match path.symlink_metadata() {
            Ok(_) => {
                let text = std::fs::read_to_string(&path).unwrap_or_default();
                if text.lines().any(|line| line == PLIST_MARKER) {
                    return Err(bad_state_with_hint(
                        BUILTIN,
                        &format!("{label} already exists; a service is never overwritten"),
                        "choose another name, or svc_delete the existing one first",
                    ));
                }
                return Err(policy_deny(
                    BUILTIN,
                    format!("{BUILTIN}: {path:?} exists and was not created by IronShell; refusing to replace it"),
                    "choose another name",
                ));
            }
            Err(e) if e.kind() == ErrorKind::NotFound => {}
            Err(e) => return Err(fs_error(BUILTIN, &path, &e)),
        }
        if loaded_print(BUILTIN, &label)?.is_some() {
            return Err(bad_state_with_hint(
                BUILTIN,
                &format!("{label} is already loaded in the system domain; a service is never overwritten"),
                "choose another name, or svc_delete it first",
            ));
        }

        write_plist(&path, &render_plist(&spec, &label))?;
        if spec.enable {
            let plist = path.display().to_string();
            if let Err(e) = launchctl_checked(BUILTIN, &["bootstrap", "system", plist.as_str()]) {
                // Undo the file, so no half-created service stays.
                let mut e = e;
                if let Err(rm) = std::fs::remove_file(&path) {
                    if rm.kind() != std::io::ErrorKind::NotFound {
                        e = crate::safety::with_note(
                            e,
                            &format!(
                                "{} was left behind and could not be removed: {rm}",
                                path.display()
                            ),
                        );
                    }
                }
                return Err(e);
            }
        }

        let mut record = BTreeMap::new();
        record.insert("name".to_string(), Value::Str(label));
        record.insert(
            "unit_path".to_string(),
            Value::Str(path.display().to_string()),
        );
        record.insert("enabled".to_string(), Value::Bool(spec.enable));
        record.insert("started".to_string(), Value::Bool(spec.start));
        Ok(Value::Record(record))
    }

    pub(super) fn delete(name: String) -> Result<Value> {
        const BUILTIN: &str = "svc_delete";
        require_root(BUILTIN)?;
        let label = label_of(&name);
        let path = plist_path(&label);

        let meta = match path.symlink_metadata() {
            Ok(meta) => meta,
            Err(e) if e.kind() == ErrorKind::NotFound => {
                if loaded_print(BUILTIN, &label)?.is_some() {
                    return Err(policy_deny(
                        BUILTIN,
                        format!("{BUILTIN}: {label} is loaded but has no plist in {DAEMON_DIR}; it was not created by IronShell"),
                        "remove it with launchctl by hand",
                    ));
                }
                return Err(not_found(BUILTIN, "service", &label));
            }
            Err(e) => return Err(fs_error(BUILTIN, &path, &e)),
        };
        if !meta.is_file() {
            return Err(policy_deny(
                BUILTIN,
                format!("{BUILTIN}: {path:?} is not a regular file; refusing to remove it"),
                "only plists svc_create made can be deleted here",
            ));
        }
        let text = std::fs::read_to_string(&path).map_err(|e| fs_error(BUILTIN, &path, &e))?;
        if !text.lines().any(|line| line == PLIST_MARKER) {
            return Err(policy_deny(
                BUILTIN,
                format!("{BUILTIN}: {path:?} has no IronShell marker line; refusing to remove it"),
                "only services svc_create created can be deleted; remove hand-written daemons by hand",
            ));
        }
        // A plist without a `Disabled` key is loaded at boot, which is what `enable` means.
        let disabled = !text.contains("<key>Disabled</key>");

        let stopped = match loaded_print(BUILTIN, &label)? {
            Some(print) => {
                let running = print.contains("state = running");
                let target = format!("system/{label}");
                launchctl_checked(BUILTIN, &["bootout", target.as_str()])?;
                running
            }
            None => false,
        };
        std::fs::remove_file(&path).map_err(|e| fs_error(BUILTIN, &path, &e))?;

        let mut record = BTreeMap::new();
        record.insert("name".to_string(), Value::Str(label));
        record.insert("stopped".to_string(), Value::Bool(stopped));
        record.insert("disabled".to_string(), Value::Bool(disabled));
        record.insert("removed".to_string(), Value::Bool(true));
        Ok(Value::Record(record))
    }
}