gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/tools/xdp/cmd/drop.go (about)

     1  // Copyright 2022 The gVisor Authors.
     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 cmd
    16  
    17  import (
    18  	"context"
    19  	_ "embed"
    20  	"log"
    21  
    22  	"github.com/google/subcommands"
    23  	"gvisor.dev/gvisor/runsc/flag"
    24  )
    25  
    26  //go:embed bpf/drop_ebpf.o
    27  var dropProgram []byte
    28  
    29  // DropCommand is a subcommand for dropping packets.
    30  type DropCommand struct {
    31  	device      string
    32  	deviceIndex int
    33  }
    34  
    35  // Name implements subcommands.Command.Name.
    36  func (*DropCommand) Name() string {
    37  	return "drop"
    38  }
    39  
    40  // Synopsis implements subcommands.Command.Synopsis.
    41  func (*DropCommand) Synopsis() string {
    42  	return "Drop all packets to the kernel network stack."
    43  }
    44  
    45  // Usage implements subcommands.Command.Usage.
    46  func (*DropCommand) Usage() string {
    47  	return "drop -device <device> or -devidx <device index>"
    48  }
    49  
    50  // SetFlags implements subcommands.Command.SetFlags.
    51  func (pc *DropCommand) SetFlags(fs *flag.FlagSet) {
    52  	fs.StringVar(&pc.device, "device", "", "which device to attach to")
    53  	fs.IntVar(&pc.deviceIndex, "devidx", 0, "which device to attach to")
    54  }
    55  
    56  // Execute implements subcommands.Command.Execute.
    57  func (pc *DropCommand) Execute(context.Context, *flag.FlagSet, ...any) subcommands.ExitStatus {
    58  	if err := runBasicProgram(dropProgram, pc.device, pc.deviceIndex); err != nil {
    59  		log.Printf("%v", err)
    60  		return subcommands.ExitFailure
    61  	}
    62  	return subcommands.ExitSuccess
    63  }