You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
1.3 KiB
Go

5 years ago
package service
import (
"log"
"os"
"os/exec"
)
type OpenVPN struct {
Config *ZeroooConfig
Manager *Manager
shouldStop bool
cmd *exec.Cmd
}
func NewOpenVPN(manager *Manager) *OpenVPN {
return &OpenVPN{
Config: &manager.Config.Zerooo,
Manager: manager,
}
}
func (it *OpenVPN) Stop() {
it.shouldStop = true
if it.cmd != nil && it.cmd.Process != nil {
it.cmd.Process.Kill()
}
}
func (it *OpenVPN) GetConfigLocation() string {
return it.Config.Location + "/server.conf"
}
func (it *OpenVPN) Restart() {
if it.cmd != nil && it.cmd.Process != nil {
it.cmd.Process.Kill()
return
}
it.Start()
}
func (it *OpenVPN) Start() {
if !it.Manager.IsOpenVPNReady() {
log.Printf("OpenVPN not ready yet.")
return
}
log.Printf("Starting OpenVPN")
it.cmd = exec.Command("openvpn", "--config", it.GetConfigLocation())
it.cmd.Start()
go func() {
it.cmd.Wait()
if it.shouldStop {
log.Printf("OpenVPN has stopped (exit code: %d)", it.cmd.ProcessState.ExitCode())
return
}
log.Printf("OpenVPN has stopped (exit code: %d), restarting", it.cmd.ProcessState.ExitCode())
it.Start()
}()
}
func (it *OpenVPN) UpdateConfig(s string) error {
f, err := os.OpenFile(it.GetConfigLocation(), os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
return err
}
defer f.Close()
_, err = f.WriteString(s)
return err
}