github.com/pwn-term/docker@v0.0.0-20210616085119-6e977cce2565/libnetwork/drivers/bridge/setup_ip_forwarding_test.go (about)

     1  package bridge
     2  
     3  import (
     4  	"bytes"
     5  	"io/ioutil"
     6  	"testing"
     7  )
     8  
     9  func TestSetupIPForwarding(t *testing.T) {
    10  	// Read current setting and ensure the original value gets restored
    11  	procSetting := readCurrentIPForwardingSetting(t)
    12  	defer reconcileIPForwardingSetting(t, procSetting)
    13  
    14  	// Disable IP Forwarding if enabled
    15  	if bytes.Compare(procSetting, []byte("1\n")) == 0 {
    16  		writeIPForwardingSetting(t, []byte{'0', '\n'})
    17  	}
    18  
    19  	// Set IP Forwarding
    20  	if err := setupIPForwarding(true, true); err != nil {
    21  		t.Fatalf("Failed to setup IP forwarding: %v", err)
    22  	}
    23  
    24  	// Read new setting
    25  	procSetting = readCurrentIPForwardingSetting(t)
    26  	if bytes.Compare(procSetting, []byte("1\n")) != 0 {
    27  		t.Fatal("Failed to effectively setup IP forwarding")
    28  	}
    29  }
    30  
    31  func readCurrentIPForwardingSetting(t *testing.T) []byte {
    32  	procSetting, err := ioutil.ReadFile(ipv4ForwardConf)
    33  	if err != nil {
    34  		t.Fatalf("Can't execute test: Failed to read current IP forwarding setting: %v", err)
    35  	}
    36  	return procSetting
    37  }
    38  
    39  func writeIPForwardingSetting(t *testing.T, chars []byte) {
    40  	err := ioutil.WriteFile(ipv4ForwardConf, chars, ipv4ForwardConfPerm)
    41  	if err != nil {
    42  		t.Fatalf("Can't execute or cleanup after test: Failed to reset IP forwarding: %v", err)
    43  	}
    44  }
    45  
    46  func reconcileIPForwardingSetting(t *testing.T, original []byte) {
    47  	current := readCurrentIPForwardingSetting(t)
    48  	if bytes.Compare(original, current) != 0 {
    49  		writeIPForwardingSetting(t, original)
    50  	}
    51  }