structs_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright (C) 2016 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package nat
  7. import (
  8. "net"
  9. "os"
  10. "testing"
  11. "github.com/syncthing/syncthing/lib/config"
  12. "github.com/syncthing/syncthing/lib/events"
  13. "github.com/syncthing/syncthing/lib/protocol"
  14. )
  15. func TestMappingValidGateway(t *testing.T) {
  16. a := net.ParseIP("10.0.0.1")
  17. b := net.ParseIP("192.168.0.1")
  18. tests := []struct {
  19. mappingLocalIP net.IP
  20. gatewayLocalIP net.IP
  21. expected bool
  22. }{
  23. // Any of the IPs is nil or unspecified implies correct
  24. {nil, nil, true},
  25. {net.IPv4zero, net.IPv4zero, true},
  26. {nil, net.IPv4zero, true},
  27. {net.IPv4zero, nil, true},
  28. {a, nil, true},
  29. {b, nil, true},
  30. {a, net.IPv4zero, true},
  31. {b, net.IPv4zero, true},
  32. {nil, a, true},
  33. {nil, b, true},
  34. {net.IPv4zero, a, true},
  35. {net.IPv4zero, b, true},
  36. // IPs are the same implies correct
  37. {a, a, true},
  38. {b, b, true},
  39. // IPs are specified and different, implies incorrect
  40. {a, b, false},
  41. {b, a, false},
  42. }
  43. for _, test := range tests {
  44. m := Mapping{
  45. address: Address{
  46. IP: test.mappingLocalIP,
  47. },
  48. }
  49. result := m.validGateway(test.gatewayLocalIP)
  50. if result != test.expected {
  51. t.Errorf("Incorrect: local %s gateway %s result %t expected %t", test.mappingLocalIP, test.gatewayLocalIP, result, test.expected)
  52. }
  53. }
  54. }
  55. func TestMappingClearAddresses(t *testing.T) {
  56. tmpFile, err := os.CreateTemp("", "syncthing-testConfig-")
  57. if err != nil {
  58. t.Fatal(err)
  59. }
  60. w := config.Wrap(tmpFile.Name(), config.Configuration{}, protocol.LocalDeviceID, events.NoopLogger)
  61. defer os.RemoveAll(tmpFile.Name())
  62. tmpFile.Close()
  63. natSvc := NewService(protocol.EmptyDeviceID, w)
  64. // Mock a mapped port; avoids the need to actually map a port
  65. ip := net.ParseIP("192.168.0.1")
  66. m := natSvc.NewMapping(TCP, IPv4Only, ip, 1024)
  67. m.extAddresses["test"] = []Address{{
  68. IP: ip,
  69. Port: 1024,
  70. }}
  71. // Now try and remove the mapped port; prior to #4829 this deadlocked
  72. natSvc.RemoveMapping(m)
  73. }