github.com/cilium/ebpf@v0.15.1-0.20240517100537-8079b37aa138/link/socket_filter.go (about)

     1  package link
     2  
     3  import (
     4  	"syscall"
     5  
     6  	"github.com/cilium/ebpf"
     7  	"github.com/cilium/ebpf/internal/unix"
     8  )
     9  
    10  // AttachSocketFilter attaches a SocketFilter BPF program to a socket.
    11  func AttachSocketFilter(conn syscall.Conn, program *ebpf.Program) error {
    12  	rawConn, err := conn.SyscallConn()
    13  	if err != nil {
    14  		return err
    15  	}
    16  	var ssoErr error
    17  	err = rawConn.Control(func(fd uintptr) {
    18  		ssoErr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_ATTACH_BPF, program.FD())
    19  	})
    20  	if ssoErr != nil {
    21  		return ssoErr
    22  	}
    23  	return err
    24  }
    25  
    26  // DetachSocketFilter detaches a SocketFilter BPF program from a socket.
    27  func DetachSocketFilter(conn syscall.Conn) error {
    28  	rawConn, err := conn.SyscallConn()
    29  	if err != nil {
    30  		return err
    31  	}
    32  	var ssoErr error
    33  	err = rawConn.Control(func(fd uintptr) {
    34  		ssoErr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_DETACH_BPF, 0)
    35  	})
    36  	if ssoErr != nil {
    37  		return ssoErr
    38  	}
    39  	return err
    40  }