ipip.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright 2019 the Kilo 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. package encapsulation
  15. import (
  16. "fmt"
  17. "net"
  18. "github.com/squat/kilo/pkg/iproute"
  19. "github.com/squat/kilo/pkg/iptables"
  20. )
  21. type ipip struct {
  22. iface int
  23. strategy Strategy
  24. }
  25. // NewIPIP returns an encapsulator that uses IPIP.
  26. func NewIPIP(strategy Strategy) Encapsulator {
  27. return &ipip{strategy: strategy}
  28. }
  29. // CleanUp will remove any created IPIP devices.
  30. func (i *ipip) CleanUp() error {
  31. if err := iproute.DeleteAddresses(i.iface); err != nil {
  32. return nil
  33. }
  34. return iproute.RemoveInterface(i.iface)
  35. }
  36. // Gw returns the correct gateway IP associated with the given node.
  37. func (i *ipip) Gw(_, internal net.IP, _ *net.IPNet) net.IP {
  38. return internal
  39. }
  40. // Index returns the index of the IPIP interface.
  41. func (i *ipip) Index() int {
  42. return i.iface
  43. }
  44. // Init initializes the IPIP interface.
  45. func (i *ipip) Init(base int) error {
  46. iface, err := iproute.NewIPIP(base)
  47. if err != nil {
  48. return fmt.Errorf("failed to create tunnel interface: %v", err)
  49. }
  50. if err := iproute.Set(iface, true); err != nil {
  51. return fmt.Errorf("failed to set tunnel interface up: %v", err)
  52. }
  53. i.iface = iface
  54. return nil
  55. }
  56. // Rules returns a set of iptables rules that are necessary
  57. // when traffic between nodes must be encapsulated.
  58. func (i *ipip) Rules(nodes []*net.IPNet) []iptables.Rule {
  59. return iptables.IPIPRules(nodes)
  60. }
  61. // Set sets the IP address of the IPIP interface.
  62. func (i *ipip) Set(cidr *net.IPNet) error {
  63. return iproute.SetAddress(i.iface, cidr)
  64. }
  65. // Strategy returns the configured strategy for encapsulation.
  66. func (i *ipip) Strategy() Strategy {
  67. return i.strategy
  68. }