interface_darwin.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. //go:build darwin
  2. // +build darwin
  3. /*
  4. Copyright © 2021-2022 Ettore Di Giacinto <[email protected]>
  5. Licensed under the Apache License, Version 2.0 (the "License");
  6. you may not use this file except in compliance with the License.
  7. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  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. */
  15. package vpn
  16. import (
  17. "net"
  18. "os/exec"
  19. "strconv"
  20. "github.com/mudler/water"
  21. )
  22. func createInterface(c *Config) (*water.Interface, error) {
  23. config := water.Config{
  24. DeviceType: water.TUN,
  25. }
  26. config.Name = c.InterfaceName
  27. return water.New(config)
  28. }
  29. func prepareInterface(c *Config) error {
  30. iface, err := net.InterfaceByName(c.InterfaceName)
  31. if err != nil {
  32. return err
  33. }
  34. ip, ipNet, err := net.ParseCIDR(c.InterfaceAddress)
  35. if err != nil {
  36. return err
  37. }
  38. // Set the MTU using the `ifconfig` command, since the `net` package does not provide a way to set the MTU.
  39. mtu := strconv.Itoa(c.InterfaceMTU)
  40. cmd := exec.Command("ifconfig", iface.Name, "mtu", mtu)
  41. err = cmd.Run()
  42. if err != nil {
  43. return err
  44. }
  45. // Add the address to the interface. This is not directly possible with the `net` package,
  46. // so we use the `ifconfig` command.
  47. if ip.To4() == nil {
  48. // IPV6
  49. cmd = exec.Command("ifconfig", iface.Name, "inet6", ip.String())
  50. } else {
  51. // IPv4
  52. cmd = exec.Command("ifconfig", iface.Name, "inet", ip.String(), ip.String())
  53. }
  54. err = cmd.Run()
  55. if err != nil {
  56. return err
  57. }
  58. // Bring up the interface. This is not directly possible with the `net` package,
  59. // so we use the `ifconfig` command.
  60. cmd = exec.Command("ifconfig", iface.Name, "up")
  61. err = cmd.Run()
  62. if err != nil {
  63. return err
  64. }
  65. // Add route
  66. cmd = exec.Command("route", "-n", "add", "-net", ipNet.String(), ip.String())
  67. err = cmd.Run()
  68. if err != nil {
  69. return err
  70. }
  71. return nil
  72. }