Maint: tun package to handle tun device operations

- Moved from openvpn package to tun package
- TUN check verifies Rdev value
- TUN create
- Inject as interface to main function
- Add integration test
- Clearer log message for end users if tun device does not exist
- Remove unix package (unneeded for tests)
- Remove tun file opening at the end of tun file creation
- Do not mock unix.Mkdev (no OS operation)
- Remove Tun operations from OpenVPN configurator
This commit is contained in:
Quentin McGaw (desktop)
2021-08-18 15:31:08 +00:00
parent 384a4bae3a
commit 6a545aa088
10 changed files with 186 additions and 172 deletions

View File

@@ -4,7 +4,6 @@ package openvpn
import (
"github.com/qdm12/gluetun/internal/constants"
"github.com/qdm12/gluetun/internal/unix"
"github.com/qdm12/golibs/command"
"github.com/qdm12/golibs/logging"
)
@@ -12,7 +11,6 @@ import (
type Configurator interface {
VersionGetter
AuthWriter
TUNCheckCreater
Starter
}
@@ -24,18 +22,14 @@ type StarterAuthWriter interface {
type configurator struct {
logger logging.Logger
cmder command.RunStarter
unix unix.Unix
authFilePath string
tunDevPath string
}
func NewConfigurator(logger logging.Logger, unix unix.Unix,
func NewConfigurator(logger logging.Logger,
cmder command.RunStarter) Configurator {
return &configurator{
logger: logger,
cmder: cmder,
unix: unix,
authFilePath: constants.OpenVPNAuthConf,
tunDevPath: constants.TunnelDevice,
}
}

View File

@@ -1,61 +0,0 @@
package openvpn
import (
"fmt"
"os"
"path/filepath"
"github.com/qdm12/gluetun/internal/unix"
)
type TUNCheckCreater interface {
TUNChecker
TUNCreater
}
type TUNChecker interface {
CheckTUN() error
}
// CheckTUN checks the tunnel device is present and accessible.
func (c *configurator) CheckTUN() error {
c.logger.Info("checking for device " + c.tunDevPath)
f, err := os.OpenFile(c.tunDevPath, os.O_RDWR, 0)
if err != nil {
return fmt.Errorf("TUN device is not available: %w", err)
}
if err := f.Close(); err != nil {
c.logger.Warn("Could not close TUN device file: " + err.Error())
}
return nil
}
type TUNCreater interface {
CreateTUN() error
}
func (c *configurator) CreateTUN() error {
c.logger.Info("creating " + c.tunDevPath)
parentDir := filepath.Dir(c.tunDevPath)
if err := os.MkdirAll(parentDir, 0751); err != nil { //nolint:gomnd
return err
}
const (
major = 10
minor = 200
)
dev := c.unix.Mkdev(major, minor)
if err := c.unix.Mknod(c.tunDevPath, unix.S_IFCHR, int(dev)); err != nil {
return err
}
const readWriteAllPerms os.FileMode = 0666
file, err := os.OpenFile(c.tunDevPath, os.O_WRONLY, readWriteAllPerms)
if err != nil {
return err
}
return file.Close()
}