2021-08-18 15:31:08 +00:00
|
|
|
package tun
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
|
|
|
|
"os"
|
|
|
|
|
"path/filepath"
|
|
|
|
|
|
|
|
|
|
"golang.org/x/sys/unix"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// Create creates a TUN device at the path specified.
|
|
|
|
|
func (t *Tun) Create(path string) error {
|
|
|
|
|
parentDir := filepath.Dir(path)
|
2022-06-11 02:41:16 +00:00
|
|
|
if err := os.MkdirAll(parentDir, 0751); err != nil {
|
2021-08-18 15:31:08 +00:00
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const (
|
|
|
|
|
major = 10
|
|
|
|
|
minor = 200
|
|
|
|
|
)
|
|
|
|
|
dev := unix.Mkdev(major, minor)
|
|
|
|
|
err := t.mknod(path, unix.S_IFCHR, int(dev))
|
|
|
|
|
if err != nil {
|
2022-02-20 02:58:16 +00:00
|
|
|
return fmt.Errorf("cannot create TUN device file node: %w", err)
|
2021-08-18 15:31:08 +00:00
|
|
|
}
|
|
|
|
|
|
2021-09-12 13:32:50 +00:00
|
|
|
fd, err := unix.Open(path, 0, 0)
|
|
|
|
|
if err != nil {
|
2022-02-20 02:58:16 +00:00
|
|
|
return fmt.Errorf("cannot Unix Open TUN device file: %w", err)
|
2021-09-12 13:32:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const nonBlocking = true
|
|
|
|
|
err = unix.SetNonblock(fd, nonBlocking)
|
|
|
|
|
if err != nil {
|
2022-02-20 02:58:16 +00:00
|
|
|
return fmt.Errorf("cannot set non block to TUN device file descriptor: %w", err)
|
2021-09-12 13:32:50 +00:00
|
|
|
}
|
|
|
|
|
|
2021-08-18 15:31:08 +00:00
|
|
|
return nil
|
|
|
|
|
}
|