zenith-ebpf 0.1.0

Zenith eBPF 程序管理:预编译字节码嵌入(include_bytes!)、libbpf-rs 高性能加载、bpf_link 原子挂载、双 Bank 热更新
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
//! 统一 eBPF attach 框架:XDP / TC / cgroup / socket filter
//!
//! # 设计原则(极端极限极致严格标准)
//!
//! eBPF 不局限于 XDP,内核支持多种 attach 点,每种处理阶段不同、性能与适用场景各异。
//! 本模块提供统一的 attach 抽象,按需选择最优 attach 点:
//!
//! | Attach 点       | 处理阶段              | 性能   | 典型用途                  |
//! |-----------------|----------------------|--------|--------------------------|
//! | XDP             | 网卡驱动层(最早)    | 最快   | 包过滤 / AF_XDP 重定向    |
//! | TC (clsact)     | 流量控制 qdisc        | 次快   | 包分类 / 限速 / 镜像      |
//! | cgroup/sock_ops | socket 操作回调       | 中等   | socket 监控 / 调优        |
//! | socket filter   | 单个 socket 入口      | 最低   | socket 级过滤             |
//!
//! # 使用方式
//!
//! 通过 [`AttachPoint`] 枚举声明 attach 目标,调用 [`attach_program`] 统一入口,
//! 返回 [`AttachedHandle`] 用于后续 detach。每种 attach 点独立实现,互不干扰。
//!
//! # unsafe 使用
//!
//! 本模块封装 `bpf_tc_*` / `bpf_prog_attach` / `setsockopt` / `open` 等 C 系统调用。
//! 是 crate 内被精确放开 `#[allow(unsafe_code)]` 的模块之一,每个 unsafe 块
//! 均附带详细 SAFETY 论证。

#![allow(unsafe_code)]
#![deny(missing_debug_implementations)]
#![warn(missing_docs)]

use crate::error::AttachError;
use crate::xdp_attach::{XdpAttachMode, attach_xdp_raw, detach_xdp_raw};
// TC 相关类型在 libbpf-rs 顶层导出(tc 模块本身是私有的)
use libbpf_rs::{Link, Object, ProgramType, TC_EGRESS, TC_INGRESS, TcAttachPoint, TcHook};
use std::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, OwnedFd};
use std::path::PathBuf;

/// TC attach 方向
///
/// 对应内核 clsact qdisc 的 ingress / egress hook
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TcDirection {
    /// 入向(包进入网卡,尚未上交协议栈)
    Ingress,
    /// 出向(包从协议栈下发到网卡前)
    Egress,
}

impl TcDirection {
    /// 转为 libbpf-rs 的 TcAttachPoint
    #[inline]
    fn to_attach_point(self) -> TcAttachPoint {
        match self {
            TcDirection::Ingress => TC_INGRESS,
            TcDirection::Egress => TC_EGRESS,
        }
    }

    /// 获取方向名称(用于日志)
    pub fn as_str(self) -> &'static str {
        match self {
            TcDirection::Ingress => "ingress",
            TcDirection::Egress => "egress",
        }
    }
}

/// cgroup attach 类型
///
/// 对应内核 `bpf_attach_type` 中 cgroup 相关的子集。
/// 仅枚举 zenith 实际使用的类型,其余可按需扩展。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CgroupAttachType {
    /// `BPF_CGROUP_SOCK_OPS`:socket 操作回调(RTT/拥塞控制等)
    SockOps,
    /// `BPF_CGROUP_INET_INGRESS`:cgroup 入向 IP 包
    InetIngress,
    /// `BPF_CGROUP_INET_EGRESS`:cgroup 出向 IP 包
    InetEgress,
    /// `BPF_CGROUP_INET_SOCK_CREATE`:socket 创建事件
    SockCreate,
}

impl CgroupAttachType {
    /// 获取该 attach 类型期望的 BPF 程序类型(用于 prog_type 校验)
    ///
    /// 内核根据程序类型决定 attach 路径,传入错误类型的程序会导致 EINVAL。
    /// 本函数返回该 attach_type 对应的正确 ProgramType,用于前置校验。
    #[inline]
    fn expected_prog_type(self) -> ProgramType {
        match self {
            // BPF_CGROUP_SOCK_OPS 对应 BPF_PROG_TYPE_SOCK_OPS
            CgroupAttachType::SockOps => ProgramType::SockOps,
            // BPF_CGROUP_INET_INGRESS/EGRESS/SOCK_CREATE 对应 BPF_PROG_TYPE_CGROUP_SKB
            CgroupAttachType::InetIngress
            | CgroupAttachType::InetEgress
            | CgroupAttachType::SockCreate => ProgramType::CgroupSkb,
        }
    }

    /// 获取类型名称(用于日志)
    pub fn as_str(self) -> &'static str {
        match self {
            CgroupAttachType::SockOps => "sock_ops",
            CgroupAttachType::InetIngress => "inet_ingress",
            CgroupAttachType::InetEgress => "inet_egress",
            CgroupAttachType::SockCreate => "sock_create",
        }
    }
}

/// 统一的 eBPF attach 点
///
/// 用枚举封装所有支持的 attach 类型,配合 [`attach_program`] 使用。
/// 每种 attach 点对应不同的内核 hook,处理阶段与性能特性各异。
#[derive(Debug, Clone)]
pub enum AttachPoint {
    /// XDP attach(网卡驱动层,最早处理点)
    ///
    /// 支持 HW / DRV / SKB 三种子模式,`Auto` 自动逐级回退
    Xdp {
        /// 网卡接口索引
        ifindex: i32,
        /// attach 模式(Auto = HW → DRV → SKB 自动回退)
        mode: XdpAttachMode,
    },

    /// TC attach(Traffic Control clsact qdisc)
    ///
    /// 在协议栈与网卡驱动之间处理,支持 ingress / egress 两个方向
    Tc {
        /// 网卡接口索引
        ifindex: i32,
        /// attach 方向(ingress / egress)
        direction: TcDirection,
        /// 是否替换已存在的 hook
        replace: bool,
    },

    /// cgroup attach(cgroup 级别的 socket / 网络事件)
    ///
    /// 通过 cgroup v2 路径 attach,影响该 cgroup 下所有进程
    Cgroup {
        /// cgroup v2 路径(如 `/sys/fs/cgroup/zenith/`)
        cgroup_path: PathBuf,
        /// attach 类型
        attach_type: CgroupAttachType,
    },

    /// Socket filter attach(绑定到具体 socket)
    ///
    /// 仅过滤该 socket 收到的包,最低开销也最低侵入性
    SocketFilter {
        /// 目标 socket 文件描述符
        socket_fd: i32,
    },
}

impl AttachPoint {
    /// 获取 attach 点名称(用于日志)
    pub fn kind(&self) -> &'static str {
        match self {
            AttachPoint::Xdp { .. } => "xdp",
            AttachPoint::Tc { .. } => "tc",
            AttachPoint::Cgroup { .. } => "cgroup",
            AttachPoint::SocketFilter { .. } => "socket_filter",
        }
    }

    /// **便捷构造:XDP 自动最优模式(HW → DRV → SKB 逐级回退)**
    #[inline]
    pub fn xdp_auto(ifindex: i32) -> Self {
        AttachPoint::Xdp {
            ifindex,
            mode: XdpAttachMode::Auto,
        }
    }

    /// **便捷构造:XDP 指定模式**
    #[inline]
    pub fn xdp_with_mode(ifindex: i32, mode: XdpAttachMode) -> Self {
        AttachPoint::Xdp { ifindex, mode }
    }

    /// **便捷构造:TC ingress(入向)**
    #[inline]
    pub fn tc_ingress(ifindex: i32) -> Self {
        AttachPoint::Tc {
            ifindex,
            direction: TcDirection::Ingress,
            replace: false,
        }
    }

    /// **便捷构造:TC egress(出向)**
    #[inline]
    pub fn tc_egress(ifindex: i32) -> Self {
        AttachPoint::Tc {
            ifindex,
            direction: TcDirection::Egress,
            replace: false,
        }
    }

    /// **便捷构造:cgroup sock_ops(socket 监控)**
    #[inline]
    pub fn cgroup_sock_ops<P: Into<PathBuf>>(cgroup_path: P) -> Self {
        AttachPoint::Cgroup {
            cgroup_path: cgroup_path.into(),
            attach_type: CgroupAttachType::SockOps,
        }
    }

    /// **便捷构造:Socket filter**
    #[inline]
    pub fn socket_filter(socket_fd: i32) -> Self {
        AttachPoint::SocketFilter { socket_fd }
    }
}

/// 已 attach 的句柄
///
/// 持有 detach 所需的全部信息。Drop 时会自动 detach,避免资源泄漏。
/// 通过内部 `Option` 包装实现"detach 一次即置空",避免重复 detach。
#[derive(Debug)]
pub struct AttachedHandle {
    /// 内部状态:None 表示已 detach(或正在 detach)
    inner: Option<AttachedHandleInner>,
}

/// 实际的 attach 句柄变体(内部)
#[derive(Debug)]
enum AttachedHandleInner {
    /// XDP attach 句柄(用 bpf_xdp_attach 挂载)
    Xdp {
        /// 已 attach 的 ifindex
        ifindex: i32,
        /// 实际使用的模式
        mode: XdpAttachMode,
    },

    /// TC attach 句柄
    Tc {
        /// 方向
        direction: TcDirection,
        /// 原始 hook 结构(用于 detach)
        hook: TcHook,
    },

    /// cgroup attach 句柄(基于 bpf_link,detach 时销毁 link)
    Cgroup {
        /// bpf_link(持有即保持 attach,Drop 自动 detach)
        link: Link,
        /// 已打开的 cgroup fd(通过 OwnedFd::Drop 自动关闭,字段本身不显式读取)
        #[allow(dead_code)]
        cgroup_fd: OwnedFd,
    },

    /// Socket filter 句柄(detach 时 setsockopt(SO_DETACH_BPF))
    SocketFilter {
        /// 目标 socket fd
        socket_fd: i32,
    },
}

impl AttachedHandle {
    /// 获取 attach 点名称
    pub fn kind(&self) -> &'static str {
        match &self.inner {
            Some(AttachedHandleInner::Xdp { .. }) => "xdp",
            Some(AttachedHandleInner::Tc { .. }) => "tc",
            Some(AttachedHandleInner::Cgroup { .. }) => "cgroup",
            Some(AttachedHandleInner::SocketFilter { .. }) => "socket_filter",
            None => "detached",
        }
    }

    /// 是否已 detach
    pub fn is_detached(&self) -> bool {
        self.inner.is_none()
    }

    /// 显式 detach(消费内部状态,返回 detach 结果)
    ///
    /// 调用后 `self` 进入 detached 状态,后续 Drop 不会重复 detach。
    pub fn detach(&mut self) -> Result<(), AttachError> {
        if let Some(mut inner) = self.inner.take() {
            detach_handle_inner(&mut inner)
        } else {
            Ok(())
        }
    }
}

/// 自动清理:Drop 时 detach 所有 attach 资源(已 detach 则跳过)
impl Drop for AttachedHandle {
    fn drop(&mut self) {
        if let Some(mut inner) = self.inner.take() {
            let _ = detach_handle_inner(&mut inner);
        }
    }
}

/// **统一 attach 入口:用指定 attach 点挂载程序**
///
/// 根据 `point` 类型分派到具体实现:
/// - `Xdp`:调用 `bpf_xdp_attach`(支持 HW/DRV/SKB 自动回退)
/// - `Tc`:调用 `bpf_tc_hook_create` + `bpf_tc_attach`(clsact qdisc)
/// - `Cgroup`:调用 `bpf_program__attach_cgroup`(基于 bpf_link)
/// - `SocketFilter`:调用 `setsockopt(SO_ATTACH_BPF)`
///
/// # 参数
/// * `obj` - 已加载的 libbpf-rs Object
/// * `prog_name` - BPF 程序名称(C 函数名)
/// * `point` - attach 目标
///
/// # 返回
/// 成功时返回 [`AttachedHandle`],用于后续 detach(或直接 Drop 自动清理)
pub fn attach_program(
    obj: &mut Object,
    prog_name: &str,
    point: &AttachPoint,
) -> Result<AttachedHandle, AttachError> {
    match point {
        AttachPoint::Xdp { ifindex, mode } => {
            attach_xdp(obj, prog_name, *ifindex, *mode)
        }
        AttachPoint::Tc {
            ifindex,
            direction,
            replace,
        } => attach_tc(obj, prog_name, *ifindex, *direction, *replace),
        AttachPoint::Cgroup {
            cgroup_path,
            attach_type,
        } => attach_cgroup(obj, prog_name, cgroup_path, *attach_type),
        AttachPoint::SocketFilter { socket_fd } => {
            attach_socket_filter(obj, prog_name, *socket_fd)
        }
    }
}

/// **统一 detach 入口:显式释放 attach 句柄**
///
/// 通常不需要手动调用——`AttachedHandle` 的 Drop 会自动 detach。
/// 本函数用于需要显式错误处理的场景:传入 `handle` 调用其 `detach` 方法,
/// 返回 detach 结果。
pub fn detach_program(handle: &mut AttachedHandle) -> Result<(), AttachError> {
    handle.detach()
}

// ─────────────────────────────────────────────────────────────────────────────
// XDP attach 实现(复用 xdp_attach 模块)
// ─────────────────────────────────────────────────────────────────────────────

fn attach_xdp(
    obj: &mut Object,
    prog_name: &str,
    ifindex: i32,
    mode: XdpAttachMode,
) -> Result<AttachedHandle, AttachError> {
    // 查找程序并校验类型(安全前置:防止传入非 XDP 程序)
    let prog = find_program_by_name_mut(obj, prog_name)?;
    validate_prog_type(&prog, ProgramType::Xdp, "xdp")?;

    // 直接通过 as_fd() 获取 fd(bpf_xdp_attach 内核会 dup fd,零开销,无需 pin)
    let prog_fd: i32 = prog.as_fd().as_raw_fd();

    let actual_mode = attach_xdp_raw(ifindex, prog_fd, mode)?;

    Ok(AttachedHandle {
        inner: Some(AttachedHandleInner::Xdp {
            ifindex,
            mode: actual_mode,
        }),
    })
}

// ─────────────────────────────────────────────────────────────────────────────
// TC attach 实现(基于 libbpf-rs TcHook)
// ─────────────────────────────────────────────────────────────────────────────

fn attach_tc(
    obj: &mut Object,
    prog_name: &str,
    ifindex: i32,
    direction: TcDirection,
    replace: bool,
) -> Result<AttachedHandle, AttachError> {
    // 查找程序并校验类型(安全前置:TC 要求 SchedCls,即 SEC("tc"/"classifier"))
    let prog = find_program_by_name_mut(obj, prog_name)?;
    validate_prog_type(&prog, ProgramType::SchedCls, "tc")?;

    // 直接通过 as_fd() 获取 fd(TC attach 内核会 dup fd,零开销)
    let prog_fd_borrowed: BorrowedFd<'_> = prog.as_fd();

    // 构造 TC hook(clsact qdisc)
    let mut hook = TcHook::new(prog_fd_borrowed);
    hook.ifindex(ifindex);
    hook.attach_point(direction.to_attach_point());
    if replace {
        hook.replace(true);
    }

    // 创建 clsact qdisc(幂等:已存在则视为成功)
    hook.create()
        .map_err(|e| AttachError::Libbpf(format!("TC create clsact qdisc 失败: {}", e)))?;

    // attach 程序到 hook(内核会 dup prog_fd,attach 后不依赖本地 fd)
    hook.attach()
        .map_err(|e| AttachError::Libbpf(format!("TC attach 失败 ({}): {}", direction.as_str(), e)))?;

    Ok(AttachedHandle {
        inner: Some(AttachedHandleInner::Tc { direction, hook }),
    })
}

// ─────────────────────────────────────────────────────────────────────────────
// cgroup attach 实现(基于 bpf_link)
// ─────────────────────────────────────────────────────────────────────────────

fn attach_cgroup(
    obj: &mut Object,
    prog_name: &str,
    cgroup_path: &std::path::Path,
    attach_type: CgroupAttachType,
) -> Result<AttachedHandle, AttachError> {
    // 校验 cgroup 路径存在
    if !cgroup_path.exists() {
        return Err(AttachError::InterfaceNotFound(format!(
            "cgroup 路径不存在: {}",
            cgroup_path.display()
        )));
    }

    // 查找程序并校验类型(安全前置:attach_type 必须与 prog_type 匹配)
    let prog = find_program_by_name_mut(obj, prog_name)?;
    validate_prog_type(&prog, attach_type.expected_prog_type(), "cgroup")?;

    // 打开 cgroup 目录获取 fd(O_RDONLY | O_DIRECTORY)
    let cgroup_path_cstr = std::ffi::CString::new(cgroup_path.as_os_str().to_str().ok_or_else(|| {
        AttachError::InvalidFlags(format!(
            "cgroup 路径包含非 UTF-8 字符: {}",
            cgroup_path.display()
        ))
    })?)
    .map_err(|e| AttachError::InvalidFlags(format!("CString 转换失败: {}", e)))?;

    // SAFETY: open() 是 POSIX 系统调用。
    // - pathname: 来自 CString,NUL 结尾,指针在调用期间有效
    // - flags: O_RDONLY | O_DIRECTORY 为标准常量,对目录打开安全
    // 返回值 < 0 表示失败,会立即返回错误。
    let cgroup_fd_raw = unsafe {
        libc::open(
            cgroup_path_cstr.as_ptr(),
            libc::O_RDONLY | libc::O_DIRECTORY,
        )
    };
    if cgroup_fd_raw < 0 {
        let err = std::io::Error::last_os_error();
        return Err(AttachError::Libbpf(format!(
            "打开 cgroup 路径失败 ({}): {} (errno={})",
            cgroup_path.display(),
            err,
            err.raw_os_error().unwrap_or(0)
        )));
    }

    // SAFETY: cgroup_fd_raw 来自成功的 open() 调用,为有效 fd。
    // from_raw_fd 接管所有权,会在 Drop 时关闭 fd。
    let cgroup_fd = unsafe { OwnedFd::from_raw_fd(cgroup_fd_raw) };

    // 使用 bpf_program__attach_cgroup 创建 bpf_link(比 bpf_prog_attach 更现代化,支持原子替换)
    // 内核根据 prog_type 自动决定 attach_type,与上方校验的 expected_prog_type 一致
    let link = prog
        .attach_cgroup(cgroup_fd.as_raw_fd())
        .map_err(|e| {
            AttachError::Libbpf(format!(
                "cgroup attach 失败 (type={}): {}",
                attach_type.as_str(),
                e
            ))
        })?;

    Ok(AttachedHandle {
        inner: Some(AttachedHandleInner::Cgroup { link, cgroup_fd }),
    })
}

// ─────────────────────────────────────────────────────────────────────────────
// Socket filter attach 实现(SO_ATTACH_BPF)
// ─────────────────────────────────────────────────────────────────────────────

fn attach_socket_filter(
    obj: &mut Object,
    prog_name: &str,
    socket_fd: i32,
) -> Result<AttachedHandle, AttachError> {
    if socket_fd < 0 {
        return Err(AttachError::InvalidFlags(format!(
            "无效的 socket fd: {}",
            socket_fd
        )));
    }

    // 查找程序并校验类型(安全前置:socket filter 要求 ProgramType::SocketFilter)
    let prog = find_program_by_name_mut(obj, prog_name)?;
    validate_prog_type(&prog, ProgramType::SocketFilter, "socket_filter")?;

    // 直接通过 as_fd() 获取 fd(setsockopt 内核会 dup fd,零开销)
    let prog_fd: i32 = prog.as_fd().as_raw_fd();

    // setsockopt(SO_ATTACH_BPF) 将 BPF 程序绑定到 socket
    // SAFETY: setsockopt 是 POSIX 系统调用。
    // - sockfd: 由调用方提供,已校验 >= 0
    // - level: SOL_SOCKET 为标准常量
    // - optname: SO_ATTACH_BPF 为标准常量
    // - optval: &prog_fd 为有效指针,指向 i32
    // - optlen: sizeof(i32) = 4
    let ret = unsafe {
        libc::setsockopt(
            socket_fd,
            libc::SOL_SOCKET,
            libc::SO_ATTACH_BPF,
            &prog_fd as *const i32 as *const libc::c_void,
            std::mem::size_of::<i32>() as libc::socklen_t,
        )
    };
    if ret != 0 {
        let err = std::io::Error::last_os_error();
        return Err(AttachError::Libbpf(format!(
            "SO_ATTACH_BPF 失败: {} (errno={})",
            err,
            err.raw_os_error().unwrap_or(0)
        )));
    }

    Ok(AttachedHandle {
        inner: Some(AttachedHandleInner::SocketFilter { socket_fd }),
    })
}

// ─────────────────────────────────────────────────────────────────────────────
// 内部辅助函数
// ─────────────────────────────────────────────────────────────────────────────

/// 按名称查找 ProgramMut
fn find_program_by_name_mut<'a>(
    obj: &'a mut Object,
    prog_name: &str,
) -> Result<libbpf_rs::ProgramMut<'a>, AttachError> {
    obj.progs_mut()
        .find(|p| p.name().to_str().unwrap_or("") == prog_name)
        .ok_or_else(|| AttachError::Libbpf(format!("程序 {} 未找到", prog_name)))
}

/// **校验程序类型与期望类型匹配(安全前置检查)**
///
/// 防止用户传入错误类型的 BPF 程序导致内核 EINVAL 或未定义行为。
/// 例如:XDP attach 点要求 `ProgramType::Xdp`,TC 要求 `ProgramType::SchedCls`。
///
/// 注:libbpf-rs 的 `ProgramType` 未实现 `PartialEq`,因此用 `as u32` 比较。
#[inline]
fn validate_prog_type(
    prog: &libbpf_rs::ProgramMut<'_>,
    expected: ProgramType,
    attach_kind: &str,
) -> Result<(), AttachError> {
    let actual = prog.prog_type();
    if actual as u32 != expected as u32 {
        return Err(AttachError::InvalidFlags(format!(
            "程序类型不匹配(attach={}):期望 {:?},实际 {:?}\
             请确保 BPF 程序的 SEC() 声明与 attach 点匹配。",
            attach_kind, expected, actual
        )));
    }
    Ok(())
}

/// detach 一个已 attach 的句柄(内部实现,不消费 self)
fn detach_handle_inner(handle: &mut AttachedHandleInner) -> Result<(), AttachError> {
    match handle {
        AttachedHandleInner::Xdp { ifindex, mode } => {
            // 用相同模式 detach(bpf_xdp_detach)
            detach_xdp_raw(*ifindex, *mode)?;
            Ok(())
        }
        AttachedHandleInner::Tc {
            hook, direction, ..
        } => {
            // 只 detach 自己的 hook,不 destroy clsact qdisc
            // (destroy 会破坏同一网卡上其他 TC 程序,不安全)
            hook.detach().map_err(|e| {
                AttachError::Libbpf(format!(
                    "TC detach 失败 ({}): {}",
                    direction.as_str(),
                    e
                ))
            })
        }
        AttachedHandleInner::Cgroup { link, .. } => {
            // Link::detach 分离 bpf_link,Drop 会销毁
            link.detach().map_err(|e| {
                AttachError::Libbpf(format!("cgroup detach 失败: {}", e))
            })
        }
        AttachedHandleInner::SocketFilter { socket_fd } => {
            // SAFETY: setsockopt 是 POSIX 系统调用。
            // - sockfd: 来自原始 attach 时的 socket_fd(已校验 >= 0)
            // - optname: SO_DETACH_BPF 为标准常量
            // - optval/optlen: NULL/0,SO_DETACH_BPF 不需要值
            let ret = unsafe {
                libc::setsockopt(
                    *socket_fd,
                    libc::SOL_SOCKET,
                    libc::SO_DETACH_BPF,
                    std::ptr::null(),
                    0,
                )
            };
            if ret != 0 {
                let err = std::io::Error::last_os_error();
                return Err(AttachError::Libbpf(format!(
                    "SO_DETACH_BPF 失败: {} (errno={})",
                    err,
                    err.raw_os_error().unwrap_or(0)
                )));
            }
            Ok(())
        }
    }
}

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

    #[test]
    fn test_tc_direction_as_str() {
        assert_eq!(TcDirection::Ingress.as_str(), "ingress");
        assert_eq!(TcDirection::Egress.as_str(), "egress");
    }

    #[test]
    fn test_tc_direction_to_attach_point() {
        assert_eq!(TcDirection::Ingress.to_attach_point(), TC_INGRESS);
        assert_eq!(TcDirection::Egress.to_attach_point(), TC_EGRESS);
    }

    #[test]
    fn test_tc_direction_eq() {
        assert_eq!(TcDirection::Ingress, TcDirection::Ingress);
        assert_ne!(TcDirection::Ingress, TcDirection::Egress);
    }

    #[test]
    fn test_cgroup_attach_type_as_str() {
        assert_eq!(CgroupAttachType::SockOps.as_str(), "sock_ops");
        assert_eq!(CgroupAttachType::InetIngress.as_str(), "inet_ingress");
        assert_eq!(CgroupAttachType::InetEgress.as_str(), "inet_egress");
        assert_eq!(CgroupAttachType::SockCreate.as_str(), "sock_create");
    }

    #[test]
    fn test_cgroup_attach_type_unique() {
        let types = [
            CgroupAttachType::SockOps,
            CgroupAttachType::InetIngress,
            CgroupAttachType::InetEgress,
            CgroupAttachType::SockCreate,
        ];
        // 枚举值与字符串表示唯一
        for (i, a) in types.iter().enumerate() {
            for (j, b) in types.iter().enumerate() {
                if i != j {
                    assert_ne!(a, b);
                    assert_ne!(a.as_str(), b.as_str());
                }
            }
        }
        // SockOps 与其他三者的 expected_prog_type 不同
        assert_ne!(
            CgroupAttachType::SockOps.expected_prog_type() as u32,
            CgroupAttachType::InetIngress.expected_prog_type() as u32
        );
        // InetIngress/InetEgress/SockCreate 共享 CgroupSkb(同一 prog_type)
        assert_eq!(
            CgroupAttachType::InetIngress.expected_prog_type() as u32,
            CgroupAttachType::InetEgress.expected_prog_type() as u32
        );
        assert_eq!(
            CgroupAttachType::InetEgress.expected_prog_type() as u32,
            CgroupAttachType::SockCreate.expected_prog_type() as u32
        );
    }

    #[test]
    fn test_attach_point_kind() {
        let xdp = AttachPoint::Xdp {
            ifindex: 1,
            mode: XdpAttachMode::Auto,
        };
        assert_eq!(xdp.kind(), "xdp");

        let tc = AttachPoint::Tc {
            ifindex: 1,
            direction: TcDirection::Ingress,
            replace: false,
        };
        assert_eq!(tc.kind(), "tc");

        let cg = AttachPoint::Cgroup {
            cgroup_path: PathBuf::from("/sys/fs/cgroup/"),
            attach_type: CgroupAttachType::SockOps,
        };
        assert_eq!(cg.kind(), "cgroup");

        let sf = AttachPoint::SocketFilter { socket_fd: 3 };
        assert_eq!(sf.kind(), "socket_filter");
    }

    #[test]
    fn test_attach_point_clone() {
        let p1 = AttachPoint::Xdp {
            ifindex: 1,
            mode: XdpAttachMode::Drv,
        };
        let p2 = p1.clone();
        if let AttachPoint::Xdp { ifindex, mode } = &p2 {
            assert_eq!(*ifindex, 1);
            assert_eq!(*mode, XdpAttachMode::Drv);
        } else {
            panic!("clone 后类型应为 Xdp");
        }
    }

    #[test]
    fn test_attach_point_debug() {
        let p = AttachPoint::Tc {
            ifindex: 1,
            direction: TcDirection::Egress,
            replace: true,
        };
        let s = format!("{:?}", p);
        assert!(s.contains("Tc"));
        assert!(s.contains("Egress"));
    }

    #[test]
    fn test_cgroup_attach_type_all_variants() {
        let variants = [
            CgroupAttachType::SockOps,
            CgroupAttachType::InetIngress,
            CgroupAttachType::InetEgress,
            CgroupAttachType::SockCreate,
        ];
        assert_eq!(variants.len(), 4);
        for v in variants.iter() {
            assert!(!v.as_str().is_empty());
        }
    }

    #[test]
    fn test_tc_direction_all_variants() {
        let variants = [TcDirection::Ingress, TcDirection::Egress];
        assert_eq!(variants.len(), 2);
        for v in variants.iter() {
            assert!(!v.as_str().is_empty());
        }
    }

    // ─── 便捷构造函数测试 ───────────────────────────────────────────────────

    #[test]
    fn test_attach_point_xdp_auto() {
        let p = AttachPoint::xdp_auto(2);
        assert_eq!(p.kind(), "xdp");
        if let AttachPoint::Xdp { ifindex, mode } = p {
            assert_eq!(ifindex, 2);
            assert_eq!(mode, XdpAttachMode::Auto);
        } else {
            panic!("应为 Xdp 变体");
        }
    }

    #[test]
    fn test_attach_point_xdp_with_mode() {
        let p = AttachPoint::xdp_with_mode(3, XdpAttachMode::Drv);
        if let AttachPoint::Xdp { ifindex, mode } = p {
            assert_eq!(ifindex, 3);
            assert_eq!(mode, XdpAttachMode::Drv);
        } else {
            panic!("应为 Xdp 变体");
        }
    }

    #[test]
    fn test_attach_point_tc_ingress() {
        let p = AttachPoint::tc_ingress(5);
        if let AttachPoint::Tc {
            ifindex,
            direction,
            replace,
        } = p
        {
            assert_eq!(ifindex, 5);
            assert_eq!(direction, TcDirection::Ingress);
            assert!(!replace);
        } else {
            panic!("应为 Tc 变体");
        }
    }

    #[test]
    fn test_attach_point_tc_egress() {
        let p = AttachPoint::tc_egress(7);
        if let AttachPoint::Tc { direction, .. } = p {
            assert_eq!(direction, TcDirection::Egress);
        } else {
            panic!("应为 Tc 变体");
        }
    }

    #[test]
    fn test_attach_point_cgroup_sock_ops() {
        let p = AttachPoint::cgroup_sock_ops("/sys/fs/cgroup/test");
        if let AttachPoint::Cgroup {
            cgroup_path,
            attach_type,
        } = p
        {
            assert_eq!(cgroup_path, PathBuf::from("/sys/fs/cgroup/test"));
            assert_eq!(attach_type, CgroupAttachType::SockOps);
        } else {
            panic!("应为 Cgroup 变体");
        }
    }

    #[test]
    fn test_attach_point_socket_filter() {
        let p = AttachPoint::socket_filter(42);
        if let AttachPoint::SocketFilter { socket_fd } = p {
            assert_eq!(socket_fd, 42);
        } else {
            panic!("应为 SocketFilter 变体");
        }
    }

    // ─── cgroup attach_type 与 prog_type 映射测试 ──────────────────────────

    #[test]
    fn test_cgroup_attach_type_expected_prog_type() {
        // SockOps 对应 BPF_PROG_TYPE_SOCK_OPS
        assert_eq!(
            CgroupAttachType::SockOps.expected_prog_type() as u32,
            ProgramType::SockOps as u32
        );
        // InetIngress/InetEgress/SockCreate 对应 BPF_PROG_TYPE_CGROUP_SKB
        assert_eq!(
            CgroupAttachType::InetIngress.expected_prog_type() as u32,
            ProgramType::CgroupSkb as u32
        );
        assert_eq!(
            CgroupAttachType::InetEgress.expected_prog_type() as u32,
            ProgramType::CgroupSkb as u32
        );
        assert_eq!(
            CgroupAttachType::SockCreate.expected_prog_type() as u32,
            ProgramType::CgroupSkb as u32
        );
    }

    #[test]
    fn test_cgroup_attach_type_prog_type_consistency() {
        // 同一 attach_type 多次调用应返回一致结果
        for _ in 0..10 {
            assert_eq!(
                CgroupAttachType::SockOps.expected_prog_type() as u32,
                ProgramType::SockOps as u32
            );
        }
    }

    // ─── AttachedHandle 状态测试 ─────────────────────────────────────────────

    #[test]
    fn test_attached_handle_is_detached_initial() {
        // 构造一个 detached 状态的 handle(内部为 None)
        let handle = AttachedHandle { inner: None };
        assert!(handle.is_detached());
        assert_eq!(handle.kind(), "detached");
    }

    #[test]
    fn test_attached_handle_detach_when_already_detached() {
        // 对已 detach 的 handle 调用 detach 应返回 Ok(幂等)
        let mut handle = AttachedHandle { inner: None };
        let result = handle.detach();
        assert!(result.is_ok(), "detach 幂等应返回 Ok: {:?}", result.err());
    }
}