| 1 |
|
| 2 |
|
| 3 |
package link |
| 4 |
|
| 5 |
import ( |
| 6 |
"fmt" |
| 7 |
"runtime" |
| 8 |
|
| 9 |
"github.com/cilium/ebpf" |
| 10 |
"github.com/cilium/ebpf/internal/sys" |
| 11 |
) |
| 12 |
|
| 13 |
type TCXOptions struct { |
| 14 |
|
| 15 |
Interface int |
| 16 |
|
| 17 |
Program *ebpf.Program |
| 18 |
|
| 19 |
Attach ebpf.AttachType |
| 20 |
|
| 21 |
Anchor Anchor |
| 22 |
|
| 23 |
ExpectedRevision uint64 |
| 24 |
|
| 25 |
|
| 26 |
Flags uint32 |
| 27 |
} |
| 28 |
|
| 29 |
func AttachTCX(opts TCXOptions) (Link, error) { |
| 30 |
if opts.Interface < 0 { |
| 31 |
return nil, fmt.Errorf("interface %d is out of bounds", opts.Interface) |
| 32 |
} |
| 33 |
|
| 34 |
if opts.Flags&anchorFlags != 0 { |
| 35 |
return nil, fmt.Errorf("disallowed flags: use Anchor to specify attach target") |
| 36 |
} |
| 37 |
|
| 38 |
attr := sys.LinkCreateTcxAttr{ |
| 39 |
ProgFd: uint32(opts.Program.FD()), |
| 40 |
AttachType: sys.AttachType(opts.Attach), |
| 41 |
TargetIfindex: uint32(opts.Interface), |
| 42 |
ExpectedRevision: opts.ExpectedRevision, |
| 43 |
Flags: opts.Flags, |
| 44 |
} |
| 45 |
|
| 46 |
if opts.Anchor != nil { |
| 47 |
fdOrID, flags, err := opts.Anchor.anchor() |
| 48 |
if err != nil { |
| 49 |
return nil, fmt.Errorf("attach tcx link: %w", err) |
| 50 |
} |
| 51 |
|
| 52 |
attr.RelativeFdOrId = fdOrID |
| 53 |
attr.Flags |= flags |
| 54 |
} |
| 55 |
|
| 56 |
fd, err := sys.LinkCreateTcx(&attr) |
| 57 |
runtime.KeepAlive(opts.Program) |
| 58 |
runtime.KeepAlive(opts.Anchor) |
| 59 |
if err != nil { |
| 60 |
if haveFeatErr := haveTCX(); haveFeatErr != nil { |
| 61 |
return nil, haveFeatErr |
| 62 |
} |
| 63 |
return nil, fmt.Errorf("attach tcx link: %w", err) |
| 64 |
} |
| 65 |
|
| 66 |
return &tcxLink{RawLink{fd, ""}}, nil |
| 67 |
} |
| 68 |
|
| 69 |
type tcxLink struct { |
| 70 |
RawLink |
| 71 |
} |
| 72 |
|
| 73 |
var _ Link = (*tcxLink)(nil) |
| 74 |
|
| 75 |
func (tcx *tcxLink) Info() (*Info, error) { |
| 76 |
var info sys.TcxLinkInfo |
| 77 |
if err := sys.ObjInfo(tcx.fd, &info); err != nil { |
| 78 |
return nil, fmt.Errorf("tcx link info: %s", err) |
| 79 |
} |
| 80 |
extra := &TCXInfo{ |
| 81 |
Ifindex: info.Ifindex, |
| 82 |
AttachType: info.AttachType, |
| 83 |
} |
| 84 |
|
| 85 |
return &Info{ |
| 86 |
info.Type, |
| 87 |
info.Id, |
| 88 |
ebpf.ProgramID(info.ProgId), |
| 89 |
extra, |
| 90 |
}, nil |
| 91 |
} |