From 998b5cb54ad23be1f6df0ee8abd08af5614f38db Mon Sep 17 00:00:00 2001
From: Ruben Pollan <meskio@sindominio.net>
Date: Thu, 24 Sep 2020 12:24:48 +0200
Subject: [PATCH] [feat] send cmd flags to the go backend

Also disable autostart if manual quit, remove custom printer that was
used for i18n and disable previous autostart if -disable-autostart

We didn't disable autostart after the migration to qt.

- Resolves: #355 #289
---
 go.mod                   |  1 -
 go.sum                   |  2 --
 gui/backend.go           |  8 +++++++-
 gui/main.cpp             | 38 ++++++++++++++++++++++++++++++++++++-
 pkg/backend/api.go       | 12 ++++++++----
 pkg/backend/init.go      | 36 ++++++++++++++++++++++++++++++++++-
 pkg/backend/status.go    |  1 +
 pkg/bitmask/autostart.go |  8 ++++----
 pkg/bitmask/init.go      | 41 ++++++++--------------------------------
 pkg/config/gui.go        |  7 +------
 10 files changed, 101 insertions(+), 53 deletions(-)

diff --git a/go.mod b/go.mod
index f608eced..80f20983 100644
--- a/go.mod
+++ b/go.mod
@@ -11,7 +11,6 @@ require (
 	github.com/agl/ed25519 v0.0.0-20170116200512-5312a6153412 // indirect
 	github.com/apparentlymart/go-openvpn-mgmt v0.0.0-20161009010951-9a305aecd7f2
 	github.com/dchest/siphash v1.2.1 // indirect
-	github.com/jmshal/go-locale v0.0.0-20190124211249-eb00fb25cc61
 	github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0 // indirect
 	github.com/keybase/go-ps v0.0.0-20190827175125-91aafc93ba19
 	github.com/rakyll/statik v0.1.7
diff --git a/go.sum b/go.sum
index 533e8e2a..a7e7c802 100644
--- a/go.sum
+++ b/go.sum
@@ -16,8 +16,6 @@ github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8
 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
 github.com/dchest/siphash v1.2.1 h1:4cLinnzVJDKxTCl9B01807Yiy+W7ZzVHj/KIroQRvT4=
 github.com/dchest/siphash v1.2.1/go.mod h1:q+IRvb2gOSrUnYoPqHiyHXS0FOBBOdl6tONBlVnOnt4=
-github.com/jmshal/go-locale v0.0.0-20190124211249-eb00fb25cc61 h1:9vsXCXRCUb82jJKv4O+R8Hyo4oPJsOjVwT0pWvHgeyc=
-github.com/jmshal/go-locale v0.0.0-20190124211249-eb00fb25cc61/go.mod h1:+Ny9b1U6p4zX0L9w+k3hSkz3puupLFP14Mion+rGNF8=
 github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0 h1:iQTw/8FWTuc7uiaSepXwyf3o52HaUYcV+Tu66S3F5GA=
 github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0/go.mod h1:1NbS8ALrpOvjt0rHPNLyCIeMtbizbir8U//inJ+zuB8=
 github.com/keybase/go-ps v0.0.0-20190827175125-91aafc93ba19 h1:WjT3fLi9n8YWh/Ih8Q1LHAPsTqGddPcHqscN+PJ3i68=
diff --git a/gui/backend.go b/gui/backend.go
index 7632bb4d..92fbb974 100644
--- a/gui/backend.go
+++ b/gui/backend.go
@@ -53,9 +53,15 @@ func SubscribeToEvent(event string, f unsafe.Pointer) {
 }
 
 //export InitializeBitmaskContext
-func InitializeBitmaskContext(provider string, jsonPtr unsafe.Pointer, jsonLen C.int) {
+func InitializeBitmaskContext(provider string,
+	jsonPtr unsafe.Pointer, jsonLen C.int,
+	obfs4 bool, disableAutostart bool, startVPN string) {
+
 	json := C.GoBytes(jsonPtr, jsonLen)
 	opts := backend.InitOptsFromJSON(provider, string(json))
+	opts.Obfs4 = obfs4
+	opts.DisableAutostart = disableAutostart
+	opts.StartVPN = startVPN
 	backend.InitializeBitmaskContext(opts)
 }
 
diff --git a/gui/main.cpp b/gui/main.cpp
index 4ba9dd6f..42123ae3 100644
--- a/gui/main.cpp
+++ b/gui/main.cpp
@@ -76,15 +76,50 @@ int main(int argc, char **argv) {
                 "main",
                 "Install helpers (linux only, requires sudo)."),
         },
+        {
+            {"v", "version"},
+            QApplication::translate(
+                "main",
+		"Version of the bitmask-vpn."),
+        },
+        {
+            {"o", "obfs4"},
+            QApplication::translate(
+                "main",
+		"Use obfs4 to obfuscate the traffic is available in the provider."),
+        },
+        {
+            {"a", "disable-autostart"},
+            QApplication::translate(
+                "main",
+		"Disable the autostart for the next run."),
+        },
+        {
+            {"s", "start-vpn"},
+            QApplication::translate(
+                "main",
+		"Start the vpn in turned 'on' or 'off'."),
+        },
     });
     QCommandLineOption webPortOption("web-port", QApplication::translate("main", "Web api port (default: 8080)"), "port", "8080");
     parser.addOption(webPortOption);
+    QCommandLineOption startVPNOption("start-vpn", QApplication::translate("main", "Start the vpn in turned 'on' or 'off'."), "status", "");
+    parser.addOption(startVPNOption);
     parser.process(app);
 
     bool hideSystray    = parser.isSet("no-systray");
     bool installHelpers = parser.isSet("install-helpers");
     bool webAPI         = parser.isSet("web-api");
     QString webPort     = parser.value("web-port");
+    bool version        = parser.isSet("version");
+    bool obfs4          = parser.isSet("obfs4");
+    bool disAutostart   = parser.isSet("disable-autostart");
+    QString startVPN    = parser.value("start-vpn");
+
+    if (version) {
+        qDebug() << backend.getVersion();
+        exit(0);
+    }
 
     if (hideSystray) {
         qDebug() << "Not showing systray icon because --no-systray option is set.";
@@ -152,7 +187,8 @@ int main(int argc, char **argv) {
     /* let the Go side initialize its internal state */
     InitializeBitmaskContext(
             toGoStr(defaultProvider.toString()),
-            (char*)QProvidersJSON.toUtf8().data(), strlen(QProvidersJSON.toUtf8().data()));
+            (char*)QProvidersJSON.toUtf8().data(), strlen(QProvidersJSON.toUtf8().data()),
+	    obfs4, disAutostart, toGoStr(startVPN));
 
     /* if requested, enable web api for controlling the VPN */
     if (webAPI) {
diff --git a/pkg/backend/api.go b/pkg/backend/api.go
index 9706bdf9..a8d16a32 100644
--- a/pkg/backend/api.go
+++ b/pkg/backend/api.go
@@ -11,8 +11,8 @@ import (
 
 	"0xacab.org/leap/bitmask-vpn/pkg/bitmask"
 	"0xacab.org/leap/bitmask-vpn/pkg/config/version"
-	"0xacab.org/leap/bitmask-vpn/pkg/pid"
 	"0xacab.org/leap/bitmask-vpn/pkg/pickle"
+	"0xacab.org/leap/bitmask-vpn/pkg/pid"
 )
 
 func Login(username, password string) {
@@ -48,6 +48,7 @@ func SwitchOff() {
 }
 
 func Quit() {
+	ctx.autostart.Disable()
 	if ctx.Status != off {
 		go setStatus(stopping)
 		ctx.cfg.SetUserStoppedVPN(false)
@@ -74,8 +75,11 @@ type Providers struct {
 }
 
 type InitOpts struct {
-	ProviderOptions *bitmask.ProviderOpts
-	SkipLaunch      bool
+	ProviderOptions  *bitmask.ProviderOpts
+	SkipLaunch       bool
+	Obfs4            bool
+	DisableAutostart bool
+	StartVPN         string
 }
 
 func InitOptsFromJSON(provider, providersJSON string) *InitOpts {
@@ -88,7 +92,7 @@ func InitOptsFromJSON(provider, providersJSON string) *InitOpts {
 		panic("BUG: we do not support multi-provider yet")
 	}
 	providerOpts := &providers.Data[0]
-	return &InitOpts{providerOpts, false}
+	return &InitOpts{ProviderOptions: providerOpts}
 }
 
 func InitializeBitmaskContext(opts *InitOpts) {
diff --git a/pkg/backend/init.go b/pkg/backend/init.go
index c0d8f37b..842c91b2 100644
--- a/pkg/backend/init.go
+++ b/pkg/backend/init.go
@@ -52,6 +52,7 @@ func initializeBitmask(errCh chan string, opts *InitOpts) {
 	}
 	bitmask.InitializeLogger()
 	ctx.cfg = config.ParseConfig()
+	setConfigOpts(opts, ctx.cfg)
 
 	err := pid.AcquirePID()
 	if err != nil {
@@ -60,12 +61,13 @@ func initializeBitmask(errCh chan string, opts *InitOpts) {
 		return
 	}
 
-	b, err := bitmask.InitializeBitmask(opts.SkipLaunch)
+	b, err := bitmask.InitializeBitmask(ctx.cfg)
 	if err != nil {
 		log.Println("error: cannot initialize bitmask")
 		errCh <- err.Error()
 		return
 	}
+	ctx.autostart = initializeAutostart(ctx.cfg)
 
 	helpers, privilege, err := b.VPNCheck()
 
@@ -85,3 +87,35 @@ func initializeBitmask(errCh chan string, opts *InitOpts) {
 
 	ctx.bm = b
 }
+
+func setConfigOpts(opts *InitOpts, conf *config.Config) {
+	conf.SkipLaunch = opts.SkipLaunch
+	if opts.StartVPN != "" {
+		if opts.StartVPN != "on" && opts.StartVPN != "off" {
+			log.Println("-start-vpn should be 'on' or 'off'")
+		} else {
+			conf.StartVPN = opts.StartVPN == "on"
+		}
+	}
+	if opts.Obfs4 {
+		conf.Obfs4 = opts.Obfs4
+	}
+	if opts.DisableAutostart {
+		conf.DisableAustostart = opts.DisableAutostart
+	}
+}
+
+func initializeAutostart(conf *config.Config) bitmask.Autostart {
+	autostart := bitmask.NewAutostart(config.ApplicationName, "")
+	if conf.SkipLaunch || conf.DisableAustostart {
+		autostart.Disable()
+		autostart = &bitmask.DummyAutostart{}
+	}
+
+	err := autostart.Enable()
+	if err != nil {
+		log.Printf("Error enabling autostart: %v", err)
+	}
+	return autostart
+
+}
diff --git a/pkg/backend/status.go b/pkg/backend/status.go
index f06d26df..ffa79fc0 100644
--- a/pkg/backend/status.go
+++ b/pkg/backend/status.go
@@ -43,6 +43,7 @@ type connectionCtx struct {
 	Errors          string `json:"errors"`
 	Status          status `json:"status"`
 	bm              bitmask.Bitmask
+	autostart       bitmask.Autostart
 	cfg             *config.Config
 }
 
diff --git a/pkg/bitmask/autostart.go b/pkg/bitmask/autostart.go
index 9e37fe4c..f314dbc4 100644
--- a/pkg/bitmask/autostart.go
+++ b/pkg/bitmask/autostart.go
@@ -36,7 +36,7 @@ type Autostart interface {
 }
 
 // newAutostart creates a handler for the autostart of your platform
-func newAutostart(appName string, iconPath string) Autostart {
+func NewAutostart(appName string, iconPath string) Autostart {
 	exec := os.Args
 	if os.Getenv("SNAP") != "" {
 		re := regexp.MustCompile("/snap/([^/]*)/")
@@ -65,12 +65,12 @@ func newAutostart(appName string, iconPath string) Autostart {
 	}
 }
 
-type dummyAutostart struct{}
+type DummyAutostart struct{}
 
-func (a *dummyAutostart) Disable() error {
+func (a *DummyAutostart) Disable() error {
 	return nil
 }
 
-func (a *dummyAutostart) Enable() error {
+func (a *DummyAutostart) Enable() error {
 	return nil
 }
diff --git a/pkg/bitmask/init.go b/pkg/bitmask/init.go
index 401f8a7d..00f145e8 100644
--- a/pkg/bitmask/init.go
+++ b/pkg/bitmask/init.go
@@ -17,14 +17,12 @@ package bitmask
 
 import (
 	"errors"
+	"fmt"
 	"log"
 	"os"
 	"path"
 	"strconv"
 
-	"github.com/jmshal/go-locale"
-	"golang.org/x/text/message"
-
 	"0xacab.org/leap/bitmask-vpn/pkg/config"
 	"0xacab.org/leap/bitmask-vpn/pkg/vpn"
 )
@@ -89,27 +87,24 @@ func InitializeLogger() {
 	}
 }
 
-func initBitmask(printer *message.Printer) (Bitmask, error) {
+func initBitmask() (Bitmask, error) {
 	b, err := vpn.Init()
 	if err != nil {
 		log.Printf("An error ocurred starting bitmask: %v", err)
-		err = errors.New(printer.Sprintf(errorMsg, err))
+		err = errors.New(fmt.Sprintf(errorMsg, err))
 	}
 	return b, err
 }
 
-func InitializeBitmask(skipLaunch bool) (Bitmask, error) {
-	if skipLaunch {
+func InitializeBitmask(conf *config.Config) (Bitmask, error) {
+	if conf.SkipLaunch {
 		log.Println("Initializing bitmask, but not launching it...")
 	}
 	if _, err := os.Stat(config.Path); os.IsNotExist(err) {
 		os.MkdirAll(config.Path, os.ModePerm)
 	}
 
-	conf := config.ParseConfig()
-	conf.Printer = initPrinter()
-
-	b, err := initBitmask(conf.Printer)
+	b, err := initBitmask()
 	if err != nil {
 		return nil, err
 	}
@@ -119,39 +114,19 @@ func InitializeBitmask(skipLaunch bool) (Bitmask, error) {
 		return nil, err
 	}
 
-	if !skipLaunch {
+	if !conf.SkipLaunch {
 		err := maybeStartVPN(b, conf)
 		if err != nil {
 			log.Println("Error starting VPN: ", err)
 			return nil, err
 		}
 	}
-
-	var as Autostart
-	if skipLaunch || conf.DisableAustostart {
-		as = &dummyAutostart{}
-	} else {
-		as = newAutostart(config.ApplicationName, "")
-	}
-
-	err = as.Enable()
-	if err != nil {
-		log.Printf("Error enabling autostart: %v", err)
-	}
 	return b, nil
 }
 
-func initPrinter() *message.Printer {
-	locale, err := go_locale.DetectLocale()
-	if err != nil {
-		log.Println("Error detecting the system locale: ", err)
-	}
-
-	return message.NewPrinter(message.MatchLanguage(locale, "en"))
-}
-
 func setTransport(b Bitmask, conf *config.Config) error {
 	if conf.Obfs4 {
+		log.Printf("Use transport Obfs4")
 		err := b.UseTransport("obfs4")
 		if err != nil {
 			log.Printf("Error setting transport: %v", err)
diff --git a/pkg/config/gui.go b/pkg/config/gui.go
index 7f2515ce..3df1197a 100644
--- a/pkg/config/gui.go
+++ b/pkg/config/gui.go
@@ -20,8 +20,6 @@ import (
 	"os"
 	"path"
 	"time"
-
-	"golang.org/x/text/message"
 )
 
 const (
@@ -39,16 +37,14 @@ type Config struct {
 	file struct {
 		LastReminded      time.Time
 		Donated           time.Time
-		SelectGateway     bool
 		Obfs4             bool
 		UserStoppedVPN    bool
 		DisableAustostart bool
 	}
-	SelectGateway     bool
 	Obfs4             bool
 	DisableAustostart bool
 	StartVPN          bool
-	Printer           *message.Printer
+	SkipLaunch        bool
 }
 
 // ParseConfig reads the configuration from the configuration file
@@ -64,7 +60,6 @@ func ParseConfig() *Config {
 		err = dec.Decode(&conf.file)
 	}
 
-	conf.SelectGateway = conf.file.SelectGateway
 	conf.Obfs4 = conf.file.Obfs4
 	conf.DisableAustostart = conf.file.DisableAustostart
 	conf.StartVPN = !conf.file.UserStoppedVPN
-- 
GitLab