interface.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. //go:build !windows
  2. // +build !windows
  3. // Copyright © 2021 Ettore Di Giacinto <[email protected]>
  4. //
  5. // This program is free software; you can redistribute it and/or modify
  6. // it under the terms of the GNU General Public License as published by
  7. // the Free Software Foundation; either version 2 of the License, or
  8. // (at your option) any later version.
  9. //
  10. // This program is distributed in the hope that it will be useful,
  11. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. // GNU General Public License for more details.
  14. //
  15. // You should have received a copy of the GNU General Public License along
  16. // with this program; if not, see <http://www.gnu.org/licenses/>.
  17. package vpn
  18. import (
  19. "fmt"
  20. "io"
  21. "github.com/vishvananda/netlink"
  22. "golang.zx2c4.com/wireguard/tun"
  23. )
  24. type tunWriter struct {
  25. tun.Device
  26. offset int
  27. }
  28. func newtunWriter(t tun.Device, offset int) io.WriteCloser {
  29. return tunWriter{Device: t, offset: offset}
  30. }
  31. func (t tunWriter) Write(b []byte) (int, error) {
  32. return t.Device.Write(b, t.offset)
  33. }
  34. func createInterface(c *Config) (tun.Device, error) {
  35. ifname := c.InterfaceName
  36. if ifname == "auto" {
  37. ifname = "\000"
  38. }
  39. return tun.CreateTUN(ifname, c.InterfaceMTU)
  40. }
  41. func prepareInterface(c *Config) error {
  42. fmt.Println("Preparing interface")
  43. link, err := netlink.LinkByName(c.InterfaceName)
  44. if err != nil {
  45. fmt.Println("link", err)
  46. return err
  47. }
  48. addr, err := netlink.ParseAddr(c.InterfaceAddress)
  49. if err != nil {
  50. fmt.Println("parse addr", err)
  51. return err
  52. }
  53. err = netlink.LinkSetMTU(link, c.InterfaceMTU)
  54. if err != nil {
  55. return err
  56. }
  57. fmt.Println(addr)
  58. err = netlink.AddrAdd(link, addr)
  59. if err != nil {
  60. fmt.Println("add addr", err)
  61. return err
  62. }
  63. err = netlink.LinkSetUp(link)
  64. if err != nil {
  65. return err
  66. }
  67. fmt.Println("done Preparing interface")
  68. return nil
  69. }