Files
gluetun/internal/openvpn/loop.go

296 lines
7.7 KiB
Go
Raw Normal View History

package openvpn
import (
"context"
"net"
"net/http"
"os"
"strings"
"time"
2021-02-06 11:05:50 -05:00
"github.com/qdm12/gluetun/internal/configuration"
2020-07-26 12:07:06 +00:00
"github.com/qdm12/gluetun/internal/constants"
"github.com/qdm12/gluetun/internal/firewall"
"github.com/qdm12/gluetun/internal/loopstate"
2020-07-26 12:07:06 +00:00
"github.com/qdm12/gluetun/internal/models"
"github.com/qdm12/gluetun/internal/openvpn/state"
2020-07-26 12:07:06 +00:00
"github.com/qdm12/gluetun/internal/provider"
"github.com/qdm12/gluetun/internal/routing"
"github.com/qdm12/golibs/logging"
)
type Looper interface {
Run(ctx context.Context, done chan<- struct{})
GetStatus() (status models.LoopStatus)
2021-07-16 21:20:34 +00:00
ApplyStatus(ctx context.Context, status models.LoopStatus) (
outcome string, err error)
2021-02-06 11:05:50 -05:00
GetSettings() (settings configuration.OpenVPN)
SetSettings(ctx context.Context, settings configuration.OpenVPN) (
outcome string)
GetServers() (servers models.AllServers)
SetServers(servers models.AllServers)
GetPortForwarded() (port uint16)
PortForward(vpnGatewayIP net.IP)
}
type looper struct {
statusManager loopstate.Manager
state state.Manager
// Fixed parameters
username string
puid int
pgid int
targetConfPath string
// Configurators
conf Configurator
fw firewall.Configurator
routing routing.Routing
// Other objects
logger, pfLogger logging.Logger
client *http.Client
2021-01-26 04:17:22 +00:00
tunnelReady chan<- struct{}
2021-07-16 21:20:34 +00:00
// Internal channels and values
stop <-chan struct{}
stopped chan<- struct{}
start <-chan struct{}
running chan<- models.LoopStatus
portForwardSignals chan net.IP
2021-07-16 21:20:34 +00:00
userTrigger bool
// Internal constant values
backoffTime time.Duration
}
2021-05-04 15:36:12 -04:00
const (
defaultBackoffTime = 15 * time.Second
2021-05-04 15:36:12 -04:00
)
2021-02-06 11:05:50 -05:00
func NewLooper(settings configuration.OpenVPN,
2020-12-29 16:44:35 +00:00
username string, puid, pgid int, allServers models.AllServers,
conf Configurator, fw firewall.Configurator, routing routing.Routing,
logger logging.ParentLogger, client *http.Client,
tunnelReady chan<- struct{}) Looper {
2021-07-16 21:20:34 +00:00
start := make(chan struct{})
running := make(chan models.LoopStatus)
stop := make(chan struct{})
stopped := make(chan struct{})
statusManager := loopstate.New(constants.Stopped, start, running, stop, stopped)
state := state.New(statusManager, settings, allServers)
2021-07-16 21:20:34 +00:00
return &looper{
statusManager: statusManager,
2021-07-16 21:20:34 +00:00
state: state,
2020-12-27 00:36:39 +00:00
username: username,
2020-12-29 16:44:35 +00:00
puid: puid,
pgid: pgid,
targetConfPath: constants.OpenVPNConf,
conf: conf,
fw: fw,
routing: routing,
logger: logger.NewChild(logging.Settings{Prefix: "openvpn: "}),
pfLogger: logger.NewChild(logging.Settings{Prefix: "port forwarding: "}),
client: client,
2021-01-26 04:17:22 +00:00
tunnelReady: tunnelReady,
2021-07-16 21:20:34 +00:00
start: start,
running: running,
stop: stop,
stopped: stopped,
portForwardSignals: make(chan net.IP),
2021-07-16 21:20:34 +00:00
userTrigger: true,
backoffTime: defaultBackoffTime,
}
}
func (l *looper) PortForward(vpnGateway net.IP) { l.portForwardSignals <- vpnGateway }
2021-07-16 21:20:34 +00:00
func (l *looper) signalOrSetStatus(status models.LoopStatus) {
if l.userTrigger {
l.userTrigger = false
select {
case l.running <- status:
default: // receiver calling ApplyStatus droppped out
}
} else {
l.statusManager.SetStatus(status)
}
}
func (l *looper) Run(ctx context.Context, done chan<- struct{}) {
defer close(done)
2021-07-16 21:20:34 +00:00
select {
case <-l.start:
case <-ctx.Done():
return
}
for ctx.Err() == nil {
2021-07-16 21:20:34 +00:00
settings, allServers := l.state.GetSettingsAndServers()
providerConf := provider.New(settings.Provider.Name, allServers, time.Now)
var connection models.OpenVPNConnection
var lines []string
var err error
2021-07-16 21:20:34 +00:00
if settings.Config == "" {
connection, err = providerConf.GetOpenVPNConnection(settings.Provider.ServerSelection)
if err != nil {
2021-07-16 21:20:34 +00:00
l.signalOrSetStatus(constants.Crashed)
l.logAndWait(ctx, err)
continue
}
lines = providerConf.BuildConf(connection, l.username, settings)
} else {
lines, connection, err = l.processCustomConfig(settings)
if err != nil {
2021-07-16 21:20:34 +00:00
l.signalOrSetStatus(constants.Crashed)
l.logAndWait(ctx, err)
continue
}
2020-07-23 02:15:37 +00:00
}
if err := l.writeOpenvpnConf(lines); err != nil {
2021-07-16 21:20:34 +00:00
l.signalOrSetStatus(constants.Crashed)
l.logAndWait(ctx, err)
continue
2020-07-23 02:15:37 +00:00
}
if settings.User != "" {
2021-07-16 21:20:34 +00:00
err := l.conf.WriteAuthFile(
settings.User, settings.Password, l.puid, l.pgid)
if err != nil {
l.signalOrSetStatus(constants.Crashed)
l.logAndWait(ctx, err)
continue
}
2020-07-23 02:15:37 +00:00
}
if err := l.fw.SetVPNConnection(ctx, connection); err != nil {
2021-07-16 21:20:34 +00:00
l.signalOrSetStatus(constants.Crashed)
l.logAndWait(ctx, err)
continue
}
openvpnCtx, openvpnCancel := context.WithCancel(context.Background())
stdoutLines, stderrLines, waitError, err := l.conf.Start(
openvpnCtx, settings.Version, settings.Flags)
if err != nil {
openvpnCancel()
2021-07-16 21:20:34 +00:00
l.signalOrSetStatus(constants.Crashed)
l.logAndWait(ctx, err)
continue
}
lineCollectionDone := make(chan struct{})
go l.collectLines(stdoutLines, stderrLines, lineCollectionDone)
closeStreams := func() {
close(stdoutLines)
close(stderrLines)
<-lineCollectionDone
}
2021-01-26 04:17:22 +00:00
2020-09-12 19:17:19 +00:00
// Needs the stream line from main.go to know when the tunnel is up
portForwardDone := make(chan struct{})
go func(ctx context.Context) {
defer close(portForwardDone)
select {
// TODO have a way to disable pf with a context
case <-ctx.Done():
return
case gateway := <-l.portForwardSignals:
l.portForward(ctx, providerConf, l.client, gateway)
}
}(openvpnCtx)
2021-07-16 21:20:34 +00:00
l.backoffTime = defaultBackoffTime
l.signalOrSetStatus(constants.Running)
stayHere := true
for stayHere {
select {
case <-ctx.Done():
openvpnCancel()
<-waitError
close(waitError)
closeStreams()
<-portForwardDone
return
case <-l.stop:
2021-07-16 21:20:34 +00:00
l.userTrigger = true
l.logger.Info("stopping")
openvpnCancel()
<-waitError
// do not close waitError or the waitError
// select case will trigger
closeStreams()
<-portForwardDone
l.stopped <- struct{}{}
case <-l.start:
2021-07-16 21:20:34 +00:00
l.userTrigger = true
l.logger.Info("starting")
stayHere = false
case err := <-waitError: // unexpected error
close(waitError)
closeStreams()
2021-07-16 21:20:34 +00:00
l.statusManager.Lock() // prevent SetStatus from running in parallel
2021-07-16 21:20:34 +00:00
openvpnCancel()
l.statusManager.SetStatus(constants.Crashed)
<-portForwardDone
l.logAndWait(ctx, err)
stayHere = false
2021-07-16 21:20:34 +00:00
l.statusManager.Unlock()
}
}
2021-07-16 21:20:34 +00:00
openvpnCancel()
}
}
func (l *looper) logAndWait(ctx context.Context, err error) {
if err != nil {
l.logger.Error(err.Error())
}
2021-07-16 21:20:34 +00:00
l.logger.Info("retrying in " + l.backoffTime.String())
timer := time.NewTimer(l.backoffTime)
l.backoffTime *= 2
2020-10-20 02:45:28 +00:00
select {
case <-timer.C:
case <-ctx.Done():
if !timer.Stop() {
<-timer.C
}
}
}
// portForward is a blocking operation which may or may not be infinite.
2020-10-20 02:45:28 +00:00
// You should therefore always call it in a goroutine.
func (l *looper) portForward(ctx context.Context,
providerConf provider.Provider, client *http.Client, gateway net.IP) {
settings := l.state.GetSettings()
2020-07-16 01:26:37 +00:00
if !settings.Provider.PortForwarding.Enabled {
return
}
2021-02-06 18:31:14 +00:00
syncState := func(port uint16) (pfFilepath string) {
l.state.SetPortForwarded(port)
settings := l.state.GetSettings()
return settings.Provider.PortForwarding.Filepath
}
providerConf.PortForward(ctx, client, l.pfLogger,
gateway, l.fw, syncState)
}
func (l *looper) writeOpenvpnConf(lines []string) error {
file, err := os.OpenFile(l.targetConfPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
if err != nil {
return err
}
_, err = file.WriteString(strings.Join(lines, "\n"))
if err != nil {
return err
}
2021-06-20 16:12:39 +00:00
return file.Close()
}