wireguard.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. //go:build linux
  15. // +build linux
  16. package wireguard
  17. import (
  18. "fmt"
  19. "github.com/vishvananda/netlink"
  20. )
  21. // DefaultMTU is the the default MTU used by WireGuard.
  22. const DefaultMTU = 1420
  23. // WireGuardOverhead is the overhead in bytes added by WireGuard encapsulation.
  24. // IPv4 header (20) + UDP header (8) + WireGuard header (32) + MAC (16) + padding (4) = 80 bytes.
  25. const WireGuardOverhead = 80
  26. // SetMTU sets the MTU on the interface with the given index.
  27. // If the current MTU already matches, no change is made.
  28. func SetMTU(index int, mtu uint) error {
  29. link, err := netlink.LinkByIndex(index)
  30. if err != nil {
  31. return fmt.Errorf("failed to get link: %v", err)
  32. }
  33. if link.Attrs().MTU == int(mtu) {
  34. return nil
  35. }
  36. return netlink.LinkSetMTU(link, int(mtu))
  37. }
  38. type wgLink struct {
  39. a netlink.LinkAttrs
  40. t string
  41. }
  42. func (w wgLink) Attrs() *netlink.LinkAttrs {
  43. return &w.a
  44. }
  45. func (w wgLink) Type() string {
  46. return w.t
  47. }
  48. // New returns a WireGuard interface with the given name.
  49. // If the interface exists, its index is returned.
  50. // Otherwise, a new interface is created.
  51. // The function also returns a boolean to indicate if the interface was created.
  52. func New(name string, mtu uint) (int, bool, error) {
  53. link, err := netlink.LinkByName(name)
  54. if err == nil {
  55. return link.Attrs().Index, false, nil
  56. }
  57. if _, ok := err.(netlink.LinkNotFoundError); !ok {
  58. return 0, false, fmt.Errorf("failed to get links: %v", err)
  59. }
  60. wl := wgLink{a: netlink.NewLinkAttrs(), t: "wireguard"}
  61. wl.a.Name = name
  62. wl.a.MTU = int(mtu)
  63. if err := netlink.LinkAdd(wl); err != nil {
  64. return 0, false, fmt.Errorf("failed to create interface %s: %v", name, err)
  65. }
  66. link, err = netlink.LinkByName(name)
  67. if err != nil {
  68. return 0, false, fmt.Errorf("failed to get interface index: %v", err)
  69. }
  70. return link.Attrs().Index, true, nil
  71. }