tailtalk 0.3.0

A modern async user space AppleTalk stack with Rust + Tokio
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
use anyhow::Error;
use mac_address::mac_address_by_name;
use rand::Rng;
use std::path::PathBuf;
use std::time::SystemTime;
use tailtalk_packets::aarp;
use tailtalk_packets::ddp::DdpPacket;
use tailtalk_packets::ethertalk::{EtherTalkPhase2Frame, EtherTalkPhase2Type};
use tailtalk_packets::llap::{LlapPacket, LlapType};
use tashtalk::TashTalk;
use tokio::sync::mpsc;
use tokio_serial::SerialPortBuilderExt;
use futures::StreamExt;
pub use tokio_util::sync::CancellationToken;

pub use tashtalk::TashTalkFeatures;

pub mod addressing;
pub mod adsp;
pub mod afp;
pub mod asp;
pub mod atp;

pub mod ddp;
pub mod echo;
pub mod nbp;
pub mod pap;
pub mod stylewriter;

#[derive(Debug, PartialEq, Eq)]
pub enum DataLinkProtocol {
    Ddp,
    Aarp,
}

#[derive(Debug)]
pub struct DataLinkPacket {
    pub dest_node: addressing::Node,
    pub protocol: DataLinkProtocol,
    pub payload: Box<[u8]>,
    /// Our own LocalTalk node ID, used to populate the LLAP `src_node` field.
    /// Zero for Ethernet destinations (LLAP is not used on EtherTalk).
    pub src_node_id: u8,
}

/// Trivial pcap codec that boxes the raw Ethernet frame bytes.
struct EtherTalkCodec;

impl pcap::PacketCodec for EtherTalkCodec {
    type Item = Box<[u8]>;

    fn decode(&mut self, packet: pcap::Packet) -> Self::Item {
        packet.data.into()
    }
}

pub struct PacketProcessor {
    /// RX capture, consumed into an async stream in `run()`.
    pcap_rx: Option<pcap::Capture<pcap::Active>>,
    /// TX capture, used for packet injection in the outbound loop.
    pcap_tx: Option<pcap::Capture<pcap::Active>>,
    outbound_rx: mpsc::Receiver<DataLinkPacket>,
    our_mac: Option<[u8; 6]>,
    /// Opened TashTalk instance, stored here and handed to the async task in `run()`.
    tashtalk: Option<TashTalk<tokio_serial::SerialStream>>,
    /// CRC features to set on the TashTalk firmware at startup.
    tashtalk_features: tashtalk::TashTalkFeatures,
    /// Sender to the LocalTalk pcap writer thread, if capture is enabled.
    pcap_sender: Option<std::sync::mpsc::SyncSender<(SystemTime, Vec<u8>)>>,
}

// ── Builder ───────────────────────────────────────────────────────────────────

/// Builder for [`PacketProcessor`].
///
/// At least one transport must be configured before calling [`build`](PacketProcessorBuilder::build).
///
/// # Example – EtherTalk only
/// ```no_run
/// # use tailtalk::PacketProcessor;
/// let (processor, handle) = PacketProcessor::builder()
///     .ethernet("eth0")
///     .build()?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Example – LocalTalk only
/// ```no_run
/// # use tailtalk::PacketProcessor;
/// let (processor, handle) = PacketProcessor::builder()
///     .localtalk("/dev/ttyUSB0")
///     .build()?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Example – both transports
/// ```no_run
/// # use tailtalk::PacketProcessor;
/// let (processor, handle) = PacketProcessor::builder()
///     .ethernet("eth0")
///     .localtalk("/dev/ttyUSB0")
///     .build()?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub struct PacketProcessorBuilder {
    ethernet_intf: Option<String>,
    localtalk_serial_path: Option<String>,
    tashtalk_features: tashtalk::TashTalkFeatures,
    pcap_path: Option<PathBuf>,
}

impl PacketProcessorBuilder {
    fn new() -> Self {
        Self {
            ethernet_intf: None,
            localtalk_serial_path: None,
            tashtalk_features: tashtalk::TashTalkFeatures::new(),
            pcap_path: None,
        }
    }

    /// Configure an EtherTalk transport on the given network interface.
    pub fn ethernet(mut self, intf: &str) -> Self {
        self.ethernet_intf = Some(intf.to_string());
        self
    }

    /// Configure which CRC features the TashTalk firmware should enable.
    ///
    /// By default no features are enabled.  Call this with a [`TashTalkFeatures`]
    /// value to turn on hardware CRC generation, checking, or both.
    pub fn tashtalk_features(mut self, features: tashtalk::TashTalkFeatures) -> Self {
        self.tashtalk_features = features;
        self
    }

    /// Configure a LocalTalk transport via a TashTalk serial adapter.
    ///
    /// The serial port is opened during [`build`](Self::build). The TashTalk
    /// async task (including node-ID registration) is started inside
    /// [`PacketProcessor::run`], which already receives the `addressing` and
    /// `ddp` handles needed for that setup.
    pub fn localtalk(mut self, serial_path: &str) -> Self {
        self.localtalk_serial_path = Some(serial_path.to_string());
        self
    }

    /// Enable LocalTalk pcap capture to the given file path.
    ///
    /// When set, every LocalTalk frame received from or sent to the TashTalk
    /// device is written to a pcap file (DLT 114 / LINKTYPE_LOCALTALK).
    /// Frames are written without the trailing CRC bytes.
    pub fn pcap_capture(mut self, path: impl Into<PathBuf>) -> Self {
        self.pcap_path = Some(path.into());
        self
    }

    /// Finalise the builder: open pcap captures and the serial port as configured.
    pub fn build(self) -> Result<(PacketProcessor, OutboundHandle), Error> {
        let mut pcap_rx: Option<pcap::Capture<pcap::Active>> = None;
        let mut pcap_tx: Option<pcap::Capture<pcap::Active>> = None;
        let mut our_mac: Option<[u8; 6]> = None;

        // ── EtherTalk setup ──────────────────────────────────────────────────
        if let Some(ref intf) = self.ethernet_intf {
            // Retrieve the interface MAC address cross-platform.
            let mac = mac_address_by_name(intf)?
                .ok_or_else(|| anyhow::anyhow!("no MAC address found for interface {}", intf))?;
            our_mac = Some(mac.bytes());

            // BPF filter: Phase 1 AppleTalk (0x809B), Phase 1 AARP (0x80F3),
            // and any IEEE 802.2 LLC/SNAP frame (length field ≤ 1500) for Phase 2.
            let filter = format!("(ether proto 0x809B or ether proto 0x80F3 or (ether[12:2] <= 1500)) and not ether src {mac}");

            tracing::info!("filter string: {filter}");
            // RX capture – promiscuous mode, filter applied.
            let mut rx = pcap::Capture::from_device(intf.as_str())?
                .promisc(true)
                .immediate_mode(true)
                .open()?;
            rx.filter(&filter, true)?;

            pcap_rx = Some(rx);

            // TX capture – separate handle used solely for packet injection.
            let tx = pcap::Capture::from_device(intf.as_str())?
                .promisc(true)
                .open()?;
            pcap_tx = Some(tx);

            tracing::info!("EtherTalk pcap captures opened on {}", intf);
        }

        // ── LocalTalk / TashTalk setup ───────────────────────────────────────
        // Open the serial port now so failures surface at build time.
        // The async task is deferred to run() where addressing/ddp handles are available.
        let tashtalk = if let Some(path) = self.localtalk_serial_path {
            let stream = tokio_serial::new(&path, 1_000_000)
                .flow_control(tokio_serial::FlowControl::Hardware)
                .open_native_async()
                .map_err(|e| anyhow::anyhow!("Failed to open TashTalk serial port '{}': {e}", path))?;
            Some(TashTalk::new(stream))
        } else {
            None
        };

        let (outbound_tx, outbound_rx) = mpsc::channel(100);

        let pcap_sender = self.pcap_path.and_then(spawn_pcap_writer);

        let processor = PacketProcessor {
            pcap_rx,
            pcap_tx,
            outbound_rx,
            our_mac,
            tashtalk,
            tashtalk_features: self.tashtalk_features,
            pcap_sender,
        };
        let handle = OutboundHandle { tx: outbound_tx };

        Ok((processor, handle))
    }
}

// ── LocalTalk pcap writer ─────────────────────────────────────────────────────

/// Spawn a background thread that writes LocalTalk frames to a pcap file.
///
/// Returns a `SyncSender` that the caller uses to submit `(timestamp, frame)`
/// pairs. The thread exits when the sender is dropped (channel closed).
/// Frames should not include the trailing 2-byte LocalTalk CRC.
fn spawn_pcap_writer(
    path: PathBuf,
) -> Option<std::sync::mpsc::SyncSender<(SystemTime, Vec<u8>)>> {
    use std::io::Write as _;

    let mut file = match std::fs::File::create(&path).map(std::io::BufWriter::new) {
        Ok(f) => f,
        Err(e) => {
            tracing::error!("Failed to create pcap file '{}': {e}", path.display());
            return None;
        }
    };

    // Classic pcap global header (little-endian, DLT 114 = LINKTYPE_LOCALTALK).
    let mut hdr = [0u8; 24];
    hdr[0..4].copy_from_slice(&0xa1b2c3d4u32.to_le_bytes()); // magic
    hdr[4..6].copy_from_slice(&2u16.to_le_bytes());           // version major
    hdr[6..8].copy_from_slice(&4u16.to_le_bytes());           // version minor
    // thiszone and sigfigs remain 0
    hdr[16..20].copy_from_slice(&65535u32.to_le_bytes());     // snaplen
    hdr[20..24].copy_from_slice(&114u32.to_le_bytes());       // LINKTYPE_LOCALTALK

    if let Err(e) = file.write_all(&hdr) {
        tracing::error!("Failed to write pcap global header: {e}");
        return None;
    }

    let (tx, rx) = std::sync::mpsc::sync_channel::<(SystemTime, Vec<u8>)>(512);

    std::thread::spawn(move || {
        use std::io::Write as _;
        tracing::info!("LocalTalk pcap capture started: '{}'", path.display());
        for (ts, data) in rx {
            let d = ts.duration_since(std::time::UNIX_EPOCH).unwrap_or_default();
            let ts_sec = d.as_secs() as u32;
            let ts_usec = d.subsec_micros();
            let len = data.len() as u32;
            let mut rec = [0u8; 16];
            rec[0..4].copy_from_slice(&ts_sec.to_le_bytes());
            rec[4..8].copy_from_slice(&ts_usec.to_le_bytes());
            rec[8..12].copy_from_slice(&len.to_le_bytes());
            rec[12..16].copy_from_slice(&len.to_le_bytes());
            if file.write_all(&rec).is_err() || file.write_all(&data).is_err() {
                tracing::error!("pcap write error, stopping capture");
                break;
            }
            let _ = file.flush();
        }
        tracing::info!("LocalTalk pcap capture stopped: '{}'", path.display());
    });

    Some(tx)
}

// ── PacketProcessor ───────────────────────────────────────────────────────────

impl PacketProcessor {
    pub fn builder() -> PacketProcessorBuilder {
        PacketProcessorBuilder::new()
    }

    /// Returns the Ethernet MAC address of the configured interface, or `None`
    /// if no EtherTalk transport was added.
    pub fn get_mac(&self) -> Option<[u8; 6]> {
        self.our_mac
    }

    pub async fn run(self, addressing: addressing::AddressingHandle, ddp: ddp::DdpHandle, token: CancellationToken) {
        // Extract pcap senders before any other field moves.
        // pcap_rx_sender goes into the TashTalk receive task; pcap_tx_sender stays in the outbound loop.
        let pcap_rx_sender = self.pcap_sender.clone();
        let pcap_tx_sender = self.pcap_sender;

        // ── EtherTalk RX task ────────────────────────────────────────────────
        if let Some(rx_cap) = self.pcap_rx {
            let ddp_rx = ddp.clone();
            let addressing_rx = addressing.clone();
            let rx_token = token.clone();

            let rx_cap = match rx_cap.setnonblock() {
                Ok(c) => c,
                Err(e) => {
                    tracing::error!("Failed to set pcap nonblocking: {e}");
                    return;
                }
            };
            let stream = match rx_cap.stream(EtherTalkCodec) {
                Ok(s) => s,
                Err(e) => {
                    tracing::error!("Failed to create pcap stream: {e}");
                    return;
                }
            };

            tokio::spawn(async move {
                tracing::info!("EtherTalk RX task started");
                tokio::pin!(stream);
                loop {
                    let data: Box<[u8]> = tokio::select! {
                        _ = rx_token.cancelled() => break,
                        result = stream.next() => match result {
                            Some(Ok(d)) => d,
                            Some(Err(e)) => { tracing::error!("pcap rx error: {e}"); break; }
                            None => break,
                        },
                    };

                    let ethertype_or_len = u16::from_be_bytes([data[12], data[13]]);

                    if ethertype_or_len <= 1500 {
                        // EtherTalk Phase 2 – IEEE 802.2 LLC/SNAP encapsulation.
                        match EtherTalkPhase2Frame::parse(&data) {
                            Err(e) => tracing::debug!("Phase 2 parse failed: {:?}", e),
                            Ok(header) => {
                                let payload = &data[EtherTalkPhase2Frame::len()..];
                                match header.protocol {
                                    EtherTalkPhase2Type::Ddp => {
                                        ddp_rx.received_pkt(
                                            payload,
                                            aarp::AddressSource::EtherTalkPhase2,
                                            header.src_mac,
                                        );
                                    }
                                    EtherTalkPhase2Type::Aarp => {
                                        if let Err(e) = addressing_rx.received_pkt(
                                            payload,
                                            aarp::AddressSource::EtherTalkPhase2,
                                        ) {
                                            tracing::error!("failed to relay Phase 2 AARP: {e}");
                                        }
                                    }
                                }
                            }
                        }
                    } else if ethertype_or_len == 0x80F3 {
                        // EtherTalk Phase 1 AARP.
                        if data.len() > 14
                            && let Err(e) = addressing_rx.received_pkt(
                                &data[14..],
                                aarp::AddressSource::EtherTalkPhase1,
                            )
                        {
                            tracing::error!("failed to relay Phase 1 AARP: {e}");
                        }
                    } else if ethertype_or_len == 0x809B {
                        // EtherTalk Phase 1 – LLAP encapsulated in Ethernet.
                        if data.len() > 14 + LlapPacket::LEN
                            && let Ok(llap) = LlapPacket::parse(&data[14..])
                        {
                            match llap.type_ {
                                LlapType::DdpShort => {
                                    let payload = &data[(14 + LlapPacket::LEN)..];
                                    if payload.len() >= 5
                                        && let Ok(headers) = DdpPacket::parse_short(
                                            payload,
                                            llap.dst_node,
                                            llap.src_node,
                                        )
                                    {
                                        let ddp_payload = payload[5..headers.len.min(payload.len())].into();
                                        let source_mac: [u8; 6] =
                                            data[6..12].try_into().unwrap();
                                        ddp_rx.received_parsed_pkt(
                                            headers,
                                            ddp_payload,
                                            aarp::AddressSource::EtherTalkPhase1,
                                            source_mac,
                                        );
                                    }
                                }
                                LlapType::DdpLong => {
                                    let payload = &data[(14 + LlapPacket::LEN)..];
                                    if payload.len() >= DdpPacket::LEN
                                        && let Ok(headers) = DdpPacket::parse(payload)
                                    {
                                        let ddp_payload =
                                            payload[DdpPacket::LEN..headers.len.min(payload.len())].into();
                                        let source_mac: [u8; 6] =
                                            data[6..12].try_into().unwrap();
                                        ddp_rx.received_parsed_pkt(
                                            headers,
                                            ddp_payload,
                                            aarp::AddressSource::EtherTalkPhase1,
                                            source_mac,
                                        );
                                    }
                                }
                                _ => {}
                            }
                        }
                    }
                }
            });
        }

        // ── TashTalk async task ──────────────────────────────────────────────
        // Spawned here rather than in the builder because it needs the addressing
        // and ddp handles, which callers construct using the OutboundHandle that
        // build() returns.
        let tashtalk_features = self.tashtalk_features;
        let tashtalk_tx: Option<mpsc::Sender<Vec<u8>>> = if let Some(mut tashtalk_instance) = self.tashtalk {
            let (tx, mut tashtalk_rx) = mpsc::channel::<Vec<u8>>(100);

            let ddp_handle = ddp.clone();
            let addressing_handle = addressing.clone();
            let tash_token = token.clone();

            tokio::spawn(async move {
                tracing::info!("Resetting TashTalk buffers...");
                if let Err(e) = tashtalk_instance.reset().await {
                    tracing::error!("Failed to reset TashTalk: {:?}", e);
                }

                tracing::info!("Setting TashTalk features: {:?}", tashtalk_features);
                if let Err(e) = tashtalk_instance
                    .set_features(tashtalk_features)
                    .await
                {
                    tracing::error!("Failed to set TashTalk features: {:?}", e);
                }

                match addressing_handle.addr().await {
                    Ok(addr) => {
                        let node_id = addr.node_number;
                        tracing::info!("Setting TashTalk node ID bits for node {}", node_id);
                        let mut node_bits = [0u8; 32];
                        let byte_idx = (node_id / 8) as usize;
                        let bit_idx = node_id % 8;
                        node_bits[byte_idx] |= 1 << bit_idx;
                        if let Err(e) = tashtalk_instance.set_node_ids(node_bits).await {
                            tracing::error!("Failed to set TashTalk node IDs: {:?}", e);
                        }
                    }
                    Err(e) => {
                        tracing::error!(
                            "Failed to get our AppleTalk address for TashTalk setup: {:?}",
                            e
                        );
                    }
                }

                tracing::info!("Starting TashTalk async loop");
                let mut last_receive_was_error = false;
                loop {
                    tokio::select! {
                        _ = tash_token.cancelled() => break,
                        frame_opt = tashtalk_rx.recv() => {
                            if let Some(frame) = frame_opt {
                                if let Err(e) = tashtalk_instance.send_frame(&frame).await {
                                    tracing::error!("TashTalk send_frame error: {:?}", e);
                                }
                            } else {
                                break;
                            }
                        }
                        res = tashtalk_instance.receive_frame() => {
                            match res {
                                Ok(Some(data)) => {
                                    last_receive_was_error = false;
                                    if let Some(ref tx) = pcap_rx_sender {
                                        let _ = tx.try_send((SystemTime::now(), data.clone()));
                                    }
                                    if data.len() < 3 { continue; }
                                    if let Ok(llap) = LlapPacket::parse(&data) {
                                        match llap.type_ {
                                            LlapType::DdpShort => {
                                                tracing::info!("TashTalk: LocalTalk DDP Short");
                                                if let Ok(headers) = DdpPacket::parse_short(
                                                    &data[3..],
                                                    llap.dst_node,
                                                    llap.src_node,
                                                ) {
                                                    tracing::info!(
                                                        "LLAP: {:?}, DDP Short: {:?}",
                                                        llap,
                                                        headers
                                                    );
                                                    let end = (3 + headers.len).min(data.len());
                                                    let payload = data[8..end].to_vec().into_boxed_slice();
                                                    ddp_handle.received_parsed_pkt(
                                                        headers,
                                                        payload,
                                                        aarp::AddressSource::LocalTalk,
                                                        [0; 6],
                                                    );
                                                }
                                            }
                                            LlapType::DdpLong => {
                                                tracing::info!("TashTalk: LocalTalk DDP Long");
                                                if let Ok(headers) = DdpPacket::parse(&data[3..]) {
                                                    let end = (3 + headers.len).min(data.len());
                                                    let payload =
                                                        data[(3 + DdpPacket::LEN)..end].to_vec().into_boxed_slice();
                                                    ddp_handle.received_parsed_pkt(
                                                        headers,
                                                        payload,
                                                        aarp::AddressSource::LocalTalk,
                                                        [0; 6],
                                                    );
                                                }
                                            }
                                            _ => {}
                                        }
                                    }
                                }
                                Ok(None) => {
                                    // tokio-util emits one None after every decode error as a
                                    // recovery artifact; only treat None as real EOF otherwise.
                                    if last_receive_was_error {
                                        last_receive_was_error = false;
                                        continue;
                                    }
                                    break;
                                }
                                Err(e) => {
                                    last_receive_was_error = true;
                                    tracing::error!("TashTalk receive error: {:?}", e);
                                }
                            }
                        }
                    }
                }
            });

            Some(tx)
        } else {
            None
        };

        // ── Outbound TX loop ─────────────────────────────────────────────────
        let our_mac = self.our_mac.unwrap_or([0; 6]);
        let mut rx = self.outbound_rx;
        let mut pcap_tx = self.pcap_tx;

        loop {
            let pkt = tokio::select! {
                _ = token.cancelled() => break,
                pkt = rx.recv() => match pkt { Some(p) => p, None => break },
            };
            let mut output_buf: [u8; 1500] = [0u8; 1500];

            let final_size = match pkt.protocol {
                DataLinkProtocol::Ddp => {
                    match pkt.dest_node {
                        addressing::Node::EtherTalkPhase1(mac) => {
                            output_buf[0..6].copy_from_slice(&mac);
                            output_buf[6..12].copy_from_slice(&our_mac);
                            output_buf[12] = 0x80;
                            output_buf[13] = 0x9B;
                            let dst_node = if pkt.payload.len() > 8 { pkt.payload[8] } else { 0 };
                            let src_node = if pkt.payload.len() > 9 { pkt.payload[9] } else { 0 };
                            output_buf[14] = dst_node;
                            output_buf[15] = src_node;
                            output_buf[16] = 2;
                            let payload_len = pkt.payload.len();
                            output_buf[17..17 + payload_len].copy_from_slice(&pkt.payload);
                            17 + payload_len
                        }
                        addressing::Node::EtherTalkPhase2(mac) => {
                            output_buf[0..6].copy_from_slice(&mac);
                            output_buf[6..12].copy_from_slice(&our_mac);
                            let payload_len = pkt.payload.len();
                            let total_payload = 8 + payload_len;
                            output_buf[12] = (total_payload >> 8) as u8;
                            output_buf[13] = (total_payload & 0xFF) as u8;
                            output_buf[14] = 0xAA;
                            output_buf[15] = 0xAA;
                            output_buf[16] = 0x03;
                            output_buf[17] = 0x08;
                            output_buf[18] = 0x00;
                            output_buf[19] = 0x07;
                            output_buf[20] = 0x80;
                            output_buf[21] = 0x9B;
                            output_buf[22..22 + payload_len].copy_from_slice(&pkt.payload);
                            14 + total_payload
                        }
                        addressing::Node::LocalTalk(node_id) => {
                            let llap_pkt = LlapPacket {
                                dst_node: node_id,
                                src_node: pkt.src_node_id,
                                type_: LlapType::DdpShort,
                            };
                            let header_len = llap_pkt
                                .to_bytes(&mut output_buf)
                                .expect("failed to frame LLAP");

                            let payload_len = pkt.payload.len();
                            output_buf[header_len..header_len + payload_len]
                                .copy_from_slice(&pkt.payload);

                            let frame_end = header_len + payload_len;
                            let crc = tashtalk::lt_crc(&output_buf[..frame_end]);
                            output_buf[frame_end] = crc[0];
                            output_buf[frame_end + 1] = crc[1];

                            frame_end + 2
                        }
                    }
                }
                DataLinkProtocol::Aarp => {
                    let payload_len = pkt.payload.len();
                    match pkt.dest_node {
                        addressing::Node::EtherTalkPhase1(mac) => {
                            output_buf[0..6].copy_from_slice(&mac);
                            output_buf[6..12].copy_from_slice(&our_mac);
                            output_buf[12] = 0x80;
                            output_buf[13] = 0xF3;
                            output_buf[14..14 + payload_len].copy_from_slice(&pkt.payload);
                            14 + payload_len
                        }
                        addressing::Node::EtherTalkPhase2(mac) => {
                            output_buf[0..6].copy_from_slice(&mac);
                            output_buf[6..12].copy_from_slice(&our_mac);
                            let total_payload = 8 + payload_len;
                            output_buf[12] = (total_payload >> 8) as u8;
                            output_buf[13] = (total_payload & 0xFF) as u8;
                            output_buf[14] = 0xAA;
                            output_buf[15] = 0xAA;
                            output_buf[16] = 0x03;
                            output_buf[17] = 0x00;
                            output_buf[18] = 0x00;
                            output_buf[19] = 0x00;
                            output_buf[20] = 0x80;
                            output_buf[21] = 0xF3;
                            output_buf[22..22 + payload_len].copy_from_slice(&pkt.payload);
                            14 + total_payload
                        }
                        addressing::Node::LocalTalk(_) => 0,
                    }
                }
            };

            if final_size == 0 {
                continue;
            }

            match pkt.dest_node {
                addressing::Node::EtherTalkPhase1(_) | addressing::Node::EtherTalkPhase2(_) => {
                    if let Some(ref mut tx) = pcap_tx {
                        let padded_size = final_size.max(60);
                        if let Err(e) = tx.sendpacket(&output_buf[..padded_size]) {
                            tracing::error!("failed to send packet: {e}");
                        }
                    }
                }
                addressing::Node::LocalTalk(_) => {
                    if let Some(tx) = &tashtalk_tx {
                        tracing::info!("Sending to Tashtalk tx: {:X?}", &output_buf[..final_size]);
                        if let Err(e) = tx.send(output_buf[..final_size].to_vec()).await {
                            tracing::error!("Failed to send to Tashtalk tx: {}", e);
                        }
                    }
                    // Capture outbound frame without the trailing 2 CRC bytes.
                    if let Some(ref tx) = pcap_tx_sender {
                        let frame_len = final_size.saturating_sub(2);
                        let _ = tx.try_send((SystemTime::now(), output_buf[..frame_len].to_vec()));
                    }
                }
            }
        }
    }
}

// ── OutboundHandle ────────────────────────────────────────────────────────────

#[derive(Clone)]
pub struct OutboundHandle {
    tx: mpsc::Sender<DataLinkPacket>,
}

impl OutboundHandle {
    pub fn new(tx: mpsc::Sender<DataLinkPacket>) -> Self {
        Self { tx }
    }

    pub async fn send(&self, packet: DataLinkPacket) -> Result<(), Error> {
        self.tx.send(packet).await?;
        Ok(())
    }
}

// ── TalkStack ─────────────────────────────────────────────────────────────────

/// A lightweight handle that can be used to shut down a running [`TalkStack`]
/// from another task without holding the full stack.
#[derive(Clone)]
pub struct ShutdownHandle(CancellationToken);

impl ShutdownHandle {
    /// Signal the stack to shut down all actors.
    pub fn shutdown(&self) {
        self.0.cancel();
    }
}

/// Handles to all mandatory AppleTalk stack layers.
///
/// Obtain one via [`TalkStack::builder`]. Once built, spawn services on top:
///
/// ```no_run
/// # use tailtalk::{TalkStack, afp::{AfpServer, AfpServerConfig}};
/// # async fn example() -> anyhow::Result<()> {
/// let stack = TalkStack::builder()
///     .ethernet("eth0")
///     .build()
///     .await?;
///
/// let _afp = AfpServer::spawn(&stack.ddp, &stack.nbp, Some(254), AfpServerConfig::default(), stack.token()).await?;
/// # Ok(()) }
/// ```
pub struct TalkStack {
    pub addressing: addressing::AddressingHandle,
    pub ddp: ddp::DdpHandle,
    pub nbp: nbp::NbpHandle,
    pub echo: echo::EchoHandle,
    token: CancellationToken,
}

impl TalkStack {
    /// Signal all stack actors to stop.
    pub fn shutdown(&self) {
        self.token.cancel();
    }

    /// Wait until [`shutdown`](Self::shutdown) has been called.
    pub async fn wait_for_shutdown(&self) {
        self.token.cancelled().await;
    }

    /// Return a [`ShutdownHandle`] that can be sent to another task to
    /// trigger shutdown remotely.
    pub fn shutdown_handle(&self) -> ShutdownHandle {
        ShutdownHandle(self.token.clone())
    }

    /// Return a clone of the stack's cancellation token, suitable for passing
    /// to sub-services such as [`AfpServer::spawn`](afp::AfpServer::spawn).
    pub fn token(&self) -> CancellationToken {
        self.token.clone()
    }
}

/// Builder for [`TalkStack`].
pub struct TalkStackBuilder {
    ethernet_intf: Option<String>,
    localtalk_serial_path: Option<String>,
    tashtalk_features: tashtalk::TashTalkFeatures,
    fixed_addr: Option<tailtalk_packets::aarp::AppleTalkAddress>,
    pcap_path: Option<PathBuf>,
}

impl TalkStack {
    pub fn builder() -> TalkStackBuilder {
        TalkStackBuilder {
            ethernet_intf: None,
            localtalk_serial_path: None,
            tashtalk_features: tashtalk::TashTalkFeatures::new(),
            fixed_addr: None,
            pcap_path: None,
        }
    }
}

impl TalkStackBuilder {
    /// Configure an EtherTalk transport on the given network interface.
    pub fn ethernet(mut self, intf: &str) -> Self {
        self.ethernet_intf = Some(intf.to_string());
        self
    }

    /// Configure a LocalTalk transport via a TashTalk serial adapter.
    pub fn localtalk(mut self, serial_path: &str) -> Self {
        self.localtalk_serial_path = Some(serial_path.to_string());
        self
    }

    /// Configure which CRC features the TashTalk firmware should enable.
    pub fn tashtalk_features(mut self, features: tashtalk::TashTalkFeatures) -> Self {
        self.tashtalk_features = features;
        self
    }

    /// Enable LocalTalk pcap capture to the given file path.
    ///
    /// Forwarded to [`PacketProcessorBuilder::pcap_capture`].
    pub fn pcap_capture(mut self, path: impl Into<PathBuf>) -> Self {
        self.pcap_path = Some(path.into());
        self
    }

    /// Use a fixed AppleTalk address instead of probing via AARP.
    pub fn fixed_address(mut self, network: u16, node: u8) -> Self {
        self.fixed_addr = Some(tailtalk_packets::aarp::AppleTalkAddress {
            network_number: network,
            node_number: node,
        });
        self
    }

    /// Launch the full AppleTalk stack and return handles to each layer.
    ///
    /// Spawns actors for AARP/Addressing, DDP, AEP (Echo), and NBP in dependency
    /// order, then starts the [`PacketProcessor`] background task.
    pub async fn build(self) -> Result<TalkStack, Error> {
        let mut pp = PacketProcessor::builder().tashtalk_features(self.tashtalk_features);
        if let Some(ref intf) = self.ethernet_intf {
            pp = pp.ethernet(intf);
        }
        if let Some(ref path) = self.localtalk_serial_path {
            pp = pp.localtalk(path);
        }
        if let Some(path) = self.pcap_path {
            pp = pp.pcap_capture(path);
        }
        let (processor, outbound) = pp.build()?;

        // On LocalTalk-only setups, short DDP carries no network number (implying 0).
        // If we let AARP pick network 1, NBP advertises net 1 but packets appear as
        // net 0 — clients reject server-initiated requests (WriteContinue) due to the
        // mismatch. Force network 0 so the address is consistent end-to-end.
        let fixed_addr = if self.fixed_addr.is_some() {
            self.fixed_addr
        } else if self.ethernet_intf.is_none() && self.localtalk_serial_path.is_some() {
            Some(tailtalk_packets::aarp::AppleTalkAddress {
                network_number: 0,
                node_number: rand::rng().random_range(1..=253u8),
            })
        } else {
            None
        };

        let mac = processor.get_mac().unwrap_or([0u8; 6]);
        let addressing = addressing::Addressing::spawn(mac, outbound.clone(), fixed_addr);
        let ddp = ddp::DdpProcessor::spawn(addressing.clone(), outbound);
        let echo = echo::Echo::spawn(&ddp).await;
        let nbp = nbp::Nbp::spawn(&ddp, addressing.clone()).await;

        let token = CancellationToken::new();
        tokio::spawn(processor.run(addressing.clone(), ddp.clone(), token.clone()));

        // Wait until AARP has confirmed our node address before returning.
        // Without this, callers could attempt to send packets before addressing
        // is ready, especially when probing is required (no fixed address).
        addressing.addr().await?;

        Ok(TalkStack { addressing, ddp, nbp, echo, token })
    }
}

// ── AFP time helpers ──────────────────────────────────────────────────────────

/// Converts a SystemTime to a 32-bit AFP date for **AFP 2.x** (seconds since Jan 1, 2000).
///
/// AFP 2.0 and later use midnight, January 1, 2000 as the epoch. Times before the
/// epoch are clamped to 0.
pub fn time_to_afp(time: SystemTime) -> u32 {
    // Seconds from Unix epoch (Jan 1, 1970) to AFP 2.x epoch (Jan 1, 2000)
    const AFP2_EPOCH_OFFSET: u64 = 946_684_800;

    let unix_secs = time
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();

    unix_secs.saturating_sub(AFP2_EPOCH_OFFSET) as u32
}

/// Converts a SystemTime to a 32-bit AFP date for **AFP 1.x** (seconds since Jan 1, 1904).
///
/// AFP 1.x (and classic Mac OS) use midnight, January 1, 1904 as the epoch —
/// 2,082,844,800 seconds before the Unix epoch.
pub fn time_to_afp_v1(time: SystemTime) -> u32 {
    // Seconds from Jan 1, 1904 (Mac OS classic epoch) to Jan 1, 1970 (Unix epoch)
    const MAC_TO_UNIX_EPOCH_OFFSET: u64 = 2_082_844_800;

    let unix_secs = time
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();

    (unix_secs + MAC_TO_UNIX_EPOCH_OFFSET) as u32
}