github.com/pawelgaczynski/gain@v0.4.0-alpha.0.20230821120126-41f1e60a18da/cbpf.go (about)

     1  // Copyright (c) 2023 Paweł Gaczyński
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package gain
    16  
    17  import (
    18  	"fmt"
    19  	"syscall"
    20  	"unsafe"
    21  
    22  	"golang.org/x/net/bpf"
    23  	"golang.org/x/sys/unix"
    24  )
    25  
    26  const (
    27  	skfAdOffPlusKSkfAdCPU = 4294963236
    28  	cpuIDSize             = 4
    29  )
    30  
    31  type filter []bpf.Instruction
    32  
    33  func (f filter) applyTo(fileDescriptor int) error {
    34  	var (
    35  		err       error
    36  		assembled []bpf.RawInstruction
    37  	)
    38  
    39  	if assembled, err = bpf.Assemble(f); err != nil {
    40  		return fmt.Errorf("BPF filter assemble error: %w", err)
    41  	}
    42  	program := unix.SockFprog{
    43  		Len:    uint16(len(assembled)),
    44  		Filter: (*unix.SockFilter)(unsafe.Pointer(&assembled[0])),
    45  	}
    46  	b := (*[unix.SizeofSockFprog]byte)(unsafe.Pointer(&program))[:unix.SizeofSockFprog]
    47  
    48  	if _, _, errno := syscall.Syscall6(syscall.SYS_SETSOCKOPT,
    49  		uintptr(fileDescriptor), uintptr(syscall.SOL_SOCKET), uintptr(unix.SO_ATTACH_REUSEPORT_CBPF),
    50  		uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), 0); errno != 0 {
    51  		return errno
    52  	}
    53  
    54  	return nil
    55  }
    56  
    57  // /* A = raw_smp_processor_id(). */
    58  // { BPF_LD  | BPF_W | BPF_ABS, 0, 0, SKF_AD_OFF + SKF_AD_CPU },
    59  // /* Adjust the CPUID to socket group size. */
    60  // { BPF_ALU | BPF_MOD | BPF_K, 0, 0, sock_count },
    61  // /* Return A. */
    62  // { BPF_RET | BPF_A, 0, 0, 0 },
    63  //
    64  //nolint:godot
    65  func newFilter(cpus uint32) filter {
    66  	return filter{
    67  		bpf.LoadAbsolute{Off: skfAdOffPlusKSkfAdCPU, Size: cpuIDSize},
    68  		bpf.ALUOpConstant{Op: bpf.ALUOpMod, Val: cpus},
    69  		bpf.RetA{}, // return 0xffff bytes (or less) from packet.
    70  	}
    71  }