setup_ip_forwarding_test.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //go:build linux
  2. // +build linux
  3. package bridge
  4. import (
  5. "bytes"
  6. "os"
  7. "testing"
  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. // Disable IP Forwarding if enabled
  14. if bytes.Equal(procSetting, []byte("1\n")) {
  15. writeIPForwardingSetting(t, []byte{'0', '\n'})
  16. }
  17. // Set IP Forwarding
  18. if err := setupIPForwarding(true, true); err != nil {
  19. t.Fatalf("Failed to setup IP forwarding: %v", err)
  20. }
  21. // Read new setting
  22. procSetting = readCurrentIPForwardingSetting(t)
  23. if !bytes.Equal(procSetting, []byte("1\n")) {
  24. t.Fatal("Failed to effectively setup IP forwarding")
  25. }
  26. }
  27. func readCurrentIPForwardingSetting(t *testing.T) []byte {
  28. procSetting, err := os.ReadFile(ipv4ForwardConf)
  29. if err != nil {
  30. t.Fatalf("Can't execute test: Failed to read current IP forwarding setting: %v", err)
  31. }
  32. return procSetting
  33. }
  34. func writeIPForwardingSetting(t *testing.T, chars []byte) {
  35. err := os.WriteFile(ipv4ForwardConf, chars, ipv4ForwardConfPerm)
  36. if err != nil {
  37. t.Fatalf("Can't execute or cleanup after test: Failed to reset IP forwarding: %v", err)
  38. }
  39. }
  40. func reconcileIPForwardingSetting(t *testing.T, original []byte) {
  41. current := readCurrentIPForwardingSetting(t)
  42. if !bytes.Equal(original, current) {
  43. writeIPForwardingSetting(t, original)
  44. }
  45. }