-
Notifications
You must be signed in to change notification settings - Fork 250
/
sock_map.rs
106 lines (97 loc) · 2.83 KB
/
sock_map.rs
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
use core::mem;
use aya_bpf_cty::c_void;
use crate::{
bindings::{bpf_map_def, bpf_map_type::BPF_MAP_TYPE_SOCKMAP, bpf_sock_ops},
helpers::{
bpf_map_lookup_elem, bpf_msg_redirect_map, bpf_sk_assign, bpf_sk_redirect_map,
bpf_sk_release, bpf_sock_map_update,
},
maps::PinningType,
programs::{SkBuffContext, SkLookupContext, SkMsgContext},
BpfContext,
};
#[repr(transparent)]
pub struct SockMap {
def: bpf_map_def,
}
impl SockMap {
pub const fn with_max_entries(max_entries: u32, flags: u32) -> SockMap {
SockMap {
def: bpf_map_def {
type_: BPF_MAP_TYPE_SOCKMAP,
key_size: mem::size_of::<u32>() as u32,
value_size: mem::size_of::<u32>() as u32,
max_entries,
map_flags: flags,
id: 0,
pinning: PinningType::None as u32,
},
}
}
pub const fn pinned(max_entries: u32, flags: u32) -> SockMap {
SockMap {
def: bpf_map_def {
type_: BPF_MAP_TYPE_SOCKMAP,
key_size: mem::size_of::<u32>() as u32,
value_size: mem::size_of::<u32>() as u32,
max_entries,
map_flags: flags,
id: 0,
pinning: PinningType::ByName as u32,
},
}
}
pub unsafe fn update(
&mut self,
mut index: u32,
sk_ops: *mut bpf_sock_ops,
flags: u64,
) -> Result<(), i64> {
let ret = bpf_sock_map_update(
sk_ops,
&mut self.def as *mut _ as *mut _,
&mut index as *mut _ as *mut c_void,
flags,
);
if ret < 0 {
Err(ret)
} else {
Ok(())
}
}
pub unsafe fn redirect_msg(&mut self, ctx: &SkMsgContext, index: u32, flags: u64) -> i64 {
bpf_msg_redirect_map(
ctx.as_ptr() as *mut _,
&mut self.def as *mut _ as *mut _,
index,
flags,
)
}
pub unsafe fn redirect_skb(&mut self, ctx: &SkBuffContext, index: u32, flags: u64) -> i64 {
bpf_sk_redirect_map(
ctx.as_ptr() as *mut _,
&mut self.def as *mut _ as *mut _,
index,
flags,
)
}
pub fn redirect_sk_lookup(
&mut self,
ctx: &SkLookupContext,
index: u32,
flags: u64,
) -> Result<(), u32> {
unsafe {
let sk = bpf_map_lookup_elem(
&mut self.def as *mut _ as *mut _,
&index as *const _ as *const c_void,
);
if sk.is_null() {
return Err(1);
}
let ret = bpf_sk_assign(ctx.as_ptr() as *mut _, sk, flags);
bpf_sk_release(sk);
(ret >= 0).then(|| ()).ok_or(1)
}
}
}