rscamper 0.2.2

Rust interface to scamper network measurement tool
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
// rscamper - Rust wrapper for the scamper control interface
//
// Copyright (C) 2026 Dimitrios Giakatos
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3.

use std::collections::VecDeque;
use std::ffi::{CStr, CString};
use std::ptr;
use std::time::Duration;

use crate::ffi::libscamperctrl::{self, ScamperCtrlT, ScamperInstT, ScamperTaskT,
    SCAMPER_CTRL_TYPE_DATA, SCAMPER_CTRL_TYPE_MORE, SCAMPER_CTRL_TYPE_ERR,
    SCAMPER_CTRL_TYPE_EOF, SCAMPER_CTRL_TYPE_FATAL};
use crate::ffi::scamper_file;
use crate::inst::{ScamperInst, InstData};
use crate::task::ScamperTask;
use crate::mux::ScamperMux;
use crate::vp::ScamperVp;
use crate::file::{ScamperFile, ScamperObject, parse_scamper_obj};

/// A queued item from a scamper instance.
struct CtrlItem {
    /// Raw pointer to the InstData for the producing instance.
    inst_data: *mut InstData,
    /// Name of the instance that produced this object (path or address).
    inst_name: Option<String>,
    obj: ScamperObject,
}

/// A measurement result together with the instance that produced it.
pub struct ResponseItem {
    pub obj: ScamperObject,
    /// Name of the instance that produced this result (path or address).
    pub inst_name: Option<String>,
}

/// Internal state for ScamperCtrl, stored as the ctrl param.
struct CtrlData {
    objs: VecDeque<CtrlItem>,
    errors: VecDeque<String>,
    /// Total outstanding tasks across all instances.
    task_count: usize,
    /// Whether to yield List/Cycle meta-objects from responses().
    meta: bool,
    /// Optional output file for all results.
    outfile: Option<ScamperFile>,
}

/// The C callback invoked by libscamperctrl for all events.
///
/// # Safety
/// This function is called from C. All pointer accesses use the params we
/// previously set, so they are valid for the lifetime of the ctrl/inst.
unsafe extern "C" fn ctrl_cb(
    c_inst: *mut ScamperInstT,
    kind: u8,
    c_task: *mut ScamperTaskT,
    data: *const libc::c_void,
    len: libc::size_t,
) {
    let c_ctrl = unsafe { libscamperctrl::scamper_inst_ctrl_get(c_inst) };
    let ctrl_data = unsafe { &mut *(libscamperctrl::scamper_ctrl_param_get(c_ctrl) as *mut CtrlData) };
    let inst_data = unsafe { &mut *(libscamperctrl::scamper_inst_param_get(c_inst) as *mut InstData) };

    // If a task is associated with this event, it has completed — remove it.
    if !c_task.is_null() {
        if let Some(pos) = inst_data.tasks.iter().position(|&t| t == c_task) {
            inst_data.tasks.swap_remove(pos);
            if ctrl_data.task_count > 0 {
                ctrl_data.task_count -= 1;
            }
        }
    }

    match kind {
        SCAMPER_CTRL_TYPE_DATA => {
            // Feed the raw warts data into the readbuf, then parse one object.
            unsafe { scamper_file::scamper_file_readbuf_add(inst_data.c_rb, data, len) };
            let mut o_type: u16 = 0;
            let mut o_data: *mut libc::c_void = ptr::null_mut();
            unsafe { scamper_file::scamper_file_read(inst_data.c_f, ptr::null(), &mut o_type, &mut o_data) };
            if o_data.is_null() { return; }

            if let Some(obj) = unsafe { parse_scamper_obj(o_type, o_data) } {
                if let Some(ref mut outfile) = ctrl_data.outfile {
                    let _ = outfile.write(&obj);
                }
                let name_ptr = unsafe { libscamperctrl::scamper_inst_name_get(c_inst) };
                let inst_name = if name_ptr.is_null() {
                    None
                } else {
                    Some(unsafe { CStr::from_ptr(name_ptr) }.to_string_lossy().into_owned())
                };
                inst_data.queued += 1;
                ctrl_data.objs.push_back(CtrlItem {
                    inst_data: inst_data as *mut InstData,
                    inst_name,
                    obj,
                });
            }
        }

        SCAMPER_CTRL_TYPE_ERR => {
            let msg = if data.is_null() {
                "error from instance".to_string()
            } else {
                let cstr = unsafe { CStr::from_ptr(data as *const libc::c_char) };
                cstr.to_string_lossy().into_owned()
            };
            ctrl_data.errors.push_back(msg);
        }

        SCAMPER_CTRL_TYPE_FATAL => {
            let c_ctrl2 = unsafe { libscamperctrl::scamper_inst_ctrl_get(c_inst) };
            let errptr = unsafe { libscamperctrl::scamper_ctrl_strerror(c_ctrl2) };
            let msg = if errptr.is_null() {
                "fatal error".to_string()
            } else {
                unsafe { CStr::from_ptr(errptr) }.to_string_lossy().into_owned()
            };
            ctrl_data.errors.push_back(format!("fatal: {}", msg));
        }

        SCAMPER_CTRL_TYPE_EOF => {
            inst_data.eof = true;
        }

        SCAMPER_CTRL_TYPE_MORE => {
            // More capacity available; no action by default.
        }

        _ => {}
    }
}

/// Parameters for attaching to a scamper instance (optional).
pub struct AttachParams {
    inner: *mut libscamperctrl::ScamperAttpT,
}

impl AttachParams {
    pub fn new() -> Option<Self> {
        let inner = unsafe { libscamperctrl::scamper_attp_alloc() };
        if inner.is_null() { None } else { Some(AttachParams { inner }) }
    }

    pub fn set_list_id(&mut self, id: u32) {
        unsafe { libscamperctrl::scamper_attp_listid_set(self.inner, id) };
    }

    pub fn set_cycle_id(&mut self, id: u32) {
        unsafe { libscamperctrl::scamper_attp_cycleid_set(self.inner, id) };
    }

    pub fn set_priority(&mut self, priority: u32) {
        unsafe { libscamperctrl::scamper_attp_priority_set(self.inner, priority) };
    }
}

impl Drop for AttachParams {
    fn drop(&mut self) {
        unsafe { libscamperctrl::scamper_attp_free(self.inner) };
    }
}

/// An error from a ScamperCtrl event loop.
#[derive(Debug)]
pub struct ScamperCtrlError(pub String);

impl std::fmt::Display for ScamperCtrlError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl std::error::Error for ScamperCtrlError {}

/// Controller for one or more scamper instances.
///
/// Create with `ScamperCtrl::new()`. Add instances with `add_unix`, `add_inet`,
/// or `add_remote`. Issue measurements with `do_trace`, `do_ping`, etc.
/// Consume results with the `responses()` iterator.
///
/// # Example
/// ```no_run
/// use rscamper::ctrl::ScamperCtrl;
/// let mut ctrl = ScamperCtrl::new(false, None).unwrap();
/// let inst = ctrl.add_unix("/var/run/scamper.sock").unwrap();
/// let _task = ctrl.do_trace(&inst, "1.2.3.4", None, None, None, None, None,
///                            None, None, None, None, None, None, None, None,
///                            None, None, None, None, None, None, None).unwrap();
/// inst.done();
/// for obj in ctrl.responses(None) {
///     // process obj
/// }
/// ```
pub struct ScamperCtrl {
    c: *mut ScamperCtrlT,
    data: *mut CtrlData,
    insts: Vec<ScamperInst>,
    muxes: Vec<ScamperMux>,
}

impl ScamperCtrl {
    /// Create a new ScamperCtrl.
    ///
    /// - `meta`: if true, `responses()` also yields List and Cycle objects.
    /// - `outfile`: optional output file to receive all results.
    pub fn new(meta: bool, outfile: Option<ScamperFile>) -> Result<Self, String> {
        let data = Box::into_raw(Box::new(CtrlData {
            objs: VecDeque::new(),
            errors: VecDeque::new(),
            task_count: 0,
            meta,
            outfile,
        }));
        let c = unsafe { libscamperctrl::scamper_ctrl_alloc(ctrl_cb) };
        if c.is_null() {
            // Recover the Box before returning error
            unsafe { drop(Box::from_raw(data)) };
            return Err("could not allocate ScamperCtrl".into());
        }
        unsafe { libscamperctrl::scamper_ctrl_param_set(c, data as *mut libc::c_void) };
        Ok(ScamperCtrl { c, data, insts: Vec::new(), muxes: Vec::new() })
    }

    fn ctrl_strerror(&self) -> String {
        let ptr = unsafe { libscamperctrl::scamper_ctrl_strerror(self.c) };
        if ptr.is_null() {
            "unknown error".into()
        } else {
            unsafe { CStr::from_ptr(ptr) }.to_string_lossy().into_owned()
        }
    }

    /// Add a local scamper instance via a unix-domain socket.
    pub fn add_unix(&mut self, path: &str) -> Result<ScamperInst, String> {
        let c_path = CString::new(path).map_err(|e| e.to_string())?;
        let c = unsafe {
            libscamperctrl::scamper_inst_unix(self.c, ptr::null(), c_path.as_ptr())
        };
        if c.is_null() { return Err(self.ctrl_strerror()); }
        let inst = unsafe { ScamperInst::from_ptr(c) };
        Ok(inst)
    }

    /// Add a scamper instance via TCP.
    pub fn add_inet(&mut self, port: u16, addr: Option<&str>) -> Result<ScamperInst, String> {
        let c_addr = match addr {
            Some(a) => Some(CString::new(a).map_err(|e| e.to_string())?),
            None => None,
        };
        let addr_ptr = c_addr.as_ref().map_or(ptr::null(), |s| s.as_ptr());
        let c = unsafe {
            libscamperctrl::scamper_inst_inet(self.c, ptr::null(), addr_ptr, port)
        };
        if c.is_null() { return Err(self.ctrl_strerror()); }
        let inst = unsafe { ScamperInst::from_ptr(c) };
        Ok(inst)
    }

    /// Add a remote scamper instance via a unix-domain socket.
    pub fn add_remote(&mut self, path: &str) -> Result<ScamperInst, String> {
        let c_path = CString::new(path).map_err(|e| e.to_string())?;
        let c = unsafe { libscamperctrl::scamper_inst_remote(self.c, c_path.as_ptr()) };
        if c.is_null() { return Err(self.ctrl_strerror()); }
        let inst = unsafe { ScamperInst::from_ptr(c) };
        Ok(inst)
    }

    /// Add a multiplexor interface.
    pub fn add_mux(&mut self, path: &str) -> Result<&ScamperMux, String> {
        let c_path = CString::new(path).map_err(|e| e.to_string())?;
        let c = unsafe { libscamperctrl::scamper_mux_add(self.c, c_path.as_ptr()) };
        if c.is_null() { return Err(self.ctrl_strerror()); }
        let mux = unsafe { ScamperMux::from_ptr(c).ok_or("null mux")? };
        self.muxes.push(mux);
        Ok(self.muxes.last().unwrap())
    }

    /// Add a VP instance (via a mux).
    pub fn add_vp(&mut self, vp: &ScamperVp) -> Result<ScamperInst, String> {
        let c = unsafe { libscamperctrl::scamper_inst_vp(self.c, vp.inner) };
        if c.is_null() { return Err(self.ctrl_strerror()); }
        let inst = unsafe { ScamperInst::from_ptr(c) };
        Ok(inst)
    }

    /// Return the vantage points available across all mux connections.
    pub fn vps(&self) -> Vec<ScamperVp> {
        self.muxes.iter().flat_map(|m| m.vps()).collect()
    }

    /// True if all instances have signalled done and no tasks are outstanding.
    pub fn is_done(&self) -> bool {
        let ctrl_data = unsafe { &*self.data };
        if !ctrl_data.objs.is_empty() { return false; }
        unsafe { libscamperctrl::scamper_ctrl_isdone(self.c) != 0 }
    }

    /// Return any pending error messages (non-fatal).
    pub fn errors(&mut self) -> Vec<String> {
        let ctrl_data = unsafe { &mut *self.data };
        ctrl_data.errors.drain(..).collect()
    }

    /// Issue a raw command string on an instance. Returns a ScamperTask handle.
    pub fn do_cmd(&mut self, inst: &ScamperInst, cmd: &str) -> Result<ScamperTask, String> {
        let cstr = CString::new(cmd).map_err(|e| e.to_string())?;
        let task_ptr = unsafe {
            libscamperctrl::scamper_inst_do(inst.c, cstr.as_ptr(), ptr::null_mut())
        };
        if task_ptr.is_null() {
            return Err(format!("could not schedule command on {}", inst));
        }
        let inst_data = unsafe { &mut *inst.data };
        inst_data.tasks.push(task_ptr);
        let ctrl_data = unsafe { &mut *self.data };
        ctrl_data.task_count += 1;
        Ok(unsafe { ScamperTask::from_ptr(task_ptr) })
    }

    // -----------------------------------------------------------------------
    // Traceroute
    // -----------------------------------------------------------------------

    #[allow(clippy::too_many_arguments)]
    pub fn do_trace(
        &mut self,
        inst: &ScamperInst,
        dst: &str,
        confidence: Option<u8>,
        dport: Option<u16>,
        icmp_id: Option<u16>,
        icmp_sum: Option<u16>,
        firsthop: Option<u8>,
        gaplimit: Option<u8>,
        loops: Option<u8>,
        hoplimit: Option<u8>,
        pmtud: Option<bool>,
        squeries: Option<u8>,
        ptr_lookup: Option<bool>,
        payload: Option<&[u8]>,
        method: Option<&str>,
        attempts: Option<u8>,
        all_attempts: Option<bool>,
        rtr: Option<&str>,
        sport: Option<u16>,
        src: Option<&str>,
        tos: Option<u8>,
        userid: Option<u32>,
        wait_timeout: Option<Duration>,
        wait_probe: Option<Duration>,
    ) -> Result<ScamperTask, String> {
        let mut args = vec!["trace".to_string()];

        let m = method.map(|s| s.to_lowercase());

        if sport.is_some() || dport.is_some() {
            match &m {
                None => return Err("specify method when specifying port".into()),
                Some(mm) if !mm.starts_with("tcp") && !mm.starts_with("udp") =>
                    return Err(format!("cannot specify ports with method {}", mm)),
                _ => {}
            }
        }
        if let Some(s) = sport { args.push(format!("-s {}", s)); }
        if let Some(d) = dport { args.push(format!("-d {}", d)); }
        if let Some(cs) = icmp_sum { args.push(format!("-d {}", cs)); }
        if let Some(id) = icmp_id { args.push(format!("-s {}", id)); }
        if let Some(c) = confidence { args.push(format!("-C {}", c)); }
        if let Some(f) = firsthop { args.push(format!("-f {}", f)); }
        if let Some(g) = gaplimit { args.push(format!("-g {}", g)); }
        if let Some(l) = loops { args.push(format!("-l {}", l)); }
        if let Some(m) = hoplimit { args.push(format!("-m {}", m)); }
        if pmtud == Some(true) { args.push("-M".into()); }
        if let Some(n) = squeries { args.push(format!("-N {}", n)); }
        if ptr_lookup == Some(true) { args.push("-O ptr".into()); }
        if let Some(p) = payload {
            args.push(format!("-p {}", hex::encode(p)));
        }
        if let Some(ref meth) = method { args.push(format!("-P {}", meth)); }
        if let Some(q) = attempts { args.push(format!("-q {}", q)); }
        if all_attempts == Some(true) { args.push("-Q".into()); }
        if let Some(r) = rtr { args.push(format!("-r {}", r)); }
        if let Some(s) = src { args.push(format!("-S {}", s)); }
        if let Some(t) = tos { args.push(format!("-t {}", t)); }
        if let Some(u) = userid { args.push(format!("-U {}", u)); }
        if let Some(w) = wait_timeout {
            args.push(format!("-w {}s", w.as_secs_f64()));
        }
        if let Some(w) = wait_probe {
            args.push(format!("-W {}s", w.as_secs_f64()));
        }
        args.push(dst.to_string());

        self.do_cmd(inst, &args.join(" "))
    }

    // -----------------------------------------------------------------------
    // MDA Traceroute
    // -----------------------------------------------------------------------

    #[allow(clippy::too_many_arguments)]
    pub fn do_tracelb(
        &mut self,
        inst: &ScamperInst,
        dst: &str,
        confidence: Option<u8>,
        dport: Option<u16>,
        firsthop: Option<u8>,
        gaplimit: Option<u8>,
        method: Option<&str>,
        attempts: Option<u8>,
        ptr_lookup: Option<bool>,
        rtr: Option<&str>,
        sport: Option<u16>,
        tos: Option<u8>,
        userid: Option<u32>,
        wait_timeout: Option<Duration>,
        wait_probe: Option<Duration>,
    ) -> Result<ScamperTask, String> {
        let mut args = vec!["tracelb".to_string()];

        if let Some(c) = confidence { args.push(format!("-c {}", c)); }
        if let Some(d) = dport { args.push(format!("-d {}", d)); }
        if let Some(f) = firsthop { args.push(format!("-f {}", f)); }
        if let Some(g) = gaplimit { args.push(format!("-g {}", g)); }
        if let Some(ref meth) = method { args.push(format!("-P {}", meth)); }
        if let Some(q) = attempts { args.push(format!("-q {}", q)); }
        if ptr_lookup == Some(true) { args.push("-O ptr".into()); }
        if let Some(r) = rtr { args.push(format!("-r {}", r)); }
        if let Some(s) = sport { args.push(format!("-s {}", s)); }
        if let Some(t) = tos { args.push(format!("-t {}", t)); }
        if let Some(u) = userid { args.push(format!("-U {}", u)); }
        if let Some(w) = wait_timeout {
            args.push(format!("-w {}s", w.as_secs_f64()));
        }
        if let Some(w) = wait_probe {
            args.push(format!("-W {}s", w.as_secs_f64()));
        }
        args.push(dst.to_string());

        self.do_cmd(inst, &args.join(" "))
    }

    // -----------------------------------------------------------------------
    // Ping
    // -----------------------------------------------------------------------

    #[allow(clippy::too_many_arguments)]
    pub fn do_ping(
        &mut self,
        inst: &ScamperInst,
        dst: &str,
        tcp_ack: Option<u32>,
        tcp_seq: Option<u32>,
        attempts: Option<u16>,
        icmp_id: Option<u16>,
        icmp_seq: Option<u16>,
        icmp_sum: Option<u16>,
        dport: Option<u16>,
        sport: Option<u16>,
        wait_probe: Option<Duration>,
        ttl: Option<u8>,
        mtu: Option<u16>,
        stop_count: Option<u16>,
        method: Option<&str>,
        payload: Option<&[u8]>,
        rtr: Option<&str>,
        recordroute: Option<bool>,
        size: Option<u16>,
        src: Option<&str>,
        wait_timeout: Option<Duration>,
        tos: Option<u8>,
        userid: Option<u32>,
    ) -> Result<ScamperTask, String> {
        let mut args = vec!["ping".to_string()];

        if let Some(a) = tcp_ack { args.push(format!("-A {}", a)); }
        if let Some(a) = tcp_seq { args.push(format!("-A {}", a)); }
        if let Some(p) = payload {
            args.push(format!("-B {}", hex::encode(p)));
        }
        if let Some(c) = attempts { args.push(format!("-c {}", c)); }
        if let Some(cs) = icmp_sum { args.push(format!("-C {}", cs)); }
        if let Some(d) = dport { args.push(format!("-d {}", d)); }
        if let Some(s) = icmp_seq { args.push(format!("-d {}", s)); }
        if let Some(f) = sport { args.push(format!("-F {}", f)); }
        if let Some(id) = icmp_id { args.push(format!("-F {}", id)); }
        if let Some(w) = wait_probe {
            args.push(format!("-i {}s", w.as_secs_f64()));
        }
        if let Some(m) = ttl { args.push(format!("-m {}", m)); }
        if let Some(m) = mtu { args.push(format!("-M {}", m)); }
        if let Some(o) = stop_count { args.push(format!("-o {}", o)); }
        if let Some(ref meth) = method { args.push(format!("-P {}", meth)); }
        if let Some(r) = rtr { args.push(format!("-r {}", r)); }
        if recordroute == Some(true) { args.push("-R".into()); }
        if let Some(s) = size { args.push(format!("-s {}", s)); }
        if let Some(s) = src { args.push(format!("-S {}", s)); }
        if let Some(u) = userid { args.push(format!("-U {}", u)); }
        if let Some(w) = wait_timeout {
            args.push(format!("-W {}s", w.as_secs_f64()));
        }
        if let Some(t) = tos { args.push(format!("-z {}", t)); }
        args.push(dst.to_string());

        self.do_cmd(inst, &args.join(" "))
    }

    // -----------------------------------------------------------------------
    // DNS / host
    // -----------------------------------------------------------------------

    #[allow(clippy::too_many_arguments)]
    pub fn do_dns(
        &mut self,
        inst: &ScamperInst,
        qname: &str,
        server: Option<&str>,
        qclass: Option<&str>,
        qtype: Option<&str>,
        attempts: Option<u8>,
        rd: Option<bool>,
        wait_timeout: Option<Duration>,
        tcp: Option<bool>,
        nsid: Option<bool>,
        ecs: Option<&str>,
        userid: Option<u32>,
    ) -> Result<ScamperTask, String> {
        let mut args = vec!["host".to_string()];

        if let Some(s) = server { args.push(format!("-s {}", s)); }
        if let Some(c) = qclass { args.push(format!("-c {}", c)); }
        if let Some(t) = qtype { args.push(format!("-t {}", t)); }
        if let Some(a) = attempts {
            if a < 1 { return Err("attempts < 1".into()); }
            args.push(format!("-R {}", a));
        }
        if let Some(w) = wait_timeout {
            args.push(format!("-W {}s", w.as_secs_f64()));
        }
        if let Some(u) = userid { args.push(format!("-U {}", u)); }
        if rd == Some(false) { args.push("-r".into()); }
        if tcp == Some(true) { args.push("-T".into()); }
        if nsid == Some(true) { args.push("-O nsid".into()); }
        if let Some(e) = ecs { args.push(format!("-O subnet={}", e)); }
        args.push(qname.to_string());

        self.do_cmd(inst, &args.join(" "))
    }

    // -----------------------------------------------------------------------
    // Alias resolution: Ally
    // -----------------------------------------------------------------------

    #[allow(clippy::too_many_arguments)]
    pub fn do_ally(
        &mut self,
        inst: &ScamperInst,
        dst1: &str,
        dst2: &str,
        fudge: Option<u16>,
        icmp_sum: Option<u16>,
        dport: Option<u16>,
        sport: Option<u16>,
        method: Option<&str>,
        attempts: Option<u8>,
        wait_probe: Option<Duration>,
        wait_timeout: Option<Duration>,
        userid: Option<u32>,
    ) -> Result<ScamperTask, String> {
        let mut args = vec!["dealias -m ally".to_string()];

        let m = method.map(|s| s.to_lowercase());

        if let Some(ref mm) = m {
            let mut pd = format!("-p '-P {}", mm);
            if let Some(s) = sport { pd.push_str(&format!(" -F {}", s)); }
            if let Some(d) = dport { pd.push_str(&format!(" -d {}", d)); }
            if let Some(cs) = icmp_sum { pd.push_str(&format!(" -c {}", cs)); }
            pd.push('\'');
            args.push(pd);
        }

        if let Some(f) = fudge {
            if f == 0 { args.push("-O inseq".into()); }
            else { args.push(format!("-f {}", f)); }
        }
        if let Some(a) = attempts { args.push(format!("-q {}", a)); }
        if let Some(u) = userid { args.push(format!("-U {}", u)); }
        if let Some(w) = wait_probe {
            args.push(format!("-W {}s", w.as_secs_f64()));
        }
        if let Some(w) = wait_timeout {
            args.push(format!("-w {}s", w.as_secs_f64()));
        }
        args.push(format!("{} {}", dst1, dst2));

        self.do_cmd(inst, &args.join(" "))
    }

    // -----------------------------------------------------------------------
    // Alias resolution: Mercator
    // -----------------------------------------------------------------------

    pub fn do_mercator(
        &mut self,
        inst: &ScamperInst,
        dst: &str,
        userid: Option<u32>,
    ) -> Result<ScamperTask, String> {
        let mut args = vec!["dealias -m mercator".to_string()];
        if let Some(u) = userid { args.push(format!("-U {}", u)); }
        args.push(dst.to_string());
        self.do_cmd(inst, &args.join(" "))
    }

    // -----------------------------------------------------------------------
    // Alias resolution: Prefixscan
    // -----------------------------------------------------------------------

    #[allow(clippy::too_many_arguments)]
    pub fn do_prefixscan(
        &mut self,
        inst: &ScamperInst,
        near: &str,
        far: &str,
        prefixlen: u8,
        fudge: Option<u16>,
        icmp_sum: Option<u16>,
        dport: Option<u16>,
        sport: Option<u16>,
        method: Option<&str>,
        attempts: Option<u8>,
        wait_probe: Option<Duration>,
        wait_timeout: Option<Duration>,
        userid: Option<u32>,
    ) -> Result<ScamperTask, String> {
        let mut args = vec!["dealias -m prefixscan".to_string()];

        let m = method.map(|s| s.to_lowercase()).unwrap_or_else(|| "udp".to_string());

        let mut pd = format!("-p '-P {}", m);
        if let Some(s) = sport { pd.push_str(&format!(" -F {}", s)); }
        if let Some(d) = dport { pd.push_str(&format!(" -d {}", d)); }
        if let Some(cs) = icmp_sum { pd.push_str(&format!(" -c {}", cs)); }
        pd.push('\'');
        args.push(pd);

        if let Some(f) = fudge {
            if f == 0 { args.push("-O inseq".into()); }
            else { args.push(format!("-f {}", f)); }
        }
        if let Some(a) = attempts { args.push(format!("-q {}", a)); }
        if let Some(u) = userid { args.push(format!("-U {}", u)); }
        if let Some(w) = wait_probe {
            args.push(format!("-W {}s", w.as_secs_f64()));
        }
        if let Some(w) = wait_timeout {
            args.push(format!("-w {}s", w.as_secs_f64()));
        }
        args.push(format!("{} {}/{}", near, far, prefixlen));

        self.do_cmd(inst, &args.join(" "))
    }

    // -----------------------------------------------------------------------
    // Radargun
    // -----------------------------------------------------------------------

    #[allow(clippy::too_many_arguments)]
    pub fn do_radargun(
        &mut self,
        inst: &ScamperInst,
        probedefs: &[&str],
        addrs: Option<&[&str]>,
        rounds: Option<u32>,
        wait_probe: Option<Duration>,
        wait_round: Option<Duration>,
        wait_timeout: Option<Duration>,
        userid: Option<u32>,
    ) -> Result<ScamperTask, String> {
        let mut args = vec!["dealias -m radargun".to_string()];

        if let Some(r) = rounds { args.push(format!("-q {}", r)); }
        if let Some(u) = userid { args.push(format!("-U {}", u)); }
        if let Some(w) = wait_probe {
            args.push(format!("-W {}s", w.as_secs_f64()));
        }
        if let Some(w) = wait_round {
            args.push(format!("-r {}s", w.as_secs_f64()));
        }
        if let Some(w) = wait_timeout {
            args.push(format!("-w {}s", w.as_secs_f64()));
        }
        for pd in probedefs { args.push(format!("-p '{}'", pd)); }
        if let Some(addrs) = addrs {
            for a in addrs { args.push(a.to_string()); }
        }

        self.do_cmd(inst, &args.join(" "))
    }

    // -----------------------------------------------------------------------
    // Alias resolution: Midarest
    // -----------------------------------------------------------------------

    #[allow(clippy::too_many_arguments)]
    pub fn do_midarest(
        &mut self,
        inst: &ScamperInst,
        probedefs: &[&str],
        addrs: &[&str],
        rounds: Option<u32>,
        wait_probe: Option<Duration>,
        wait_round: Option<Duration>,
        wait_timeout: Option<Duration>,
        userid: Option<u32>,
    ) -> Result<ScamperTask, String> {
        if probedefs.is_empty() { return Err("missing probedefs".into()); }
        if addrs.is_empty() { return Err("missing addrs".into()); }

        let mut args = vec!["dealias -m midarest".to_string()];

        if let Some(r) = rounds { args.push(format!("-q {}", r)); }
        if let Some(u) = userid { args.push(format!("-U {}", u)); }
        if let Some(w) = wait_probe {
            let ms = w.as_millis();
            if ms == 0 { return Err("wait_probe must be at least 1ms".into()); }
            args.push(format!("-W {}", ms));
        }
        if let Some(w) = wait_timeout {
            let s = w.as_secs();
            if s == 0 { return Err("wait_timeout must be at least 1s".into()); }
            args.push(format!("-w {}", s));
        }
        if let Some(w) = wait_round {
            let ms = w.as_millis();
            if ms == 0 { return Err("wait_round must be at least 1ms".into()); }
            args.push(format!("-r {}", ms));
        }
        for pd in probedefs { args.push(format!("-p '{}'", pd)); }
        for addr in addrs { args.push(addr.to_string()); }

        self.do_cmd(inst, &args.join(" "))
    }

    // -----------------------------------------------------------------------
    // Alias resolution: Midardisc
    // -----------------------------------------------------------------------

    #[allow(clippy::too_many_arguments)]
    pub fn do_midardisc(
        &mut self,
        inst: &ScamperInst,
        probedefs: &[&str],
        schedule: &[&str],
        startat: Option<f64>,
        wait_timeout: Option<Duration>,
        userid: Option<u32>,
    ) -> Result<ScamperTask, String> {
        if probedefs.is_empty() { return Err("missing probedefs".into()); }
        if schedule.is_empty() { return Err("missing schedule".into()); }

        let mut args = vec!["dealias -m midardisc".to_string()];

        if let Some(u) = userid { args.push(format!("-U {}", u)); }
        if let Some(w) = wait_timeout {
            let s = w.as_secs();
            if s == 0 { return Err("wait_timeout must be at least 1s".into()); }
            args.push(format!("-w {}", s));
        }
        if let Some(t) = startat { args.push(format!("-@ {}", t)); }
        for pd in probedefs { args.push(format!("-p '{}'", pd)); }
        for s in schedule { args.push(format!("-S {}", s)); }

        self.do_cmd(inst, &args.join(" "))
    }

    // -----------------------------------------------------------------------
    // Sniff
    // -----------------------------------------------------------------------

    pub fn do_sniff(
        &mut self,
        inst: &ScamperInst,
        src: &str,
        icmp_id: u16,
        limit_pkt_count: Option<u32>,
        limit_time: Option<Duration>,
        userid: Option<u32>,
    ) -> Result<ScamperTask, String> {
        let mut args = vec![format!("sniff -S {}", src)];

        if let Some(c) = limit_pkt_count { args.push(format!("-c {}", c)); }
        if let Some(t) = limit_time {
            args.push(format!("-G {}s", t.as_secs_f64()));
        }
        if let Some(u) = userid { args.push(format!("-U {}", u)); }
        args.push(format!("icmp[icmpid] == {}", icmp_id));

        self.do_cmd(inst, &args.join(" "))
    }

    // -----------------------------------------------------------------------
    // HTTP
    // -----------------------------------------------------------------------

    pub fn do_http(
        &mut self,
        inst: &ScamperInst,
        dst: &str,
        url: &str,
        headers: Option<&[(&str, &str)]>,
        insecure: bool,
        limit_time: Option<Duration>,
        userid: Option<u32>,
    ) -> Result<ScamperTask, String> {
        let mut args = vec!["http".to_string()];

        if insecure { args.push("-O insecure".into()); }
        if let Some(t) = limit_time {
            args.push(format!("-m {}s", t.as_secs_f64()));
        }
        if let Some(hdrs) = headers {
            for (name, val) in hdrs {
                args.push(format!("-H '{}: {}'", name, val));
            }
        }
        if let Some(u) = userid { args.push(format!("-U {}", u)); }
        let esc_url = url.replace('\'', "\\'");
        args.push(format!("-u '{}' {}", esc_url, dst));

        self.do_cmd(inst, &args.join(" "))
    }

    // -----------------------------------------------------------------------
    // UDP probe
    // -----------------------------------------------------------------------

    pub fn do_udpprobe(
        &mut self,
        inst: &ScamperInst,
        dst: &str,
        dport: u16,
        payload: &[u8],
        attempts: Option<u16>,
        src: Option<&str>,
        stop_count: Option<u16>,
        userid: Option<u32>,
    ) -> Result<ScamperTask, String> {
        if dport == 0 { return Err("invalid destination port".into()); }
        let mut args = vec!["udpprobe".to_string()];

        args.push(format!("-d {}", dport));
        args.push(format!("-p {}", hex::encode(payload)));
        if let Some(a) = attempts { args.push(format!("-c {}", a)); }
        if let Some(o) = stop_count { args.push(format!("-o {}", o)); }
        if let Some(s) = src { args.push(format!("-S {}", s)); }
        if let Some(u) = userid { args.push(format!("-U {}", u)); }
        args.push(dst.to_string());

        self.do_cmd(inst, &args.join(" "))
    }

    // -----------------------------------------------------------------------
    // TBIT
    // -----------------------------------------------------------------------

    pub fn do_tbit(
        &mut self,
        inst: &ScamperInst,
        dst: &str,
        method: &str,
        url: &str,
        userid: Option<u32>,
    ) -> Result<ScamperTask, String> {
        let mut args = vec!["tbit".to_string()];
        if let Some(u) = userid { args.push(format!("-U {}", u)); }
        let esc_url = url.replace('\'', "\\'");
        args.push(format!("-u '{}' -t {} {}", esc_url, method, dst));
        self.do_cmd(inst, &args.join(" "))
    }

    // -----------------------------------------------------------------------
    // OWAMP
    // -----------------------------------------------------------------------

    #[allow(clippy::too_many_arguments)]
    pub fn do_owamp(
        &mut self,
        inst: &ScamperInst,
        dst: &str,
        direction: &str,
        attempts: Option<u32>,
        dscp: Option<u8>,
        schedule: Option<&str>,
        size: Option<u16>,
        startat: Option<f64>,
        ttl: Option<u8>,
        wait_timeout: Option<Duration>,
        userid: Option<u32>,
    ) -> Result<ScamperTask, String> {
        if direction != "tx" && direction != "rx" {
            return Err("direction must be tx or rx".into());
        }
        let mut args = vec!["owamp".to_string()];

        if let Some(t) = startat { args.push(format!("-@ {}", t)); }
        if let Some(w) = wait_timeout {
            args.push(format!("-w {}s", w.as_secs_f64()));
        }
        if let Some(s) = schedule { args.push(format!("-i {}", s)); }
        if let Some(c) = attempts { args.push(format!("-c {}", c)); }
        if let Some(s) = size { args.push(format!("-s {}", s)); }
        if let Some(m) = ttl { args.push(format!("-m {}", m)); }
        if let Some(d) = dscp { args.push(format!("-D {}", d)); }
        if let Some(u) = userid { args.push(format!("-U {}", u)); }
        args.push(format!("-d {} {}", direction, dst));

        self.do_cmd(inst, &args.join(" "))
    }

    // -----------------------------------------------------------------------
    // Event loop
    // -----------------------------------------------------------------------

    /// Wait up to `timeout` for the next event, with an optional timeval.
    fn wait(&mut self, timeout: Option<Duration>) {
        match timeout {
            None => {
                unsafe { libscamperctrl::scamper_ctrl_wait(self.c, ptr::null_mut()) };
            }
            Some(d) => {
                let mut tv = libc::timeval {
                    tv_sec: d.as_secs() as libc::time_t,
                    tv_usec: d.subsec_micros() as libc::suseconds_t,
                };
                unsafe { libscamperctrl::scamper_ctrl_wait(self.c, &mut tv) };
            }
        }
    }

    /// Return an iterator that drives the event loop and yields measurement
    /// results one at a time as they complete.
    ///
    /// The iterator blocks per item — each call to `.next()` waits until the
    /// next result arrives — and ends automatically when all outstanding tasks
    /// have finished (every instance has called [`ScamperInst::done`] and
    /// every submitted measurement has produced a result), or when the
    /// optional `timeout` deadline elapses.
    ///
    /// `timeout` is a safety net for the **entire** batch, not a per-result
    /// timeout. Per-measurement timeouts are configured via the `wait_timeout`
    /// parameter of the `do_*` scheduling methods.
    ///
    /// Meta objects (`List`, `CycleStart`, `CycleDef`, `CycleStop`) are
    /// yielded only if the controller was created with `meta = true`.
    ///
    /// # Comparison with `poll`
    ///
    /// Both `responses()` and [`poll`](Self::poll) block until one result is
    /// ready. Use `responses()` when you want iterator semantics or need a
    /// timeout on the whole batch; use `poll()` when you prefer an explicit
    /// `while let` loop with no timeout.
    ///
    /// | | `responses()` | `poll()` |
    /// |---|---|---|
    /// | API style | Iterator — `for` loop | Explicit — `while let` loop |
    /// | Timeout for whole batch | Yes — `Some(duration)` | No |
    /// | Pull exactly one result | `.next()` | call once |
    ///
    /// # Example
    ///
    /// ```no_run
    /// use std::time::Duration;
    /// use rscamper::ScamperObject;
    ///
    /// inst.done();
    ///
    /// // Collect all results
    /// for item in ctrl.responses(None) {
    ///     if let ScamperObject::Ping(p) = &item.obj { /* … */ }
    /// }
    ///
    /// // Collect all results with a safety timeout
    /// for item in ctrl.responses(Some(Duration::from_secs(60))) { /* … */ }
    ///
    /// // Pull exactly one result
    /// let r = ctrl.responses(None).next().expect("no result");
    /// ```
    pub fn responses(&mut self, timeout: Option<Duration>) -> Responses<'_> {
        let deadline = timeout.map(|t| {
            std::time::Instant::now() + t
        });
        Responses { ctrl: self, deadline }
    }

    /// Wait for the next measurement result and return it.
    ///
    /// Blocks until one result is available from the scamper daemon, then
    /// returns it immediately. Returns `None` when all outstanding tasks have
    /// completed and there is nothing left to wait for.
    ///
    /// Each call corresponds to one completed measurement. Use it when 
    /// you want to process results one at a time as they arrive:
    ///
    /// ```no_run
    /// while let Some(item) = ctrl.poll() {
    ///     println!("result: {:?}", item.obj);
    /// }
    /// ```
    ///
    /// For iterator-style access or timeout support, use
    /// [`responses`](Self::responses) instead.
    pub fn poll(&mut self) -> Option<ResponseItem> {
        loop {
            let data_ptr = self.data;
            let task_count;
            {
                let ctrl_data = unsafe { &mut *data_ptr };
                while let Some(item) = ctrl_data.objs.pop_front() {
                    let inst_data = unsafe { &mut *item.inst_data };
                    if inst_data.queued > 0 { inst_data.queued -= 1; }
                    let is_meta = is_meta_obj(&item.obj);
                    if !is_meta || ctrl_data.meta {
                        return Some(ResponseItem { obj: item.obj, inst_name: item.inst_name });
                    }
                }
                task_count = ctrl_data.task_count;
            }
            if task_count == 0 { return None; }
            self.wait(None);
        }
    }
}

/// Helper: is this a meta object (List or Cycle)?
fn is_meta_obj(obj: &ScamperObject) -> bool {
    matches!(obj,
        ScamperObject::List(_) |
        ScamperObject::CycleStart(_) |
        ScamperObject::CycleDef(_) |
        ScamperObject::CycleStop(_))
}

/// Iterator returned by `ScamperCtrl::responses()`.
pub struct Responses<'a> {
    ctrl: &'a mut ScamperCtrl,
    deadline: Option<std::time::Instant>,
}

impl<'a> Iterator for Responses<'a> {
    type Item = ResponseItem;

    fn next(&mut self) -> Option<ResponseItem> {
        loop {
            // Drain the queue first. Copy the raw pointer so the borrow
            // of self.ctrl ends before we call self.ctrl.wait() below.
            let data_ptr = self.ctrl.data;
            let task_count;
            {
                let ctrl_data = unsafe { &mut *data_ptr };
                while let Some(item) = ctrl_data.objs.pop_front() {
                    let inst_data = unsafe { &mut *item.inst_data };
                    if inst_data.queued > 0 { inst_data.queued -= 1; }
                    let is_meta = is_meta_obj(&item.obj);
                    if !is_meta || ctrl_data.meta {
                        return Some(ResponseItem { obj: item.obj, inst_name: item.inst_name });
                    }
                }
                task_count = ctrl_data.task_count;
            }

            // Stop if no tasks remain.
            if task_count == 0 { return None; }

            // Check timeout deadline.
            let remaining = match self.deadline {
                None => None,
                Some(dl) => {
                    let now = std::time::Instant::now();
                    if now >= dl { return None; }
                    Some(dl - now)
                }
            };

            // Block until something happens.
            self.ctrl.wait(remaining);
        }
    }
}

impl Drop for ScamperCtrl {
    fn drop(&mut self) {
        // Drop CtrlData (and the optional outfile inside it)
        if !self.data.is_null() {
            unsafe { drop(Box::from_raw(self.data)) };
            self.data = ptr::null_mut();
        }
        // insts and muxes are dropped by their Vec
        self.insts.clear();
        self.muxes.clear();
        if !self.c.is_null() {
            unsafe { libscamperctrl::scamper_ctrl_free(self.c) };
        }
    }
}

unsafe impl Send for ScamperCtrl {}
unsafe impl Sync for ScamperCtrl {}

// ---------------------------------------------------------------------------
// Hex encoding helper (avoids adding a dependency on the hex crate)
// ---------------------------------------------------------------------------
mod hex {
    pub fn encode(data: &[u8]) -> String {
        data.iter().map(|b| format!("{:02x}", b)).collect()
    }
}