Debian Codegraph @

link/link.go

raw symbols SCIP
1 package link
2
3 import (
4 "errors"
5 "fmt"
6 "os"
7
8 "github.com/cilium/ebpf"
9 "github.com/cilium/ebpf/btf"
10 "github.com/cilium/ebpf/internal"
11 "github.com/cilium/ebpf/internal/sys"
12 "github.com/cilium/ebpf/internal/unix"
13 )
14
15 // Type is the kind of link.
16 type Type = sys.LinkType
17
18 var ErrNotSupported = internal.ErrNotSupported
19
20 // Link represents a Program attached to a BPF hook.
21 type Link interface {
22 // Replace the current program with a new program.
23 //
24 // Passing a nil program is an error. May return an error wrapping ErrNotSupported.
25 Update(*ebpf.Program) error
26
27 // Persist a link by pinning it into a bpffs.
28 //
29 // May return an error wrapping ErrNotSupported.
30 Pin(string) error
31
32 // Undo a previous call to Pin.
33 //
34 // May return an error wrapping ErrNotSupported.
35 Unpin() error
36
37 // Close frees resources.
38 //
39 // The link will be broken unless it has been successfully pinned.
40 // A link may continue past the lifetime of the process if Close is
41 // not called.
42 Close() error
43
44 // Detach the link from its corresponding attachment point.
45 //
46 // May return an error wrapping ErrNotSupported.
47 Detach() error
48
49 // Info returns metadata on a link.
50 //
51 // May return an error wrapping ErrNotSupported.
52 Info() (*Info, error)
53
54 // Prevent external users from implementing this interface.
55 isLink()
56 }
57
58 // NewFromFD creates a link from a raw fd.
59 //
60 // You should not use fd after calling this function.
61 func NewFromFD(fd int) (Link, error) {
62 sysFD, err := sys.NewFD(fd)
63 if err != nil {
64 return nil, err
65 }
66
67 return wrapRawLink(&RawLink{fd: sysFD})
68 }
69
70 // NewFromID returns the link associated with the given id.
71 //
72 // Returns ErrNotExist if there is no link with the given id.
73 func NewFromID(id ID) (Link, error) {
74 getFdAttr := &sys.LinkGetFdByIdAttr{Id: id}
75 fd, err := sys.LinkGetFdById(getFdAttr)
76 if err != nil {
77 return nil, fmt.Errorf("get link fd from ID %d: %w", id, err)
78 }
79
80 return wrapRawLink(&RawLink{fd, ""})
81 }
82
83 // LoadPinnedLink loads a Link from a pin (file) on the BPF virtual filesystem.
84 //
85 // Requires at least Linux 5.7.
86 func LoadPinnedLink(fileName string, opts *ebpf.LoadPinOptions) (Link, error) {
87 raw, err := loadPinnedRawLink(fileName, opts)
88 if err != nil {
89 return nil, err
90 }
91
92 return wrapRawLink(raw)
93 }
94
95 // ID uniquely identifies a BPF link.
96 type ID = sys.LinkID
97
98 // RawLinkOptions control the creation of a raw link.
99 type RawLinkOptions struct {
100 // File descriptor to attach to. This differs for each attach type.
101 Target int
102 // Program to attach.
103 Program *ebpf.Program
104 // Attach must match the attach type of Program.
105 Attach ebpf.AttachType
106 // BTF is the BTF of the attachment target.
107 BTF btf.TypeID
108 // Flags control the attach behaviour.
109 Flags uint32
110 }
111
112 // Info contains metadata on a link.
113 type Info struct {
114 Type Type
115 ID ID
116 Program ebpf.ProgramID
117 extra any
118 }
119
120 // RawLink is the low-level API to bpf_link.
121 //
122 // You should consider using the higher level interfaces in this
123 // package instead.
124 type RawLink struct {
125 fd *sys.FD
126 pinnedPath string
127 }
128
129 func loadPinnedRawLink(fileName string, opts *ebpf.LoadPinOptions) (*RawLink, error) {
130 fd, typ, err := sys.ObjGetTyped(&sys.ObjGetAttr{
131 Pathname: sys.NewStringPointer(fileName),
132 FileFlags: opts.Marshal(),
133 })
134 if err != nil {
135 return nil, fmt.Errorf("load pinned link: %w", err)
136 }
137
138 if typ != sys.BPF_TYPE_LINK {
139 _ = fd.Close()
140 return nil, fmt.Errorf("%s is not a Link", fileName)
141 }
142
143 return &RawLink{fd, fileName}, nil
144 }
145
146 func (l *RawLink) isLink() {}
147
148 // FD returns the raw file descriptor.
149 func (l *RawLink) FD() int {
150 return l.fd.Int()
151 }
152
153 // Close breaks the link.
154 //
155 // Use Pin if you want to make the link persistent.
156 func (l *RawLink) Close() error {
157 return l.fd.Close()
158 }
159
160 // Pin persists a link past the lifetime of the process.
161 //
162 // Calling Close on a pinned Link will not break the link
163 // until the pin is removed.
164 func (l *RawLink) Pin(fileName string) error {
165 if err := sys.Pin(l.pinnedPath, fileName, l.fd); err != nil {
166 return err
167 }
168 l.pinnedPath = fileName
169 return nil
170 }
171
172 // Unpin implements the Link interface.
173 func (l *RawLink) Unpin() error {
174 if err := sys.Unpin(l.pinnedPath); err != nil {
175 return err
176 }
177 l.pinnedPath = ""
178 return nil
179 }
180
181 // IsPinned returns true if the Link has a non-empty pinned path.
182 func (l *RawLink) IsPinned() bool {
183 return l.pinnedPath != ""
184 }
185
186 // Update implements the Link interface.
187 func (l *RawLink) Update(new *ebpf.Program) error {
188 return l.UpdateArgs(RawLinkUpdateOptions{
189 New: new,
190 })
191 }
192
193 // RawLinkUpdateOptions control the behaviour of RawLink.UpdateArgs.
194 type RawLinkUpdateOptions struct {
195 New *ebpf.Program
196 Old *ebpf.Program
197 Flags uint32
198 }
199
200 // UpdateArgs updates a link based on args.
201 func (l *RawLink) UpdateArgs(opts RawLinkUpdateOptions) error {
202 newFd := opts.New.FD()
203 if newFd < 0 {
204 return fmt.Errorf("invalid program: %s", sys.ErrClosedFd)
205 }
206
207 var oldFd int
208 if opts.Old != nil {
209 oldFd = opts.Old.FD()
210 if oldFd < 0 {
211 return fmt.Errorf("invalid replacement program: %s", sys.ErrClosedFd)
212 }
213 }
214
215 attr := sys.LinkUpdateAttr{
216 LinkFd: l.fd.Uint(),
217 NewProgFd: uint32(newFd),
218 OldProgFd: uint32(oldFd),
219 Flags: opts.Flags,
220 }
221 if err := sys.LinkUpdate(&attr); err != nil {
222 return fmt.Errorf("update link: %w", err)
223 }
224 return nil
225 }
226
227 // Detach the link from its corresponding attachment point.
228 func (l *RawLink) Detach() error {
229 attr := sys.LinkDetachAttr{
230 LinkFd: l.fd.Uint(),
231 }
232
233 err := sys.LinkDetach(&attr)
234
235 switch {
236 case errors.Is(err, unix.EOPNOTSUPP):
237 return internal.ErrNotSupported
238 case err != nil:
239 return fmt.Errorf("detach link: %w", err)
240 default:
241 return nil
242 }
243 }
244
245 // Info returns metadata about the link.
246 //
247 // Linktype specific metadata is not included and can be retrieved
248 // via the linktype specific Info() method.
249 func (l *RawLink) Info() (*Info, error) {
250 var info sys.LinkInfo
251
252 if err := sys.ObjInfo(l.fd, &info); err != nil {
253 return nil, fmt.Errorf("link info: %s", err)
254 }
255
256 return &Info{
257 info.Type,
258 info.Id,
259 ebpf.ProgramID(info.ProgId),
260 nil,
261 }, nil
262 }
263
264 // Iterator allows iterating over links attached into the kernel.
265 type Iterator struct {
266 // The ID of the current link. Only valid after a call to Next
267 ID ID
268 // The current link. Only valid until a call to Next.
269 // See Take if you want to retain the link.
270 Link Link
271 err error
272 }
273
274 // Next retrieves the next link.
275 //
276 // Returns true if another link was found. Call [Iterator.Err] after the function returns false.
277 func (it *Iterator) Next() bool {
278 id := it.ID
279 for {
280 getIdAttr := &sys.LinkGetNextIdAttr{Id: id}
281 err := sys.LinkGetNextId(getIdAttr)
282 if errors.Is(err, os.ErrNotExist) {
283 // There are no more links.
284 break
285 } else if err != nil {
286 it.err = fmt.Errorf("get next link ID: %w", err)
287 break
288 }
289
290 id = getIdAttr.NextId
291 l, err := NewFromID(id)
292 if errors.Is(err, os.ErrNotExist) {
293 // Couldn't load the link fast enough. Try next ID.
294 continue
295 } else if err != nil {
296 it.err = fmt.Errorf("get link for ID %d: %w", id, err)
297 break
298 }
299
300 if it.Link != nil {
301 it.Link.Close()
302 }
303 it.ID, it.Link = id, l
304 return true
305 }
306
307 // No more links or we encountered an error.
308 if it.Link != nil {
309 it.Link.Close()
310 }
311 it.Link = nil
312 return false
313 }
314
315 // Take the ownership of the current link.
316 //
317 // It's the callers responsibility to close the link.
318 func (it *Iterator) Take() Link {
319 l := it.Link
320 it.Link = nil
321 return l
322 }
323
324 // Err returns an error if iteration failed for some reason.
325 func (it *Iterator) Err() error {
326 return it.err
327 }
328
329 func (it *Iterator) Close() {
330 if it.Link != nil {
331 it.Link.Close()
332 }
333 }