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. "io/ioutil"
  9. "net"
  10. "os"
  11. "testing"
  12. "github.com/syncthing/syncthing/lib/config"
  13. "github.com/syncthing/syncthing/lib/events"
  14. "github.com/syncthing/syncthing/lib/protocol"
  15. )
  16. func TestMappingValidGateway(t *testing.T) {
  17. a := net.ParseIP("10.0.0.1")
  18. b := net.ParseIP("192.168.0.1")
  19. tests := []struct {
  20. mappingLocalIP net.IP
  21. gatewayLocalIP net.IP
  22. expected bool
  23. }{
  24. // Any of the IPs is nil or unspecified implies correct
  25. {nil, nil, true},
  26. {net.IPv4zero, net.IPv4zero, true},
  27. {nil, net.IPv4zero, true},
  28. {net.IPv4zero, nil, true},
  29. {a, nil, true},
  30. {b, nil, true},
  31. {a, net.IPv4zero, true},
  32. {b, net.IPv4zero, true},
  33. {nil, a, true},
  34. {nil, b, true},
  35. {net.IPv4zero, a, true},
  36. {net.IPv4zero, b, true},
  37. // IPs are the same implies correct
  38. {a, a, true},
  39. {b, b, true},
  40. // IPs are specified and different, implies incorrect
  41. {a, b, false},
  42. {b, a, false},
  43. }
  44. for _, test := range tests {
  45. m := Mapping{
  46. address: Address{
  47. IP: test.mappingLocalIP,
  48. },
  49. }
  50. result := m.validGateway(test.gatewayLocalIP)
  51. if result != test.expected {
  52. t.Errorf("Incorrect: local %s gateway %s result %t expected %t", test.mappingLocalIP, test.gatewayLocalIP, result, test.expected)
  53. }
  54. }
  55. }
  56. func TestMappingClearAddresses(t *testing.T) {
  57. tmpFile, err := ioutil.TempFile("", "syncthing-testConfig-")
  58. if err != nil {
  59. t.Fatal(err)
  60. }
  61. w := config.Wrap(tmpFile.Name(), config.Configuration{}, protocol.LocalDeviceID, events.NoopLogger)
  62. defer os.RemoveAll(tmpFile.Name())
  63. tmpFile.Close()
  64. natSvc := NewService(protocol.EmptyDeviceID, w)
  65. // Mock a mapped port; avoids the need to actually map a port
  66. ip := net.ParseIP("192.168.0.1")
  67. m := natSvc.NewMapping(TCP, ip, 1024)
  68. m.extAddresses["test"] = Address{
  69. IP: ip,
  70. Port: 1024,
  71. }
  72. // Now try and remove the mapped port; prior to #4829 this deadlocked
  73. natSvc.RemoveMapping(m)
  74. }