rightkit-send 0.2.0

Nearby file and text sharing over the open LocalSend v2 protocol, with Pulse extensions: TLS identity pinning, per-device trust, and macOS Bonjour discovery. Product-neutral; the host supplies identity, paths and policy.
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
//! Nearby sharing over the open LocalSend protocol v2 (github.com/localsend/protocol),
//! with the Pulse extensions (`pulse` key in prepare-upload, `px` in Bonjour TXT).
//!
//! `Service` is a long-running object a host owns: it announces this device,
//! keeps a list of nearby devices, receives files over HTTPS after the owner
//! accepts, and sends files to a chosen device. The host supplies a stored
//! `Identity`, the trust store path, the folders and the wording of anything it
//! shows; it hears about changes through the `Event` callback and reads
//! `Service::snapshot`. Errors are typed (`Error`); no user-facing English is
//! produced here.

#[cfg(all(feature = "bonjour", target_os = "macos"))]
mod bonjour;
#[cfg(all(feature = "multicast", not(target_os = "ios")))]
pub mod discovery;
mod error;
pub mod net;
mod policy;
pub mod proto;
mod receive;
pub mod send;
pub mod trust;
mod workers;

pub use error::Error;
pub use net::Identity;
pub use policy::Policy;
pub use send::{Entry, Peer, SendItem};
use trust::normalize;
pub use trust::{TrustEntry, TrustState};
use workers::{Stopper, Worker};

use proto::DeviceInfo;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr, TcpListener, TcpStream};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

/// What the host configures. Every string here is the host's own choice: the
/// crate never names a product.
#[derive(Clone, Debug)]
pub struct Config {
    /// The host's product name, reported in `Snapshot::product`.
    pub product_name: String,
    /// How other devices list this device.
    pub alias: String,
    /// Listen port (TLS). 0 picks a free port; `Service::bound_port` reports it.
    pub port: u16,
    /// Device class announced to others: "desktop", "mobile", "web", "headless" or "server".
    pub device_type: String,
    /// Model announced to others (empty for none).
    pub device_model: String,
    /// Where received files go.
    pub save_dir: PathBuf,
    /// The JSON trust store file. Created on the first change.
    pub trust_path: PathBuf,
    /// Sent as the HTTP User-Agent on every outgoing request.
    pub user_agent: String,
    /// Written into the macOS quarantine attribute as the agent name.
    pub quarantine_agent: String,
    /// Suffix of the temporary file a receive is written to until it is complete (".pulse-part" for Pulse).
    pub temp_suffix: String,
    /// Prefix of the diagnostic lines written to stderr (e.g. "pulse sharing:").
    pub log_prefix: String,
    /// Limits and folder names. `Policy::default()` is Pulse's current behaviour.
    pub policy: Policy,
}

/// A device on the network.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Device {
    pub fingerprint: String,
    pub alias: String,
    pub device_model: Option<String>,
    pub device_type: Option<String>,
    pub ip: String,
    pub port: u16,
    pub protocol: String,
    /// The device announced the Pulse extensions (Bonjour TXT `px=1`). A host
    /// decides what to offer; LocalSend-only devices report false.
    pub px: bool,
}

#[derive(Clone, Debug, Serialize)]
pub struct IncomingFile {
    pub name: String,
    pub size: u64,
}

/// A request waiting for the user's answer.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Incoming {
    pub id: String,
    pub from: String,
    pub device_model: Option<String>,
    pub fingerprint: String,
    pub ip: String,
    pub file_count: usize,
    pub total_bytes: u64,
    pub is_message: bool,
    /// Always None: a text message is not shown until it is accepted.
    pub preview: Option<String>,
    /// The first few files, for display (none for a message).
    pub files: Vec<IncomingFile>,
    /// The sender proved it holds the key behind its fingerprint by presenting its
    /// certificate. Anything less is unproven: saved apart, no clipboard, capped.
    pub verified: bool,
}

/// One send or receive, from the first request to the last byte.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Transfer {
    pub id: String,
    /// "send" or "receive".
    pub direction: String,
    pub peer: String,
    pub peer_fingerprint: String,
    /// waiting, active, done, failed, cancelled or declined.
    pub state: String,
    pub total_bytes: u64,
    pub done_bytes: u64,
    pub files_total: usize,
    pub files_done: usize,
    pub current: Option<String>,
    pub saved_to: Option<String>,
    pub saved_files: Vec<String>,
    pub error: Option<Error>,
    /// A received text message, shown with Copy rather than saved as a file.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    /// Sent from the clipboard: the receiver puts it on its clipboard.
    #[serde(default)]
    pub clipboard: bool,
    pub started: u64,
    pub finished: Option<u64>,
}

impl Transfer {
    pub fn is_open(&self) -> bool {
        self.state == "waiting" || self.state == "active"
    }
}

#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Snapshot {
    /// The host product name from `Config::product_name`.
    pub product: String,
    pub alias: String,
    pub fingerprint: String,
    pub port: u16,
    pub save_dir: String,
    pub devices: Vec<Device>,
    pub incoming: Vec<Incoming>,
    pub transfers: Vec<Transfer>,
    /// Things that don't work, typed (discovery socket, …).
    pub warnings: Vec<Error>,
    /// "unknown", "granted" or "blocked" (macOS Local Network access).
    pub local_network: String,
    /// A sweep of the local networks is running.
    pub scanning: bool,
}

#[derive(Clone, Debug)]
pub enum Event {
    /// The device list changed.
    Devices,
    /// A device wants to send; the user must answer (`Service::respond`).
    Incoming(Incoming),
    /// A request was answered, withdrawn or timed out.
    IncomingResolved(String),
    /// Bytes moved (rate-limited).
    Progress(Transfer),
    /// A transfer reached an end state.
    Finished(Transfer),
    /// Anything else (a transfer dismissed).
    Changed,
}

/// One entry of `known-devices.json`: a bare fingerprint (accepted before).
/// Older files held objects with extra fields; only the fingerprint is kept.
#[derive(Deserialize)]
#[serde(untagged)]
enum KnownEntry {
    Plain(String),
    Object {
        fingerprint: String,
        #[serde(default)]
        label: Option<String>,
    },
}

/// The old list as (fingerprint, label) pairs; the label is empty when none.
fn load_known(path: &std::path::Path) -> Vec<(String, String)> {
    let entries = std::fs::read(path)
        .ok()
        .and_then(|bytes| serde_json::from_slice::<Vec<KnownEntry>>(&bytes).ok())
        .unwrap_or_default();
    entries
        .into_iter()
        .map(|entry| match entry {
            KnownEntry::Plain(fingerprint) => (fingerprint, String::new()),
            KnownEntry::Object { fingerprint, label } => (fingerprint, label.unwrap_or_default()),
        })
        .collect()
}

/// Write `contents` next to `path` and rename it into place; the file is private
/// (0600) on Unix. The temp file is `.<name>.tmp-<hex>` in the same directory,
/// created exclusively (a name collision retries), fsynced, renamed over the
/// target, and the directory is fsynced so the rename survives power loss. A
/// failure removes the temp file and leaves the target as it was.
///
/// Deliberately not `rightkit-fs`: that crate requires rustc 1.98 and this one
/// is pinned to 1.90 (see docs/plans/2026-10-10-rightkit-send-design.md).
fn write_atomic(path: &std::path::Path, contents: &[u8]) -> std::io::Result<()> {
    use std::io::Write;
    let parent = match path.parent() {
        Some(p) if !p.as_os_str().is_empty() => p,
        _ => std::path::Path::new("."),
    };
    let name = path
        .file_name()
        .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "no file name"))?
        .to_string_lossy()
        .into_owned();
    std::fs::create_dir_all(parent)?;
    let mut options = std::fs::OpenOptions::new();
    options.write(true).create_new(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(0o600);
    }
    let mut attempt = 0;
    let (temp, mut file) = loop {
        let temp = parent.join(format!(".{name}.tmp-{}", proto::random_hex(4)));
        match options.open(&temp) {
            Ok(file) => break (temp, file),
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists && attempt < 8 => attempt += 1,
            Err(e) => return Err(e),
        }
    };
    let written = file.write_all(contents).and_then(|()| file.sync_all());
    drop(file);
    if let Err(e) = written {
        let _ = std::fs::remove_file(&temp);
        return Err(e);
    }
    if let Err(e) = std::fs::rename(&temp, path) {
        let _ = std::fs::remove_file(&temp);
        return Err(e);
    }
    // The new content is in place; a directory sync failure is not a failed write.
    #[cfg(unix)]
    if let Ok(dir) = std::fs::File::open(parent) {
        let _ = dir.sync_all();
    }
    Ok(())
}

#[cfg(test)]
mod write_atomic_tests {
    use super::write_atomic;

    fn dir(tag: &str) -> std::path::PathBuf {
        let d = std::env::temp_dir().join(format!("rk-send-atomic-{tag}-{}", proto::random_hex(4)));
        std::fs::create_dir_all(&d).unwrap();
        d
    }
    use super::proto;

    #[test]
    fn replaces_existing_content_and_leaves_no_temp() {
        let d = dir("replace");
        let target = d.join("nearby_devices.json");
        write_atomic(&target, b"one").unwrap();
        write_atomic(&target, b"two").unwrap();
        assert_eq!(std::fs::read(&target).unwrap(), b"two");
        let names: Vec<_> = std::fs::read_dir(&d)
            .unwrap()
            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
            .collect();
        assert_eq!(names, vec!["nearby_devices.json".to_string()]);
        let _ = std::fs::remove_dir_all(&d);
    }

    #[test]
    fn creates_missing_parents() {
        let d = dir("parents");
        let target = d.join("a").join("b").join("store.json");
        write_atomic(&target, b"x").unwrap();
        assert_eq!(std::fs::read(&target).unwrap(), b"x");
        let _ = std::fs::remove_dir_all(&d);
    }

    #[cfg(unix)]
    #[test]
    fn the_result_is_owner_only() {
        use std::os::unix::fs::PermissionsExt;
        let d = dir("mode");
        let target = d.join("store.json");
        write_atomic(&target, b"x").unwrap();
        assert_eq!(
            std::fs::metadata(&target).unwrap().permissions().mode() & 0o777,
            0o600
        );
        // Replacing a broader file narrows it: the new inode is 0600.
        std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o644)).unwrap();
        write_atomic(&target, b"y").unwrap();
        assert_eq!(
            std::fs::metadata(&target).unwrap().permissions().mode() & 0o777,
            0o600
        );
        let _ = std::fs::remove_dir_all(&d);
    }

    #[test]
    fn a_sibling_differing_only_by_extension_is_untouched() {
        let d = dir("sibling");
        std::fs::write(d.join("store.bak"), b"keep").unwrap();
        write_atomic(&d.join("store.json"), b"x").unwrap();
        assert_eq!(std::fs::read(d.join("store.bak")).unwrap(), b"keep");
        let _ = std::fs::remove_dir_all(&d);
    }

    #[test]
    fn a_failed_rename_removes_the_temp_and_keeps_the_target() {
        let d = dir("fail");
        // A directory at the target makes the rename fail on every platform.
        let target = d.join("store.json");
        std::fs::create_dir(&target).unwrap();
        assert!(write_atomic(&target, b"x").is_err());
        assert!(target.is_dir());
        let names: Vec<_> = std::fs::read_dir(&d)
            .unwrap()
            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
            .collect();
        assert_eq!(
            names,
            vec!["store.json".to_string()],
            "no stray temp: {names:?}"
        );
        let _ = std::fs::remove_dir_all(&d);
    }

    #[cfg(unix)]
    #[test]
    fn a_symlink_at_the_target_is_replaced_not_followed() {
        let d = dir("link");
        let outside = d.join("outside.txt");
        std::fs::write(&outside, b"precious").unwrap();
        let target = d.join("store.json");
        std::os::unix::fs::symlink(&outside, &target).unwrap();
        write_atomic(&target, b"x").unwrap();
        assert_eq!(std::fs::read(&outside).unwrap(), b"precious");
        assert_eq!(std::fs::read(&target).unwrap(), b"x");
        assert!(
            !std::fs::symlink_metadata(&target)
                .unwrap()
                .file_type()
                .is_symlink()
        );
        let _ = std::fs::remove_dir_all(&d);
    }
}

pub(crate) struct Seen {
    pub device: Device,
    pub last_seen: Instant,
    pub misses: u32,
}

pub(crate) struct Pending {
    pub incoming: Incoming,
    pub decision: Mutex<Option<bool>>,
    pub changed: Condvar,
}

pub(crate) struct CancelHandle {
    pub flag: AtomicBool,
    pub stream: Mutex<Option<TcpStream>>,
}

pub(crate) struct SessionFile {
    pub meta: proto::FileMeta,
    pub token: String,
    pub done: bool,
}

pub(crate) struct Session {
    pub transfer_id: String,
    pub peer_ip: IpAddr,
    pub peer_fingerprint: String,
    pub files: HashMap<String, SessionFile>,
    pub cancel: Arc<AtomicBool>,
    pub activity: Instant,
    pub remaining: usize,
    pub saved: Vec<PathBuf>,
    pub save_dir: PathBuf,
    /// The sender proved its key by certificate (not only by callback).
    pub proven: bool,
}

pub(crate) struct Inner {
    pub cfg: Mutex<Config>,
    pub me: DeviceInfo,
    pub tls: Arc<rustls::ServerConfig>,
    pub stop: AtomicBool,
    /// Wakes the threads that wait with a timeout (liveness, accept retry) when the service stops.
    pub park: Stopper,
    pub devices: Mutex<Vec<Seen>>,
    pub transfers: Mutex<Vec<Transfer>>,
    pub pending: Mutex<HashMap<String, Arc<Pending>>>,
    pub sessions: Mutex<HashMap<String, Session>>,
    pub cancels: Mutex<HashMap<String, Arc<CancelHandle>>>,
    pub trust: Mutex<trust::TrustStore>,
    pub on_event: Arc<dyn Fn(Event) + Send + Sync>,
    pub last_progress: Mutex<Instant>,
    pub connections: AtomicUsize,
    pub warnings: Mutex<Vec<Error>>,
    /// 0 unknown, 1 reachable, 2 macOS is refusing local network access.
    pub local_network: std::sync::atomic::AtomicU8,
    /// A sweep of the local networks is running.
    pub scanning: AtomicBool,
    /// Someone asked for a sweep; the scanner thread takes it.
    #[cfg(all(feature = "multicast", not(target_os = "ios")))]
    pub scan_requested: AtomicBool,
    /// This Mac's own addresses and when they were read.
    pub own_ips: Mutex<(Instant, Vec<Ipv4Addr>)>,
    /// Bonjour instance name to the fingerprint it resolved to, so a Remove can be
    /// mapped back to a device.
    #[cfg(all(feature = "bonjour", target_os = "macos"))]
    pub bonjour_names: Mutex<HashMap<String, String>>,
}

pub(crate) fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
    mutex
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
}

pub(crate) fn now_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

impl Inner {
    pub fn emit(&self, event: Event) {
        (self.on_event)(event);
    }

    fn config(&self) -> Config {
        lock(&self.cfg).clone()
    }

    /// Whether `ip` is one of this Mac's own addresses.
    fn is_own_ip(&self, ip: IpAddr) -> bool {
        let IpAddr::V4(v4) = ip else {
            return ip.is_loopback();
        };
        if v4.is_loopback() {
            return true;
        }
        let mut own = lock(&self.own_ips);
        if own.0.elapsed() > Duration::from_secs(30) {
            *own = (Instant::now(), local_ipv4s());
        }
        own.1.contains(&v4)
    }

    /// Record a device heard from `ip`, unless it is this Mac itself. Emits
    /// `Devices` when the list changed. Returns whether the device was taken.
    pub fn upsert(&self, info: &DeviceInfo, ip: IpAddr) -> bool {
        let fingerprint = normalize(&info.fingerprint);
        if fingerprint.is_empty() || fingerprint == self.me.fingerprint || self.is_own_ip(ip) {
            return false;
        }
        // An announcement is nobody's proof: it never sets a record's proof.
        lock(&self.trust).observe(
            &fingerprint,
            &info.alias,
            info.device_model.as_deref(),
            info.device_type.as_deref(),
            None,
        );
        let device = Device {
            fingerprint,
            alias: info.alias.clone(),
            device_model: info.device_model.clone(),
            device_type: info.device_type.clone(),
            ip: ip.to_string(),
            port: info.port,
            protocol: info.protocol.clone(),
            px: false,
        };
        let changed = {
            let mut devices = lock(&self.devices);
            match devices
                .iter_mut()
                .find(|s| s.device.fingerprint == device.fingerprint)
            {
                Some(seen) => {
                    // An announcement can move a device (ip, port) but never takes
                    // it from https back to http.
                    let mut device = device;
                    device.px = seen.device.px || device.px;
                    if seen.device.protocol == "https" {
                        device.protocol = "https".to_string();
                    }
                    let changed = seen.device.alias != device.alias
                        || seen.device.ip != device.ip
                        || seen.device.port != device.port
                        || seen.device.protocol != device.protocol;
                    seen.device = device;
                    seen.last_seen = Instant::now();
                    seen.misses = 0;
                    changed
                }
                None => {
                    devices.push(Seen {
                        device,
                        last_seen: Instant::now(),
                        misses: 0,
                    });
                    true
                }
            }
        };
        if changed {
            self.emit(Event::Devices);
        }
        true
    }

    /// Sweep the local networks for devices multicast didn't find.
    #[cfg(all(feature = "multicast", not(target_os = "ios")))]
    fn scan(&self) {
        self.scanning.store(true, Ordering::Relaxed);
        self.emit(Event::Changed);
        discovery::sweep(&self.me, &self.stop, &|heard| {
            self.upsert(&heard.info, heard.ip);
        });
        self.scanning.store(false, Ordering::Relaxed);
        self.emit(Event::Changed);
    }

    pub fn device_list(&self) -> Vec<Device> {
        let mut list: Vec<Device> = lock(&self.devices)
            .iter()
            .map(|s| s.device.clone())
            .collect();
        list.sort_by_key(|d| d.alias.to_lowercase());
        list
    }

    /// The port the device with this fingerprint announced, if it is on the list.
    pub fn announced_port(&self, fingerprint: &str) -> Option<u16> {
        let fingerprint = normalize(fingerprint);
        lock(&self.devices)
            .iter()
            .find(|s| s.device.fingerprint == fingerprint)
            .map(|s| s.device.port)
    }

    pub fn trust_state(&self, fingerprint: &str) -> TrustState {
        lock(&self.trust).state_of(fingerprint)
    }

    pub fn add_transfer(&self, transfer: Transfer) {
        let mut transfers = lock(&self.transfers);
        transfers.push(transfer);
        while transfers.len() > 12 {
            match transfers.iter().position(|t| !t.is_open()) {
                Some(index) => {
                    transfers.remove(index);
                }
                None => break,
            }
        }
    }

    /// Change one transfer. A progress event goes out at most ten times a
    /// second unless `force` is set.
    pub fn update_transfer(&self, id: &str, force: bool, change: impl FnOnce(&mut Transfer)) {
        let updated = {
            let mut transfers = lock(&self.transfers);
            transfers.iter_mut().find(|t| t.id == id).map(|t| {
                change(t);
                t.clone()
            })
        };
        let Some(transfer) = updated else { return };
        let due = {
            let mut last = lock(&self.last_progress);
            if force || last.elapsed() >= Duration::from_millis(100) {
                *last = Instant::now();
                true
            } else {
                false
            }
        };
        if due {
            self.emit(Event::Progress(transfer));
        }
    }

    /// Put a transfer in an end state, once.
    pub fn end_transfer(&self, id: &str, state: &str, error: Option<Error>) {
        let ended = {
            let mut transfers = lock(&self.transfers);
            transfers
                .iter_mut()
                .find(|t| t.id == id && t.is_open())
                .map(|t| {
                    t.state = state.to_string();
                    t.error = error;
                    t.finished = Some(now_ms());
                    if state == "done" {
                        t.done_bytes = t.total_bytes;
                        t.files_done = t.files_total;
                    }
                    t.current = None;
                    t.clone()
                })
        };
        if let Some(transfer) = ended {
            self.emit(Event::Finished(transfer));
        }
    }
}

/// Runtime figures of a running service, computed on call by [`Service::status`].
#[derive(Clone, Debug)]
pub struct SendStatus {
    /// Devices on the nearby list.
    pub devices: usize,
    /// Transfers not yet finished.
    pub transfers_open: usize,
    /// Transfers held in the list, finished ones included until dismissed.
    pub transfers_listed: usize,
    /// Incoming requests waiting for an answer.
    pub pending_incoming: usize,
    /// Connections being served now (capped at 64).
    pub connections: usize,
    /// Typed warnings currently raised.
    pub warnings: usize,
    /// A sweep of the local networks is running.
    pub scanning: bool,
    /// Resident memory, CPU time and I/O counters of the whole process (the acceptor, discovery and
    /// liveness threads run in it), or `None` when the host cannot report them. See
    /// `rightkit_child_process::ProcessUsage`.
    pub process: Option<rightkit_child_process::ProcessUsage>,
}

/// A running sharing service. Dropping it stops it.
pub struct Service {
    inner: Arc<Inner>,
    /// The acceptor and liveness threads, ended and joined by [`Service::stop`].
    workers: Mutex<Vec<Worker>>,
    #[cfg(all(feature = "bonjour", target_os = "macos"))]
    bonjour: Mutex<Option<(bonjour::Advertiser, bonjour::Browser)>>,
}

impl Service {
    /// Start sharing with `config`, presenting `identity`: the host's stored
    /// certificate and key. Fails before anything is announced when the identity,
    /// the trust store or the listen port cannot be used.
    pub fn start(
        config: Config,
        identity: Identity,
        on_event: Arc<dyn Fn(Event) + Send + Sync>,
    ) -> Result<Service, Error> {
        let tls = net::server_config(&identity).map_err(|e| Error::Identity {
            detail: e.to_string(),
        })?;
        // Windows lets a second program bind a port another one holds in some
        // cases (a dual-stack listener); a connection that succeeds first says
        // somebody is already listening, so say so instead of failing silently.
        #[cfg(windows)]
        {
            if config.port != 0 {
                let local = std::net::SocketAddr::from((Ipv4Addr::LOCALHOST, config.port));
                if TcpStream::connect_timeout(&local, Duration::from_millis(300)).is_ok() {
                    return Err(Error::PortInUse { port: config.port });
                }
            }
        }
        let listener = TcpListener::bind(("0.0.0.0", config.port)).map_err(|e| {
            if e.kind() == std::io::ErrorKind::AddrInUse
                || (cfg!(windows) && e.kind() == std::io::ErrorKind::PermissionDenied)
            {
                Error::PortInUse { port: config.port }
            } else {
                Error::Listen {
                    port: config.port,
                    detail: e.to_string(),
                }
            }
        })?;
        let port = listener
            .local_addr()
            .map(|address| address.port())
            .map_err(|e| Error::Listen {
                port: config.port,
                detail: e.to_string(),
            })?;
        let mut config = config;
        config.port = port;

        net::set_client_identity(&identity);
        net::set_user_agent(&config.user_agent);
        let trust = trust::TrustStore::load(&config.trust_path);
        let me = DeviceInfo {
            alias: config.alias.clone(),
            version: proto::VERSION.to_string(),
            device_model: Some(config.device_model.clone()),
            device_type: Some(config.device_type.clone()),
            fingerprint: identity.fingerprint.clone(),
            port,
            protocol: "https".to_string(),
            download: false,
            announce: None,
        };
        let inner = Arc::new(Inner {
            cfg: Mutex::new(config.clone()),
            me,
            tls,
            stop: AtomicBool::new(false),
            park: Stopper::new(),
            devices: Mutex::new(Vec::new()),
            transfers: Mutex::new(Vec::new()),
            pending: Mutex::new(HashMap::new()),
            sessions: Mutex::new(HashMap::new()),
            cancels: Mutex::new(HashMap::new()),
            trust: Mutex::new(trust),
            on_event,
            last_progress: Mutex::new(Instant::now()),
            connections: AtomicUsize::new(0),
            warnings: Mutex::new(Vec::new()),
            local_network: std::sync::atomic::AtomicU8::new(0),
            scanning: AtomicBool::new(false),
            #[cfg(all(feature = "multicast", not(target_os = "ios")))]
            scan_requested: AtomicBool::new(false),
            own_ips: Mutex::new((Instant::now(), local_ipv4s())),
            #[cfg(all(feature = "bonjour", target_os = "macos"))]
            bonjour_names: Mutex::new(HashMap::new()),
        });

        // The listener stays blocking: the acceptor sleeps in `accept` until a peer arrives or
        // `stop` connects to it.
        let acceptor =
            spawn_acceptor(inner.clone(), listener, port).map_err(|e| Error::Listen {
                port,
                detail: e.to_string(),
            })?;
        #[cfg(all(feature = "multicast", not(target_os = "ios")))]
        {
            match discovery::listen(port) {
                Ok(socket) => spawn_discovery(inner.clone(), socket),
                Err(e) => lock(&inner.warnings).push(Error::DiscoveryUnavailable {
                    detail: e.to_string(),
                }),
            }
            spawn_announcer(inner.clone());
            spawn_scanner(inner.clone());
        }
        #[cfg(all(feature = "bonjour", target_os = "macos"))]
        let bonjour = start_bonjour(&inner, &config, &identity.fingerprint);
        let service = Service {
            inner: inner.clone(),
            workers: Mutex::new(vec![acceptor]),
            #[cfg(all(feature = "bonjour", target_os = "macos"))]
            bonjour: Mutex::new(bonjour),
        };
        match spawn_liveness(inner) {
            Ok(liveness) => lock(&service.workers).push(liveness),
            // Dropping `service` on the way out stops what has started.
            Err(e) => {
                return Err(Error::Listen {
                    port,
                    detail: e.to_string(),
                });
            }
        }
        Ok(service)
    }

    /// The port the service listens on (the chosen one when `Config::port` was 0).
    pub fn bound_port(&self) -> u16 {
        lock(&self.inner.cfg).port
    }

    /// Add a device a host-run resolver found (on iOS, Swift's NWBrowser feeds
    /// this). `txt` holds the TXT keys (`fp`, `alias`, `type`, `model`, `px`).
    /// The fingerprint must be 64 hex characters; identity is still proven by
    /// the handshake certificate, never by this announcement.
    pub fn peer_add_resolved(
        &self,
        fingerprint: &str,
        alias: &str,
        host: IpAddr,
        port: u16,
        txt: &[(String, String)],
    ) -> Result<(), Error> {
        let fingerprint = normalize(fingerprint);
        if !net::valid_pin(&fingerprint) {
            return Err(Error::InvalidFingerprint);
        }
        let info = resolved_info(&fingerprint, alias, port, txt);
        let px = txt_value(txt, "px").as_deref() == Some("1");
        self.inner.add_resolved(&info, host, px);
        Ok(())
    }

    /// Remove a device a host-run resolver reported gone. Returns whether it was
    /// on the list.
    pub fn peer_remove(&self, fingerprint: &str) -> bool {
        self.inner.remove_device(&normalize(fingerprint))
    }

    /// Counts and process resource usage, read now. No polling thread runs for this.
    pub fn status(&self) -> SendStatus {
        let inner = &self.inner;
        let transfers = lock(&inner.transfers);
        SendStatus {
            devices: lock(&inner.devices).len(),
            transfers_open: transfers.iter().filter(|t| t.is_open()).count(),
            transfers_listed: transfers.len(),
            pending_incoming: lock(&inner.pending).len(),
            connections: inner.connections.load(Ordering::Relaxed),
            warnings: lock(&inner.warnings).len(),
            scanning: inner.scanning.load(Ordering::Relaxed),
            process: rightkit_child_process::process_usage().ok(),
        }
    }

    pub fn snapshot(&self) -> Snapshot {
        let inner = &self.inner;
        let cfg = inner.config();
        let mut incoming: Vec<Incoming> = lock(&inner.pending)
            .values()
            .map(|p| p.incoming.clone())
            .collect();
        incoming.sort_by(|a, b| a.id.cmp(&b.id));
        Snapshot {
            product: cfg.product_name.clone(),
            alias: cfg.alias,
            fingerprint: inner.me.fingerprint.clone(),
            port: cfg.port,
            save_dir: cfg.save_dir.to_string_lossy().into_owned(),
            devices: inner.device_list(),
            incoming,
            transfers: lock(&inner.transfers).clone(),
            warnings: lock(&inner.warnings).clone(),
            local_network: match inner.local_network.load(Ordering::Relaxed) {
                1 => "granted",
                2 => "blocked",
                _ => "unknown",
            }
            .to_string(),
            scanning: inner.scanning.load(Ordering::Relaxed),
        }
    }

    /// Look for devices again now: announce on multicast and sweep the local
    /// networks (the sweep is skipped while one is already running).
    pub fn refresh(&self) {
        #[cfg(all(feature = "multicast", not(target_os = "ios")))]
        {
            let inner = self.inner.clone();
            thread::spawn(move || {
                let _ = discovery::announce(&inner.me, inner.config().port, true);
            });
            self.inner.scan_requested.store(true, Ordering::Relaxed);
        }
    }

    pub fn devices(&self) -> Vec<Device> {
        self.inner.device_list()
    }

    /// The fingerprint of this Mac's certificate.
    pub fn fingerprint(&self) -> String {
        self.inner.me.fingerprint.clone()
    }

    /// Every device with a record, newest sighting first.
    pub fn devices_trust(&self) -> Vec<TrustEntry> {
        lock(&self.inner.trust).list()
    }

    /// What a never-seen device is subject to: Ask or Deny.
    pub fn default_state(&self) -> TrustState {
        lock(&self.inner.trust).default_state()
    }

    /// Set a device to Allow, Ask or Deny. Deny also withdraws what the device
    /// has pending or in flight.
    pub fn set_trust(&self, fingerprint: &str, state: TrustState) -> Result<(), Error> {
        lock(&self.inner.trust).set_state(fingerprint, state)?;
        if state == TrustState::Deny {
            self.revoke(fingerprint);
        }
        self.inner.emit(Event::Changed);
        Ok(())
    }

    /// The owner's own name for a device (empty clears it).
    pub fn set_label(&self, fingerprint: &str, label: &str) -> Result<(), Error> {
        lock(&self.inner.trust).set_label(fingerprint, label)?;
        self.inner.emit(Event::Changed);
        Ok(())
    }

    /// Drop the record of a device that is not on the network now.
    pub fn forget(&self, fingerprint: &str) -> Result<(), Error> {
        if lock(&self.inner.devices)
            .iter()
            .any(|s| s.device.fingerprint == normalize(fingerprint))
        {
            return Err(Error::DeviceNearby);
        }
        lock(&self.inner.trust).forget(fingerprint)?;
        self.inner.emit(Event::Changed);
        Ok(())
    }

    /// How devices seen for the first time start: Ask or Deny.
    pub fn set_default_state(&self, state: TrustState) -> Result<(), Error> {
        lock(&self.inner.trust).set_default(state)?;
        self.inner.emit(Event::Changed);
        Ok(())
    }

    /// Decline this device's waiting requests and cancel its receives in flight.
    fn revoke(&self, fingerprint: &str) {
        let fingerprint = normalize(fingerprint);
        let fingerprint = fingerprint.as_str();
        let waiting: Vec<Arc<Pending>> = lock(&self.inner.pending)
            .values()
            .filter(|p| p.incoming.fingerprint == fingerprint)
            .cloned()
            .collect();
        for p in waiting {
            *lock(&p.decision) = Some(false);
            p.changed.notify_all();
        }
        let ended: Vec<String> = {
            let mut sessions = lock(&self.inner.sessions);
            let ids: Vec<String> = sessions
                .iter()
                .filter(|(_, s)| s.peer_fingerprint == fingerprint)
                .map(|(id, _)| id.clone())
                .collect();
            ids.iter()
                .filter_map(|id| sessions.remove(id))
                .map(|session| {
                    session.cancel.store(true, Ordering::Relaxed);
                    session.transfer_id
                })
                .collect()
        };
        for transfer_id in ended {
            self.inner.end_transfer(&transfer_id, "cancelled", None);
        }
    }

    pub fn set_save_dir(&self, directory: PathBuf) {
        lock(&self.inner.cfg).save_dir = directory;
    }

    /// The nearby device with this fingerprint (or, failing that, alias).
    fn find_device(&self, target: &str) -> Option<Device> {
        let devices = lock(&self.inner.devices);
        let wanted = normalize(target);
        devices
            .iter()
            .find(|s| s.device.fingerprint == wanted)
            .or_else(|| {
                devices
                    .iter()
                    .find(|s| s.device.alias.eq_ignore_ascii_case(target))
            })
            .map(|s| s.device.clone())
    }

    /// This computer's name as other devices list it.
    pub fn alias(&self) -> String {
        self.inner.config().alias
    }

    /// Send to the device with this fingerprint (or, failing that, alias).
    /// Returns the transfer id; progress arrives as events.
    pub fn send(
        &self,
        target: &str,
        items: Vec<SendItem>,
        clipboard: bool,
    ) -> Result<String, Error> {
        let device = self.find_device(target).ok_or(Error::DeviceNotNearby)?;
        if self.inner.trust_state(&device.fingerprint) == TrustState::Deny {
            return Err(Error::DeviceBlocked);
        }
        if device.protocol != "https" {
            return Err(Error::PeerPlaintext {
                peer: device.alias.clone(),
            });
        }
        if !net::valid_pin(&device.fingerprint) {
            return Err(Error::InvalidIdentity {
                peer: device.alias.clone(),
            });
        }
        let ip: IpAddr = device.ip.parse().map_err(|_| Error::NoUsableAddress)?;
        let peer = Peer {
            ip,
            port: device.port,
            https: device.protocol == "https",
            fingerprint: device.fingerprint.clone(),
            alias: device.alias.clone(),
        };
        let id = proto::random_hex(8);
        self.inner.add_transfer(Transfer {
            id: id.clone(),
            direction: "send".into(),
            peer: device.alias.clone(),
            peer_fingerprint: device.fingerprint.clone(),
            state: "waiting".into(),
            total_bytes: 0,
            done_bytes: 0,
            files_total: 0,
            files_done: 0,
            current: None,
            saved_to: None,
            saved_files: Vec::new(),
            error: None,
            message: None,
            clipboard,
            started: now_ms(),
            finished: None,
        });
        let handle = Arc::new(CancelHandle {
            flag: AtomicBool::new(false),
            stream: Mutex::new(None),
        });
        lock(&self.inner.cancels).insert(id.clone(), handle.clone());
        self.inner.emit(Event::Changed);
        let inner = self.inner.clone();
        let transfer_id = id.clone();
        thread::spawn(move || run_send(inner, transfer_id, peer, items, clipboard, handle));
        Ok(id)
    }

    /// Answer a waiting request.
    pub fn respond(&self, id: &str, accept: bool) -> bool {
        let pending = lock(&self.inner.pending).get(id).cloned();
        let Some(pending) = pending else { return false };
        *lock(&pending.decision) = Some(accept);
        pending.changed.notify_all();
        true
    }

    /// Cancel a transfer, either direction.
    pub fn cancel(&self, transfer_id: &str) -> bool {
        if let Some(handle) = lock(&self.inner.cancels).get(transfer_id).cloned() {
            handle.flag.store(true, Ordering::Relaxed);
            if let Some(stream) = lock(&handle.stream).as_ref() {
                let _ = stream.shutdown(std::net::Shutdown::Both);
            }
            return true;
        }
        receive::cancel_receive(&self.inner, transfer_id)
    }

    /// Forget a finished transfer.
    pub fn dismiss(&self, transfer_id: &str) {
        lock(&self.inner.transfers).retain(|t| t.id != transfer_id || t.is_open());
        self.inner.emit(Event::Changed);
    }

    /// Stop sharing. Pending requests are declined, transfers in flight are cancelled, and the
    /// acceptor and liveness threads are ended and joined: when this returns the listening socket
    /// is closed and its port can be bound again, and no thread of the service's own is left
    /// running. It returns promptly (a few milliseconds), never waiting on a peer. Connection
    /// handlers and liveness probes already running are not joined; they finish on their own
    /// within their socket timeouts. Calling it again, or dropping the `Service`, does nothing more.
    pub fn stop(&self) {
        self.shutdown();
    }

    /// [`Service::stop`], reporting whether every worker thread was joined.
    fn shutdown(&self) -> bool {
        self.inner.stop.store(true, Ordering::Relaxed);
        self.inner.park.stop();
        #[cfg(all(feature = "bonjour", target_os = "macos"))]
        {
            let handles = lock(&self.bonjour).take();
            drop(handles);
        }
        let pending: Vec<Arc<Pending>> = lock(&self.inner.pending).values().cloned().collect();
        for p in pending {
            *lock(&p.decision) = Some(false);
            p.changed.notify_all();
        }
        let handles: Vec<Arc<CancelHandle>> = lock(&self.inner.cancels).values().cloned().collect();
        for handle in handles {
            handle.flag.store(true, Ordering::Relaxed);
            if let Some(stream) = lock(&handle.stream).as_ref() {
                let _ = stream.shutdown(std::net::Shutdown::Both);
            }
        }
        for session in lock(&self.inner.sessions).values() {
            session.cancel.store(true, Ordering::Relaxed);
        }
        // No lock is held here: the threads being joined never take one that this thread holds.
        let workers = std::mem::take(&mut *lock(&self.workers));
        let mut all_ended = true;
        for worker in workers {
            all_ended &= worker.stop();
        }
        all_ended
    }
}

impl Drop for Service {
    fn drop(&mut self) {
        self.stop();
    }
}

// ---- background threads ----------------------------------------------------

struct ConnectionGuard(Arc<Inner>);

impl Drop for ConnectionGuard {
    fn drop(&mut self) {
        self.0.connections.fetch_sub(1, Ordering::Relaxed);
    }
}

/// Start the acceptor on a thread of its own. `port` is where `stop` connects to wake it.
fn spawn_acceptor(inner: Arc<Inner>, listener: TcpListener, port: u16) -> std::io::Result<Worker> {
    Worker::spawn(
        "rk-send-accept",
        move || wake_listener(port),
        move || accept_loop(&inner, listener),
    )
}

/// End a blocked `accept` by connecting to the listener from this process (see `workers.rs` for
/// why this and not `shutdown` or `close`). The connection is dropped at once; the acceptor sees
/// the stop flag and drops it too. A failed connect is harmless: `Worker::stop` tries again.
fn wake_listener(port: u16) {
    let address = std::net::SocketAddr::from((Ipv4Addr::LOCALHOST, port));
    let _ = TcpStream::connect_timeout(&address, Duration::from_millis(250));
}

/// Connections this service serves at once; the next one is closed unread.
const MAX_CONNECTIONS: usize = 64;

/// The acceptor: blocks in `accept` and hands each connection to a handler thread of its own.
/// Owns the listener, so the port is released when this returns.
fn accept_loop(inner: &Arc<Inner>, listener: TcpListener) {
    while !inner.stop.load(Ordering::Relaxed) {
        let accepted = listener.accept();
        #[cfg(test)]
        inner.park.note_wake();
        match accepted {
            Ok((socket, address)) => {
                // `Service::stop` ends the blocking accept with a connection of its own.
                if inner.stop.load(Ordering::Relaxed) {
                    break;
                }
                let _ = socket.set_nonblocking(false);
                if inner.connections.load(Ordering::Relaxed) >= MAX_CONNECTIONS {
                    continue;
                }
                inner.connections.fetch_add(1, Ordering::Relaxed);
                // Counted down however the handler ends, panics included.
                let guard = ConnectionGuard(inner.clone());
                thread::spawn(move || {
                    let guard = guard;
                    receive::handle_connection(&guard.0, socket, address);
                });
            }
            // A failed accept (descriptor exhaustion, a peer that reset before it was taken):
            // back off so a persistent fault cannot spin, and let a stop end the wait.
            Err(_) => {
                if inner.park.wait(Duration::from_millis(250)) {
                    break;
                }
            }
        }
    }
}

#[cfg(all(feature = "multicast", not(target_os = "ios")))]
fn spawn_discovery(inner: Arc<Inner>, socket: std::net::UdpSocket) {
    thread::spawn(move || {
        let _ = socket.set_read_timeout(Some(Duration::from_millis(500)));
        let mut buffer = vec![0u8; 64 * 1024];
        let mut rejoined = Instant::now();
        while !inner.stop.load(Ordering::Relaxed) {
            if rejoined.elapsed() >= Duration::from_secs(30) {
                rejoined = Instant::now();
                discovery::rejoin(&socket);
            }
            let Ok((n, from)) = socket.recv_from(&mut buffer) else {
                continue;
            };
            let Some(heard) = discovery::parse(&buffer[..n], from) else {
                continue;
            };
            if !inner.upsert(&heard.info, heard.ip) {
                continue;
            }
            if heard.info.announce.unwrap_or(false) {
                let inner = inner.clone();
                thread::spawn(move || answer_announcement(&inner, &heard));
            }
        }
    });
}

#[cfg(all(feature = "multicast", not(target_os = "ios")))]
/// Reply to an announcement the way the protocol asks: register with the
/// sender over HTTP, and fall back to a multicast reply.
fn answer_announcement(inner: &Arc<Inner>, heard: &discovery::Heard) {
    let mut me = inner.me.clone();
    me.announce = None;
    let registered = serde_json::to_vec(&me).ok().is_some_and(|body| {
        net::request_json(
            heard.ip,
            heard.info.port,
            heard.info.protocol == "https",
            &heard.info.fingerprint,
            "POST",
            &format!("{}/register", proto::API),
            Some(&body),
            Duration::from_secs(3),
        )
        .is_ok_and(|reply| reply.status == 200)
    });
    if !registered {
        let _ = discovery::announce(&inner.me, inner.config().port, false);
    }
}

#[cfg(all(feature = "multicast", not(target_os = "ios")))]
fn spawn_announcer(inner: Arc<Inner>) {
    thread::spawn(move || {
        let mut waits = vec![100u64, 400, 1500].into_iter();
        while !inner.stop.load(Ordering::Relaxed) {
            let sent = discovery::announce(&inner.me, inner.config().port, true);
            inner.local_network.store(
                match &sent {
                    Ok(()) => 1,
                    // EHOSTUNREACH: what a denied Local Network permission looks like.
                    #[cfg(target_os = "macos")]
                    Err(e) if e.raw_os_error() == Some(65) => 2,
                    // WSAEACCES: Windows Firewall (or policy) refusing the multicast send.
                    #[cfg(windows)]
                    Err(e) if e.raw_os_error() == Some(10013) => 2,
                    Err(_) => 0,
                },
                Ordering::Relaxed,
            );
            inner.emit(Event::Changed);
            let wait = waits.next().unwrap_or(30_000);
            let until = Instant::now() + Duration::from_millis(wait);
            while Instant::now() < until && !inner.stop.load(Ordering::Relaxed) {
                thread::sleep(Duration::from_millis(100));
            }
        }
    });
}

/// Sweep the local networks shortly after start (multicast gets the first
/// word), when asked, and every minute while no device is known.
#[cfg(all(feature = "multicast", not(target_os = "ios")))]
fn spawn_scanner(inner: Arc<Inner>) {
    thread::spawn(move || {
        let mut due = Instant::now() + Duration::from_secs(2);
        let mut first = true;
        while !inner.stop.load(Ordering::Relaxed) {
            thread::sleep(Duration::from_millis(100));
            let asked = inner.scan_requested.load(Ordering::Relaxed);
            let waited = Instant::now() >= due;
            if !asked && !waited {
                continue;
            }
            if asked || first || lock(&inner.devices).is_empty() {
                inner.scan();
                inner.scan_requested.store(false, Ordering::Relaxed);
                first = false;
            }
            due = Instant::now() + Duration::from_secs(60);
        }
    });
}

/// How often devices not heard from are probed.
const LIVENESS_PERIOD: Duration = Duration::from_secs(20);

/// Drop devices that stop answering `GET /info`.
fn spawn_liveness(inner: Arc<Inner>) -> std::io::Result<Worker> {
    // The wait is on `park`, which `Service::stop` has already stopped: nothing more to wake.
    Worker::spawn("rk-send-liveness", || {}, move || liveness_loop(&inner))
}

/// One timed wait per period, ended at once by a stop.
fn liveness_loop(inner: &Arc<Inner>) {
    while !inner.park.wait(LIVENESS_PERIOD) {
        let stale: Vec<Device> = lock(&inner.devices)
            .iter()
            .filter(|s| s.last_seen.elapsed() > Duration::from_secs(20))
            .map(|s| s.device.clone())
            .collect();
        for device in stale {
            let inner = inner.clone();
            thread::spawn(move || {
                let alive = device.ip.parse::<IpAddr>().ok().is_some_and(|ip| {
                    net::request_json(
                        ip,
                        device.port,
                        device.protocol == "https",
                        &device.fingerprint,
                        "GET",
                        &format!("{}/info", proto::API),
                        None,
                        Duration::from_secs(2),
                    )
                    .is_ok_and(|reply| reply.status == 200)
                });
                let removed = {
                    let mut devices = lock(&inner.devices);
                    match devices
                        .iter()
                        .position(|s| s.device.fingerprint == device.fingerprint)
                    {
                        Some(index) if alive => {
                            devices[index].last_seen = Instant::now();
                            devices[index].misses = 0;
                            false
                        }
                        Some(index) => {
                            devices[index].misses += 1;
                            if devices[index].misses >= 2 {
                                devices.remove(index);
                                true
                            } else {
                                false
                            }
                        }
                        None => false,
                    }
                };
                if removed {
                    inner.emit(Event::Devices);
                }
            });
        }
    }
}

fn run_send(
    inner: Arc<Inner>,
    id: String,
    peer: Peer,
    items: Vec<SendItem>,
    clipboard: bool,
    handle: Arc<CancelHandle>,
) {
    let finish = |state: &str, error: Option<Error>| {
        inner.end_transfer(&id, state, error);
        lock(&inner.cancels).remove(&id);
    };
    let entries = match send::expand(&items) {
        Ok(entries) => entries,
        Err(message) => return finish("failed", Some(message)),
    };
    inner.update_transfer(&id, true, |t| {
        t.files_total = entries.len();
        t.total_bytes = entries.iter().map(|e| e.size).sum();
    });
    let register = |stream: Option<TcpStream>| {
        *lock(&handle.stream) = stream;
    };
    // A message counts as sent once it is on the other screen.
    let delivered = std::cell::Cell::new(false);
    let result = send::deliver(
        &inner.me,
        &peer,
        &entries,
        clipboard,
        &handle.flag,
        &register,
        &mut |p| {
            if p.phase == send::Phase::Delivered {
                delivered.set(true);
                inner.end_transfer(&id, "done", None);
                return;
            }
            let waiting = p.phase == send::Phase::Waiting;
            inner.update_transfer(&id, p.total > 0 && p.done >= p.total, |t| {
                t.state = if waiting { "waiting" } else { "active" }.to_string();
                t.total_bytes = p.total;
                t.done_bytes = p.done;
                t.files_total = p.files_total;
                t.files_done = p.files_done;
                t.current = p.current.clone();
            });
        },
    );
    if delivered.get() {
        lock(&inner.cancels).remove(&id);
        return;
    }
    match result {
        Ok(send::Outcome::Done) => finish("done", None),
        Ok(send::Outcome::Declined) => finish("declined", None),
        Ok(send::Outcome::Cancelled) => finish("cancelled", None),
        Err(_) if handle.flag.load(Ordering::Relaxed) => finish("cancelled", None),
        Err(message) => finish("failed", Some(message)),
    }
}

// ---- resolved peers, host-fed or Bonjour ----------------------------------

/// The TXT value for `key`, if present.
fn txt_value(txt: &[(String, String)], key: &str) -> Option<String> {
    txt.iter()
        .find(|(k, _)| k.as_str() == key)
        .map(|(_, v)| v.clone())
}

/// A resolved device as an announcement would describe it. An empty alias
/// falls back to the start of the fingerprint.
fn resolved_info(
    fingerprint: &str,
    alias: &str,
    port: u16,
    txt: &[(String, String)],
) -> DeviceInfo {
    let alias = if alias.is_empty() {
        fingerprint.chars().take(8).collect()
    } else {
        alias.to_string()
    };
    DeviceInfo {
        alias,
        version: proto::VERSION.to_string(),
        device_model: txt_value(txt, "model").filter(|m| !m.is_empty()),
        device_type: txt_value(txt, "type").filter(|t| !t.is_empty()),
        fingerprint: fingerprint.to_string(),
        port,
        protocol: "https".to_string(),
        download: false,
        announce: None,
    }
}

/// This device's IPv4 addresses, for telling its own announcements apart. Empty
/// where multicast discovery is not compiled in.
#[cfg(all(feature = "multicast", not(target_os = "ios")))]
fn local_ipv4s() -> Vec<Ipv4Addr> {
    discovery::local_ipv4s()
}

#[cfg(not(all(feature = "multicast", not(target_os = "ios"))))]
fn local_ipv4s() -> Vec<Ipv4Addr> {
    Vec::new()
}

impl Inner {
    /// Record a device a resolver found, with its `px` flag. Returns whether it
    /// was taken (not this device itself).
    fn add_resolved(&self, info: &DeviceInfo, ip: IpAddr, px: bool) -> bool {
        if !self.upsert(info, ip) {
            return false;
        }
        let fingerprint = normalize(&info.fingerprint);
        let changed = {
            let mut devices = lock(&self.devices);
            match devices
                .iter_mut()
                .find(|s| s.device.fingerprint == fingerprint)
            {
                Some(seen) if seen.device.px != px => {
                    seen.device.px = px;
                    true
                }
                _ => false,
            }
        };
        if changed {
            self.emit(Event::Devices);
        }
        true
    }

    /// Drop a device from the list. Returns whether it was listed.
    fn remove_device(&self, fingerprint: &str) -> bool {
        let removed = {
            let mut devices = lock(&self.devices);
            let before = devices.len();
            devices.retain(|s| s.device.fingerprint != fingerprint);
            devices.len() != before
        };
        if removed {
            self.emit(Event::Devices);
        }
        removed
    }
}

#[cfg(all(feature = "bonjour", target_os = "macos"))]
impl Inner {
    fn bonjour_found(&self, found: bonjour::Found) {
        let Some(fingerprint) = txt_value(&found.txt, "fp")
            .map(|f| normalize(&f))
            .filter(|f| net::valid_pin(f))
        else {
            return;
        };
        let alias = txt_value(&found.txt, "alias").unwrap_or_default();
        let info = resolved_info(&fingerprint, &alias, found.port, &found.txt);
        let px = txt_value(&found.txt, "px").as_deref() == Some("1");
        if self.add_resolved(&info, found.host, px) {
            lock(&self.bonjour_names).insert(found.instance, fingerprint);
        }
    }

    fn bonjour_lost(&self, instance: &str) {
        let fingerprint = lock(&self.bonjour_names).remove(instance);
        if let Some(fingerprint) = fingerprint {
            self.remove_device(&fingerprint);
        }
    }
}

#[cfg(all(feature = "bonjour", target_os = "macos"))]
fn start_bonjour(
    inner: &Arc<Inner>,
    config: &Config,
    fingerprint: &str,
) -> Option<(bonjour::Advertiser, bonjour::Browser)> {
    let model = Some(config.device_model.as_str()).filter(|m| !m.is_empty());
    let txt = bonjour::txt_encode(fingerprint, &config.alias, &config.device_type, model);
    let advertiser = match bonjour::Advertiser::start(&config.alias, config.port, &txt) {
        Ok(advertiser) => advertiser,
        Err(e) => {
            lock(&inner.warnings).push(Error::DiscoveryUnavailable {
                detail: e.to_string(),
            });
            return None;
        }
    };
    let found = inner.clone();
    let lost = inner.clone();
    match bonjour::Browser::start(
        config.alias.clone(),
        Box::new(move |peer| found.bonjour_found(peer)),
        Box::new(move |instance| lost.bonjour_lost(&instance)),
    ) {
        Ok(browser) => Some((advertiser, browser)),
        Err(e) => {
            lock(&inner.warnings).push(Error::DiscoveryUnavailable {
                detail: e.to_string(),
            });
            None
        }
    }
}

#[cfg(test)]
mod lifecycle_tests {
    use super::*;
    use std::io::{ErrorKind, Read};
    use std::net::SocketAddr;

    /// `Service::start` sets the client identity and User-Agent for the whole process, so these
    /// tests run one at a time.
    static SERIAL: Mutex<()> = Mutex::new(());

    fn serial() -> MutexGuard<'static, ()> {
        lock(&SERIAL)
    }

    fn config(port: u16) -> Config {
        let root = std::env::temp_dir().join(format!("rk-send-life-{}", proto::random_hex(4)));
        Config {
            product_name: "Test".into(),
            alias: "Lifecycle".into(),
            port,
            device_type: "desktop".into(),
            device_model: "Test".into(),
            save_dir: root.join("save"),
            trust_path: root.join("nearby_devices.json"),
            user_agent: "LifecycleTest/1".into(),
            quarantine_agent: "LifecycleTest".into(),
            temp_suffix: ".test-part".into(),
            log_prefix: "test sharing:".into(),
            policy: Policy::default(),
        }
    }

    fn start_on(port: u16) -> Result<Service, Error> {
        let identity = Identity::generate("Lifecycle").expect("identity");
        Service::start(config(port), identity, Arc::new(|_: Event| {}))
    }

    #[test]
    fn an_idle_service_wakes_its_threads_about_once_a_second_at_most() {
        let _serial = serial();
        let service = start_on(0).expect("service starts");
        let (began, woke_before) = (Instant::now(), service.inner.park.wakes());
        thread::sleep(Duration::from_secs(2));
        let (secs, woke) = (
            began.elapsed().as_secs_f64(),
            service.inner.park.wakes() - woke_before,
        );
        // The window can stretch on a loaded machine and the allowance stretches with it. The 50 ms
        // accept poll and 100 ms liveness tick this replaces woke about 60 times in two seconds.
        let allowed = 3u64.max(secs.ceil() as u64 + 1);
        assert!(
            woke <= allowed,
            "the service woke {woke} times in {secs:.1} s"
        );
        assert!(service.shutdown());
    }

    #[test]
    fn stop_returns_promptly_having_joined_every_service_thread() {
        let _serial = serial();
        let service = start_on(0).expect("service starts");
        // Let both threads reach their waits; stopping before they do ends them at once too.
        thread::sleep(Duration::from_millis(100));
        assert_eq!(lock(&service.workers).len(), 2, "acceptor and liveness");
        let began = Instant::now();
        assert!(service.shutdown(), "a service thread did not end");
        assert!(
            began.elapsed() < Duration::from_secs(1),
            "stop took {:?}",
            began.elapsed()
        );
        assert!(lock(&service.workers).is_empty());
        // Stopping again, and the drop that follows, change nothing.
        assert!(service.shutdown());
        service.stop();
    }

    #[test]
    fn a_second_start_on_the_same_port_succeeds_after_stop() {
        let _serial = serial();
        let first = start_on(0).expect("service starts");
        let port = first.bound_port();
        assert!(first.shutdown());
        for round in 0..3 {
            let again = start_on(port)
                .unwrap_or_else(|e| panic!("restart {round} on port {port} failed: {e:?}"));
            assert_eq!(again.bound_port(), port);
            assert!(again.shutdown());
        }
    }

    #[test]
    fn the_64_connection_cap_still_closes_the_next_connection_unread() {
        let _serial = serial();
        let service = start_on(0).expect("service starts");
        let address = SocketAddr::from((Ipv4Addr::LOCALHOST, service.bound_port()));
        let mut byte = [0u8; 1];

        // At the cap the connection is closed without a byte exchanged: end of stream or a reset,
        // never a timeout.
        service
            .inner
            .connections
            .store(MAX_CONNECTIONS, Ordering::Relaxed);
        let mut full = TcpStream::connect(address).expect("connect");
        full.set_read_timeout(Some(Duration::from_secs(10)))
            .unwrap();
        match full.read(&mut byte) {
            Ok(0) => {}
            Err(e) if !matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {}
            other => panic!("a connection over the cap must be closed, got {other:?}"),
        }

        // Below the cap it is kept: the handler waits for a TLS hello (30 s timeout), so a short
        // read here times out.
        service.inner.connections.store(0, Ordering::Relaxed);
        let mut open = TcpStream::connect(address).expect("connect");
        open.set_read_timeout(Some(Duration::from_millis(300)))
            .unwrap();
        match open.read(&mut byte) {
            Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {}
            other => panic!("a connection under the cap must be kept open, got {other:?}"),
        }
        drop(open);
        assert!(service.shutdown());
    }
}