tun_ios.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. //go:build ios && !e2e_testing
  2. // +build ios,!e2e_testing
  3. package overlay
  4. import (
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net"
  9. "os"
  10. "runtime"
  11. "sync"
  12. "syscall"
  13. "github.com/sirupsen/logrus"
  14. "github.com/slackhq/nebula/iputil"
  15. )
  16. type tun struct {
  17. io.ReadWriteCloser
  18. cidr *net.IPNet
  19. }
  20. func newTun(_ *logrus.Logger, _ string, _ *net.IPNet, _ int, _ []Route, _ int, _ bool) (*tun, error) {
  21. return nil, fmt.Errorf("newTun not supported in iOS")
  22. }
  23. func newTunFromFd(_ *logrus.Logger, deviceFd int, cidr *net.IPNet, _ int, routes []Route, _ int) (*tun, error) {
  24. if len(routes) > 0 {
  25. return nil, fmt.Errorf("routes are not supported in %s", runtime.GOOS)
  26. }
  27. file := os.NewFile(uintptr(deviceFd), "/dev/tun")
  28. return &tun{
  29. cidr: cidr,
  30. ReadWriteCloser: &tunReadCloser{f: file},
  31. }, nil
  32. }
  33. func (t *tun) Activate() error {
  34. return nil
  35. }
  36. func (t *tun) RouteFor(iputil.VpnIp) iputil.VpnIp {
  37. return 0
  38. }
  39. // The following is hoisted up from water, we do this so we can inject our own fd on iOS
  40. type tunReadCloser struct {
  41. f io.ReadWriteCloser
  42. rMu sync.Mutex
  43. rBuf []byte
  44. wMu sync.Mutex
  45. wBuf []byte
  46. }
  47. func (tr *tunReadCloser) Read(to []byte) (int, error) {
  48. tr.rMu.Lock()
  49. defer tr.rMu.Unlock()
  50. if cap(tr.rBuf) < len(to)+4 {
  51. tr.rBuf = make([]byte, len(to)+4)
  52. }
  53. tr.rBuf = tr.rBuf[:len(to)+4]
  54. n, err := tr.f.Read(tr.rBuf)
  55. copy(to, tr.rBuf[4:])
  56. return n - 4, err
  57. }
  58. func (tr *tunReadCloser) Write(from []byte) (int, error) {
  59. if len(from) == 0 {
  60. return 0, syscall.EIO
  61. }
  62. tr.wMu.Lock()
  63. defer tr.wMu.Unlock()
  64. if cap(tr.wBuf) < len(from)+4 {
  65. tr.wBuf = make([]byte, len(from)+4)
  66. }
  67. tr.wBuf = tr.wBuf[:len(from)+4]
  68. // Determine the IP Family for the NULL L2 Header
  69. ipVer := from[0] >> 4
  70. if ipVer == 4 {
  71. tr.wBuf[3] = syscall.AF_INET
  72. } else if ipVer == 6 {
  73. tr.wBuf[3] = syscall.AF_INET6
  74. } else {
  75. return 0, errors.New("unable to determine IP version from packet")
  76. }
  77. copy(tr.wBuf[4:], from)
  78. n, err := tr.f.Write(tr.wBuf)
  79. return n - 4, err
  80. }
  81. func (tr *tunReadCloser) Close() error {
  82. return tr.f.Close()
  83. }
  84. func (t *tun) Cidr() *net.IPNet {
  85. return t.cidr
  86. }
  87. func (t *tun) Name() string {
  88. return "iOS"
  89. }
  90. func (t *tun) NewMultiQueueReader() (io.ReadWriteCloser, error) {
  91. return nil, fmt.Errorf("TODO: multiqueue not implemented for ios")
  92. }