gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/test/iptables/runner/main.go (about)

     1  // Copyright 2019 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 main runs iptables tests from within a docker container.
    16  package main
    17  
    18  import (
    19  	"context"
    20  	"flag"
    21  	"fmt"
    22  	"log"
    23  	"net"
    24  
    25  	"gvisor.dev/gvisor/test/iptables"
    26  )
    27  
    28  var (
    29  	name = flag.String("name", "", "name of the test to run")
    30  	ipv6 = flag.Bool("ipv6", false, "whether the test utilizes ip6tables")
    31  )
    32  
    33  func main() {
    34  	flag.Parse()
    35  
    36  	// Find out which test we're running.
    37  	test, ok := iptables.Tests[*name]
    38  	if !ok {
    39  		log.Fatalf("No test found named %q", *name)
    40  	}
    41  	log.Printf("Running test %q", *name)
    42  
    43  	// Get the IP of the local process.
    44  	ip, err := getIP()
    45  	if err != nil {
    46  		log.Fatal(err)
    47  	}
    48  
    49  	// Run the test.
    50  	ctx, cancel := context.WithCancel(context.Background())
    51  	defer cancel()
    52  	if err := test.ContainerAction(ctx, ip, *ipv6); err != nil {
    53  		log.Fatalf("Failed running test %q: %v", *name, err)
    54  	}
    55  
    56  	// Emit the final line.
    57  	log.Printf("%s", iptables.TerminalStatement)
    58  }
    59  
    60  // getIP listens for a connection from the local process and returns the source
    61  // IP of that connection.
    62  func getIP() (net.IP, error) {
    63  	localAddr := net.TCPAddr{
    64  		Port: iptables.IPExchangePort,
    65  	}
    66  	listener, err := net.ListenTCP("tcp", &localAddr)
    67  	if err != nil {
    68  		return net.IP{}, fmt.Errorf("failed listening for IP: %v", err)
    69  	}
    70  	defer listener.Close()
    71  	conn, err := listener.AcceptTCP()
    72  	if err != nil {
    73  		return net.IP{}, fmt.Errorf("failed accepting IP: %v", err)
    74  	}
    75  	defer conn.Close()
    76  	log.Printf("Connected to %v", conn.RemoteAddr())
    77  
    78  	return conn.RemoteAddr().(*net.TCPAddr).IP, nil
    79  }