link.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. package link
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "fmt"
  6. "github.com/cilium/ebpf"
  7. "github.com/cilium/ebpf/btf"
  8. "github.com/cilium/ebpf/internal"
  9. "github.com/cilium/ebpf/internal/sys"
  10. )
  11. var ErrNotSupported = internal.ErrNotSupported
  12. // Link represents a Program attached to a BPF hook.
  13. type Link interface {
  14. // Replace the current program with a new program.
  15. //
  16. // Passing a nil program is an error. May return an error wrapping ErrNotSupported.
  17. Update(*ebpf.Program) error
  18. // Persist a link by pinning it into a bpffs.
  19. //
  20. // May return an error wrapping ErrNotSupported.
  21. Pin(string) error
  22. // Undo a previous call to Pin.
  23. //
  24. // May return an error wrapping ErrNotSupported.
  25. Unpin() error
  26. // Close frees resources.
  27. //
  28. // The link will be broken unless it has been successfully pinned.
  29. // A link may continue past the lifetime of the process if Close is
  30. // not called.
  31. Close() error
  32. // Info returns metadata on a link.
  33. //
  34. // May return an error wrapping ErrNotSupported.
  35. Info() (*Info, error)
  36. // Prevent external users from implementing this interface.
  37. isLink()
  38. }
  39. // NewLinkFromFD creates a link from a raw fd.
  40. //
  41. // You should not use fd after calling this function.
  42. func NewLinkFromFD(fd int) (Link, error) {
  43. sysFD, err := sys.NewFD(fd)
  44. if err != nil {
  45. return nil, err
  46. }
  47. return wrapRawLink(&RawLink{fd: sysFD})
  48. }
  49. // LoadPinnedLink loads a link that was persisted into a bpffs.
  50. func LoadPinnedLink(fileName string, opts *ebpf.LoadPinOptions) (Link, error) {
  51. raw, err := loadPinnedRawLink(fileName, opts)
  52. if err != nil {
  53. return nil, err
  54. }
  55. return wrapRawLink(raw)
  56. }
  57. // wrap a RawLink in a more specific type if possible.
  58. //
  59. // The function takes ownership of raw and closes it on error.
  60. func wrapRawLink(raw *RawLink) (_ Link, err error) {
  61. defer func() {
  62. if err != nil {
  63. raw.Close()
  64. }
  65. }()
  66. info, err := raw.Info()
  67. if err != nil {
  68. return nil, err
  69. }
  70. switch info.Type {
  71. case RawTracepointType:
  72. return &rawTracepoint{*raw}, nil
  73. case TracingType:
  74. return &tracing{*raw}, nil
  75. case CgroupType:
  76. return &linkCgroup{*raw}, nil
  77. case IterType:
  78. return &Iter{*raw}, nil
  79. case NetNsType:
  80. return &NetNsLink{*raw}, nil
  81. case KprobeMultiType:
  82. return &kprobeMultiLink{*raw}, nil
  83. case PerfEventType:
  84. return nil, fmt.Errorf("recovering perf event fd: %w", ErrNotSupported)
  85. default:
  86. return raw, nil
  87. }
  88. }
  89. // ID uniquely identifies a BPF link.
  90. type ID = sys.LinkID
  91. // RawLinkOptions control the creation of a raw link.
  92. type RawLinkOptions struct {
  93. // File descriptor to attach to. This differs for each attach type.
  94. Target int
  95. // Program to attach.
  96. Program *ebpf.Program
  97. // Attach must match the attach type of Program.
  98. Attach ebpf.AttachType
  99. // BTF is the BTF of the attachment target.
  100. BTF btf.TypeID
  101. // Flags control the attach behaviour.
  102. Flags uint32
  103. }
  104. // Info contains metadata on a link.
  105. type Info struct {
  106. Type Type
  107. ID ID
  108. Program ebpf.ProgramID
  109. extra interface{}
  110. }
  111. type TracingInfo sys.TracingLinkInfo
  112. type CgroupInfo sys.CgroupLinkInfo
  113. type NetNsInfo sys.NetNsLinkInfo
  114. type XDPInfo sys.XDPLinkInfo
  115. // Tracing returns tracing type-specific link info.
  116. //
  117. // Returns nil if the type-specific link info isn't available.
  118. func (r Info) Tracing() *TracingInfo {
  119. e, _ := r.extra.(*TracingInfo)
  120. return e
  121. }
  122. // Cgroup returns cgroup type-specific link info.
  123. //
  124. // Returns nil if the type-specific link info isn't available.
  125. func (r Info) Cgroup() *CgroupInfo {
  126. e, _ := r.extra.(*CgroupInfo)
  127. return e
  128. }
  129. // NetNs returns netns type-specific link info.
  130. //
  131. // Returns nil if the type-specific link info isn't available.
  132. func (r Info) NetNs() *NetNsInfo {
  133. e, _ := r.extra.(*NetNsInfo)
  134. return e
  135. }
  136. // ExtraNetNs returns XDP type-specific link info.
  137. //
  138. // Returns nil if the type-specific link info isn't available.
  139. func (r Info) XDP() *XDPInfo {
  140. e, _ := r.extra.(*XDPInfo)
  141. return e
  142. }
  143. // RawLink is the low-level API to bpf_link.
  144. //
  145. // You should consider using the higher level interfaces in this
  146. // package instead.
  147. type RawLink struct {
  148. fd *sys.FD
  149. pinnedPath string
  150. }
  151. // AttachRawLink creates a raw link.
  152. func AttachRawLink(opts RawLinkOptions) (*RawLink, error) {
  153. if err := haveBPFLink(); err != nil {
  154. return nil, err
  155. }
  156. if opts.Target < 0 {
  157. return nil, fmt.Errorf("invalid target: %s", sys.ErrClosedFd)
  158. }
  159. progFd := opts.Program.FD()
  160. if progFd < 0 {
  161. return nil, fmt.Errorf("invalid program: %s", sys.ErrClosedFd)
  162. }
  163. attr := sys.LinkCreateAttr{
  164. TargetFd: uint32(opts.Target),
  165. ProgFd: uint32(progFd),
  166. AttachType: sys.AttachType(opts.Attach),
  167. TargetBtfId: opts.BTF,
  168. Flags: opts.Flags,
  169. }
  170. fd, err := sys.LinkCreate(&attr)
  171. if err != nil {
  172. return nil, fmt.Errorf("create link: %w", err)
  173. }
  174. return &RawLink{fd, ""}, nil
  175. }
  176. func loadPinnedRawLink(fileName string, opts *ebpf.LoadPinOptions) (*RawLink, error) {
  177. fd, err := sys.ObjGet(&sys.ObjGetAttr{
  178. Pathname: sys.NewStringPointer(fileName),
  179. FileFlags: opts.Marshal(),
  180. })
  181. if err != nil {
  182. return nil, fmt.Errorf("load pinned link: %w", err)
  183. }
  184. return &RawLink{fd, fileName}, nil
  185. }
  186. func (l *RawLink) isLink() {}
  187. // FD returns the raw file descriptor.
  188. func (l *RawLink) FD() int {
  189. return l.fd.Int()
  190. }
  191. // Close breaks the link.
  192. //
  193. // Use Pin if you want to make the link persistent.
  194. func (l *RawLink) Close() error {
  195. return l.fd.Close()
  196. }
  197. // Pin persists a link past the lifetime of the process.
  198. //
  199. // Calling Close on a pinned Link will not break the link
  200. // until the pin is removed.
  201. func (l *RawLink) Pin(fileName string) error {
  202. if err := internal.Pin(l.pinnedPath, fileName, l.fd); err != nil {
  203. return err
  204. }
  205. l.pinnedPath = fileName
  206. return nil
  207. }
  208. // Unpin implements the Link interface.
  209. func (l *RawLink) Unpin() error {
  210. if err := internal.Unpin(l.pinnedPath); err != nil {
  211. return err
  212. }
  213. l.pinnedPath = ""
  214. return nil
  215. }
  216. // IsPinned returns true if the Link has a non-empty pinned path.
  217. func (l *RawLink) IsPinned() bool {
  218. return l.pinnedPath != ""
  219. }
  220. // Update implements the Link interface.
  221. func (l *RawLink) Update(new *ebpf.Program) error {
  222. return l.UpdateArgs(RawLinkUpdateOptions{
  223. New: new,
  224. })
  225. }
  226. // RawLinkUpdateOptions control the behaviour of RawLink.UpdateArgs.
  227. type RawLinkUpdateOptions struct {
  228. New *ebpf.Program
  229. Old *ebpf.Program
  230. Flags uint32
  231. }
  232. // UpdateArgs updates a link based on args.
  233. func (l *RawLink) UpdateArgs(opts RawLinkUpdateOptions) error {
  234. newFd := opts.New.FD()
  235. if newFd < 0 {
  236. return fmt.Errorf("invalid program: %s", sys.ErrClosedFd)
  237. }
  238. var oldFd int
  239. if opts.Old != nil {
  240. oldFd = opts.Old.FD()
  241. if oldFd < 0 {
  242. return fmt.Errorf("invalid replacement program: %s", sys.ErrClosedFd)
  243. }
  244. }
  245. attr := sys.LinkUpdateAttr{
  246. LinkFd: l.fd.Uint(),
  247. NewProgFd: uint32(newFd),
  248. OldProgFd: uint32(oldFd),
  249. Flags: opts.Flags,
  250. }
  251. return sys.LinkUpdate(&attr)
  252. }
  253. // Info returns metadata about the link.
  254. func (l *RawLink) Info() (*Info, error) {
  255. var info sys.LinkInfo
  256. if err := sys.ObjInfo(l.fd, &info); err != nil {
  257. return nil, fmt.Errorf("link info: %s", err)
  258. }
  259. var extra interface{}
  260. switch info.Type {
  261. case CgroupType:
  262. extra = &CgroupInfo{}
  263. case NetNsType:
  264. extra = &NetNsInfo{}
  265. case TracingType:
  266. extra = &TracingInfo{}
  267. case XDPType:
  268. extra = &XDPInfo{}
  269. case RawTracepointType, IterType,
  270. PerfEventType, KprobeMultiType:
  271. // Extra metadata not supported.
  272. default:
  273. return nil, fmt.Errorf("unknown link info type: %d", info.Type)
  274. }
  275. if extra != nil {
  276. buf := bytes.NewReader(info.Extra[:])
  277. err := binary.Read(buf, internal.NativeEndian, extra)
  278. if err != nil {
  279. return nil, fmt.Errorf("cannot read extra link info: %w", err)
  280. }
  281. }
  282. return &Info{
  283. info.Type,
  284. info.Id,
  285. ebpf.ProgramID(info.ProgId),
  286. extra,
  287. }, nil
  288. }