wireguard.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. type wgLink struct {
  24. a netlink.LinkAttrs
  25. t string
  26. }
  27. func (w wgLink) Attrs() *netlink.LinkAttrs {
  28. return &w.a
  29. }
  30. func (w wgLink) Type() string {
  31. return w.t
  32. }
  33. // New returns a WireGuard interface with the given name.
  34. // If the interface exists, its index is returned.
  35. // Otherwise, a new interface is created.
  36. // The function also returns a boolean to indicate if the interface was created.
  37. func New(name string, mtu uint) (int, bool, error) {
  38. link, err := netlink.LinkByName(name)
  39. if err == nil {
  40. return link.Attrs().Index, false, nil
  41. }
  42. if _, ok := err.(netlink.LinkNotFoundError); !ok {
  43. return 0, false, fmt.Errorf("failed to get links: %v", err)
  44. }
  45. wl := wgLink{a: netlink.NewLinkAttrs(), t: "wireguard"}
  46. wl.a.Name = name
  47. wl.a.MTU = int(mtu)
  48. if err := netlink.LinkAdd(wl); err != nil {
  49. return 0, false, fmt.Errorf("failed to create interface %s: %v", name, err)
  50. }
  51. link, err = netlink.LinkByName(name)
  52. if err != nil {
  53. return 0, false, fmt.Errorf("failed to get interface index: %v", err)
  54. }
  55. return link.Attrs().Index, true, nil
  56. }