ipip.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 iproute
  15. import (
  16. "bytes"
  17. "fmt"
  18. "os/exec"
  19. "strings"
  20. "github.com/vishvananda/netlink"
  21. )
  22. const (
  23. ipipHeaderSize = 20
  24. DefaultTunnelName = "tunl0"
  25. )
  26. // NewIPIP creates an IPIP interface named tunl0 using the base interface
  27. // to derive the tunnel's MTU.
  28. func NewIPIP(baseIndex int) (int, error) {
  29. return NewIPIPWithName(baseIndex, DefaultTunnelName)
  30. }
  31. // NewIPIPWithName creates a named IPIP interface using the base interface
  32. // to derive the tunnel's MTU.
  33. func NewIPIPWithName(baseIndex int, name string) (int, error) {
  34. link, err := netlink.LinkByName(name)
  35. if err != nil {
  36. // If we failed to find the tunnel, then it probably simply does not exist.
  37. cmd := exec.Command("ip", "tunnel", "add", name, "mode", "ipip")
  38. var stderr bytes.Buffer
  39. cmd.Stderr = &stderr
  40. // Sometimes creating a tunnel returns the error "File exists,"
  41. // in which case the interface exists and we can ignore the error.
  42. if err := cmd.Run(); err != nil && !strings.Contains(stderr.String(), "File exists") {
  43. return 0, fmt.Errorf("failed to create IPIP tunnel: %s", stderr.String())
  44. }
  45. link, err = netlink.LinkByName(name)
  46. if err != nil {
  47. return 0, fmt.Errorf("failed to get tunnel device: %v", err)
  48. }
  49. }
  50. base, err := netlink.LinkByIndex(baseIndex)
  51. if err != nil {
  52. return 0, fmt.Errorf("failed to get base device: %v", err)
  53. }
  54. mtu := base.Attrs().MTU - ipipHeaderSize
  55. if err = netlink.LinkSetMTU(link, mtu); err != nil {
  56. return 0, fmt.Errorf("failed to set tunnel MTU: %v", err)
  57. }
  58. return link.Attrs().Index, nil
  59. }