Other: Single instance

This commit is contained in:
James Houlahan
2022-10-12 23:30:43 +02:00
parent fd63611b41
commit 593d86f3a7
16 changed files with 470 additions and 73 deletions

1
go.mod
View File

@ -11,6 +11,7 @@ require (
github.com/ProtonMail/gopenpgp/v2 v2.4.10 github.com/ProtonMail/gopenpgp/v2 v2.4.10
github.com/PuerkitoBio/goquery v1.8.0 github.com/PuerkitoBio/goquery v1.8.0
github.com/abiosoft/ishell v2.0.0+incompatible github.com/abiosoft/ishell v2.0.0+incompatible
github.com/allan-simon/go-singleinstance v0.0.0-20210120080615-d0997106ab37
github.com/bradenaw/juniper v0.8.0 github.com/bradenaw/juniper v0.8.0
github.com/cucumber/godog v0.12.5 github.com/cucumber/godog v0.12.5
github.com/cucumber/messages-go/v16 v16.0.1 github.com/cucumber/messages-go/v16 v16.0.1

2
go.sum
View File

@ -59,6 +59,8 @@ github.com/agext/levenshtein v1.2.3 h1:YB2fHEn0UJagG8T1rrWknE3ZQzWM06O8AMAatNn7l
github.com/agext/levenshtein v1.2.3/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= github.com/agext/levenshtein v1.2.3/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/allan-simon/go-singleinstance v0.0.0-20210120080615-d0997106ab37 h1:28uU3TtuvQ6KRndxg9TrC868jBWmSKgh0GTXkACCXmA=
github.com/allan-simon/go-singleinstance v0.0.0-20210120080615-d0997106ab37/go.mod h1:6AXRstqK+32jeFmw89QGL2748+dj34Av4xc/I9oo9BY=
github.com/andybalholm/cascadia v1.3.1 h1:nhxRkql1kdYCc8Snf7D5/D3spOX+dBgjA6u8x004T2c= github.com/andybalholm/cascadia v1.3.1 h1:nhxRkql1kdYCc8Snf7D5/D3spOX+dBgjA6u8x004T2c=
github.com/andybalholm/cascadia v1.3.1/go.mod h1:R4bJ1UQfqADjvDa4P6HZHLh/3OxWWEqc0Sk8XGwHqvA= github.com/andybalholm/cascadia v1.3.1/go.mod h1:R4bJ1UQfqADjvDa4P6HZHLh/3OxWWEqc0Sk8XGwHqvA=
github.com/antlr/antlr4/runtime/Go/antlr v0.0.0-20220816024939-bc8df83d7b9d/go.mod h1:F7bn7fEU90QkQ3tnmaTx3LTKLEDqnwWODIYppRQ5hnY= github.com/antlr/antlr4/runtime/Go/antlr v0.0.0-20220816024939-bc8df83d7b9d/go.mod h1:F7bn7fEU90QkQ3tnmaTx3LTKLEDqnwWODIYppRQ5hnY=

View File

@ -6,14 +6,13 @@ import (
"net/http/cookiejar" "net/http/cookiejar"
"path/filepath" "path/filepath"
"github.com/Masterminds/semver/v3"
"github.com/ProtonMail/proton-bridge/v2/internal/bridge" "github.com/ProtonMail/proton-bridge/v2/internal/bridge"
"github.com/ProtonMail/proton-bridge/v2/internal/constants" "github.com/ProtonMail/proton-bridge/v2/internal/constants"
"github.com/ProtonMail/proton-bridge/v2/internal/cookies" "github.com/ProtonMail/proton-bridge/v2/internal/cookies"
"github.com/ProtonMail/proton-bridge/v2/internal/crash" "github.com/ProtonMail/proton-bridge/v2/internal/crash"
"github.com/ProtonMail/proton-bridge/v2/internal/events" "github.com/ProtonMail/proton-bridge/v2/internal/events"
"github.com/ProtonMail/proton-bridge/v2/internal/focus" "github.com/ProtonMail/proton-bridge/v2/internal/focus"
bridgeCLI "github.com/ProtonMail/proton-bridge/v2/internal/frontend/cli"
"github.com/ProtonMail/proton-bridge/v2/internal/frontend/grpc"
"github.com/ProtonMail/proton-bridge/v2/internal/locations" "github.com/ProtonMail/proton-bridge/v2/internal/locations"
"github.com/ProtonMail/proton-bridge/v2/internal/sentry" "github.com/ProtonMail/proton-bridge/v2/internal/sentry"
"github.com/ProtonMail/proton-bridge/v2/internal/useragent" "github.com/ProtonMail/proton-bridge/v2/internal/useragent"
@ -112,9 +111,10 @@ func New() *cli.App {
} }
func run(c *cli.Context) error { func run(c *cli.Context) error {
// If there's another instance already running, try to raise it and exit. // Get the current bridge version.
if raised := focus.TryRaise(); raised { version, err := semver.NewVersion(constants.Version)
return nil if err != nil {
return fmt.Errorf("could not create version: %w", err)
} }
// Create a user agent that will be used for all requests. // Create a user agent that will be used for all requests.
@ -131,42 +131,30 @@ func run(c *cli.Context) error {
return withCrashHandler(restarter, reporter, func(crashHandler *crash.Handler) error { return withCrashHandler(restarter, reporter, func(crashHandler *crash.Handler) error {
// Load the locations where we store our files. // Load the locations where we store our files.
return withLocations(func(locations *locations.Locations) error { return withLocations(func(locations *locations.Locations) error {
// Initialize the logging. // Initialize logging.
if err := initLogging(c, locations, crashHandler); err != nil { return withLogging(c, crashHandler, locations, func() error {
return fmt.Errorf("could not initialize logging: %w", err) // Ensure we are the only instance running.
} return withSingleInstance(locations, version, func() error {
// Unlock the encrypted vault.
return withVault(locations, func(vault *vault.Vault, insecure, corrupt bool) error {
// Load the cookies from the vault.
return withCookieJar(vault, func(cookieJar http.CookieJar) error {
// Create a new bridge instance.
return withBridge(c, locations, version, identifier, reporter, vault, cookieJar, func(b *bridge.Bridge, eventCh <-chan events.Event) error {
if insecure {
logrus.Warn("The vault key could not be retrieved; the vault will not be encrypted")
b.PushError(bridge.ErrVaultInsecure)
}
// Unlock the encrypted vault. if corrupt {
return withVault(locations, func(vault *vault.Vault, insecure, corrupt bool) error { logrus.Warn("The vault is corrupt and has been wiped")
// Load the cookies from the vault. b.PushError(bridge.ErrVaultCorrupt)
return withCookieJar(vault, func(cookieJar http.CookieJar) error { }
// Create a new bridge instance.
return withBridge(c, locations, identifier, reporter, vault, cookieJar, func(b *bridge.Bridge, eventCh <-chan events.Event) error {
if insecure {
logrus.Warn("The vault key could not be retrieved; the vault will not be encrypted")
b.PushError(bridge.ErrVaultInsecure)
}
if corrupt { // Run the frontend.
logrus.Warn("The vault is corrupt and has been wiped") return runFrontend(c, crashHandler, restarter, locations, b, eventCh)
b.PushError(bridge.ErrVaultCorrupt) })
} })
switch {
case c.Bool(flagCLI):
return bridgeCLI.New(b, eventCh).Loop()
case c.Bool(flagNonInteractive):
select {}
default:
service, err := grpc.NewService(crashHandler, restarter, locations, b, eventCh, !c.Bool(flagNoWindow))
if err != nil {
return fmt.Errorf("could not create service: %w", err)
}
return service.Loop()
}
}) })
}) })
}) })
@ -176,6 +164,38 @@ func run(c *cli.Context) error {
}) })
} }
// If there's another instance already running, try to raise it and exit.
func withSingleInstance(locations *locations.Locations, version *semver.Version, fn func() error) error {
lock, err := checkSingleInstance(locations.GetLockFile(), version)
if err != nil {
if ok := focus.TryRaise(); !ok {
return fmt.Errorf("another instance is already running but it could not be raised")
}
return nil
}
defer func() {
if err := lock.Close(); err != nil {
logrus.WithError(err).Error("Failed to close lock file")
}
}()
return fn()
}
// Initialize our logging system.
func withLogging(c *cli.Context, crashHandler *crash.Handler, locations *locations.Locations, fn func() error) error {
if err := initLogging(c, locations, crashHandler); err != nil {
return fmt.Errorf("could not initialize logging: %w", err)
}
// TODO: Add teardown actions (clean the log directory?)
return fn()
}
// Provide access to locations where we store our files.
func withLocations(fn func(*locations.Locations) error) error { func withLocations(fn func(*locations.Locations) error) error {
// Create a locations provider to determine where to store our files. // Create a locations provider to determine where to store our files.
provider, err := locations.NewDefaultProvider(filepath.Join(constants.VendorName, constants.ConfigName)) provider, err := locations.NewDefaultProvider(filepath.Join(constants.VendorName, constants.ConfigName))
@ -186,18 +206,15 @@ func withLocations(fn func(*locations.Locations) error) error {
// Create a new locations object that will be used to provide paths to store files. // Create a new locations object that will be used to provide paths to store files.
locations := locations.New(provider, constants.ConfigName) locations := locations.New(provider, constants.ConfigName)
// TODO: Add teardown actions (removing the lock file, etc.)
return fn(locations) return fn(locations)
} }
// Start profiling if requested.
func withProfiler(c *cli.Context, fn func() error) error { func withProfiler(c *cli.Context, fn func() error) error {
// Start CPU profile if requested.
if c.Bool(flagCPUProfile) { if c.Bool(flagCPUProfile) {
defer profile.Start(profile.CPUProfile, profile.ProfilePath(".")).Stop() defer profile.Start(profile.CPUProfile, profile.ProfilePath(".")).Stop()
} }
// Start memory profile if requested.
if c.Bool(flagMemProfile) { if c.Bool(flagMemProfile) {
defer profile.Start(profile.MemProfile, profile.MemProfileAllocs, profile.ProfilePath(".")).Stop() defer profile.Start(profile.MemProfile, profile.MemProfileAllocs, profile.ProfilePath(".")).Stop()
} }
@ -205,6 +222,7 @@ func withProfiler(c *cli.Context, fn func() error) error {
return fn() return fn()
} }
// Restart the app if necessary.
func withRestarter(fn func(*restarter.Restarter) error) error { func withRestarter(fn func(*restarter.Restarter) error) error {
restarter := restarter.New() restarter := restarter.New()
defer restarter.Restart() defer restarter.Restart()
@ -212,6 +230,7 @@ func withRestarter(fn func(*restarter.Restarter) error) error {
return fn(restarter) return fn(restarter)
} }
// Handle crashes if they occur.
func withCrashHandler(restarter *restarter.Restarter, reporter *sentry.Reporter, fn func(*crash.Handler) error) error { func withCrashHandler(restarter *restarter.Restarter, reporter *sentry.Reporter, fn func(*crash.Handler) error) error {
crashHandler := crash.NewHandler(crash.ShowErrorNotification(constants.FullAppName)) crashHandler := crash.NewHandler(crash.ShowErrorNotification(constants.FullAppName))
defer crashHandler.HandlePanic() defer crashHandler.HandlePanic()
@ -228,6 +247,7 @@ func withCrashHandler(restarter *restarter.Restarter, reporter *sentry.Reporter,
return fn(crashHandler) return fn(crashHandler)
} }
// Use a custom cookie jar to persist values across runs.
func withCookieJar(vault *vault.Vault, fn func(http.CookieJar) error) error { func withCookieJar(vault *vault.Vault, fn func(http.CookieJar) error) error {
// Create the underlying cookie jar. // Create the underlying cookie jar.
jar, err := cookiejar.New(nil) jar, err := cookiejar.New(nil)

View File

@ -29,18 +29,13 @@ const vaultSecretName = "bridge-vault-key"
func withBridge( func withBridge(
c *cli.Context, c *cli.Context,
locations *locations.Locations, locations *locations.Locations,
version *semver.Version,
identifier *useragent.UserAgent, identifier *useragent.UserAgent,
reporter *sentry.Reporter, reporter *sentry.Reporter,
vault *vault.Vault, vault *vault.Vault,
cookieJar http.CookieJar, cookieJar http.CookieJar,
fn func(*bridge.Bridge, <-chan events.Event) error, fn func(*bridge.Bridge, <-chan events.Event) error,
) error { ) error {
// Get the current bridge version.
version, err := semver.NewVersion(constants.Version)
if err != nil {
return fmt.Errorf("could not create version: %w", err)
}
// Create the underlying dialer used by the bridge. // Create the underlying dialer used by the bridge.
// It only connects to trusted servers and reports any untrusted servers it finds. // It only connects to trusted servers and reports any untrusted servers it finds.
pinningDialer := dialer.NewPinningTLSDialer( pinningDialer := dialer.NewPinningTLSDialer(

39
internal/app/frontend.go Normal file
View File

@ -0,0 +1,39 @@
package app
import (
"fmt"
"github.com/ProtonMail/proton-bridge/v2/internal/bridge"
"github.com/ProtonMail/proton-bridge/v2/internal/crash"
"github.com/ProtonMail/proton-bridge/v2/internal/events"
bridgeCLI "github.com/ProtonMail/proton-bridge/v2/internal/frontend/cli"
"github.com/ProtonMail/proton-bridge/v2/internal/frontend/grpc"
"github.com/ProtonMail/proton-bridge/v2/internal/locations"
"github.com/ProtonMail/proton-bridge/v2/pkg/restarter"
"github.com/urfave/cli/v2"
)
func runFrontend(
c *cli.Context,
crashHandler *crash.Handler,
restarter *restarter.Restarter,
locations *locations.Locations,
bridge *bridge.Bridge,
eventCh <-chan events.Event,
) error {
switch {
case c.Bool(flagCLI):
return bridgeCLI.New(bridge, eventCh).Loop()
case c.Bool(flagNonInteractive):
select {}
default:
service, err := grpc.NewService(crashHandler, restarter, locations, bridge, eventCh, !c.Bool(flagNoWindow))
if err != nil {
return fmt.Errorf("could not create service: %w", err)
}
return service.Loop()
}
}

View File

@ -0,0 +1,109 @@
// Copyright (c) 2022 Proton AG
//
// This file is part of Proton Mail Bridge.
//
// Proton Mail Bridge is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Proton Mail Bridge is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Proton Mail Bridge. If not, see <https://www.gnu.org/licenses/>.
//go:build !windows
// +build !windows
package app
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/Masterminds/semver/v3"
"github.com/ProtonMail/proton-bridge/v2/internal/focus"
"github.com/allan-simon/go-singleinstance"
"golang.org/x/sys/unix"
)
// checkSingleInstance checks if another instance of the application is already running.
// It tries to create a lock file at the given path.
// If it succeeds, it returns the lock file and a nil error.
//
// For macOS and Linux when already running version is older than this instance
// it will kill old and continue with this new bridge (i.e. no error returned).
func checkSingleInstance(lockFilePath string, curVersion *semver.Version) (*os.File, error) {
if lock, err := singleinstance.CreateLockFile(lockFilePath); err == nil {
return lock, nil
}
// We couldn't create the lock file, so another instance is probably running.
// Check if it's an older version of the app.
lastVersion, ok := focus.TryVersion()
if !ok {
return nil, fmt.Errorf("failed to determine version of running instance")
}
if !lastVersion.LessThan(curVersion) {
return nil, fmt.Errorf("running instance is newer than this one")
}
// The other instance is an older version, so we should kill it.
pid, err := getPID(lockFilePath)
if err != nil {
return nil, err
}
if err := unix.Kill(pid, unix.SIGTERM); err != nil {
return nil, err
}
// Need to wait some time to release file lock
time.Sleep(time.Second)
return singleinstance.CreateLockFile(lockFilePath)
}
func getPID(lockFilePath string) (int, error) {
file, err := os.Open(filepath.Clean(lockFilePath))
if err != nil {
return 0, err
}
defer func() { _ = file.Close() }()
rawPID := make([]byte, 10) // PID is probably up to 7 digits long, 10 should be enough
n, err := file.Read(rawPID)
if err != nil {
return 0, err
}
return strconv.Atoi(strings.TrimSpace(string(rawPID[:n])))
}
/*
func runningVersionIsOlder() error {
currentVer, err := semver.StrictNewVersion(constants.Version)
if err != nil {
return err
}
runningVer, err := semver.StrictNewVersion(settingsObj.Get(settings.LastVersionKey))
if err != nil {
return err
}
if !runningVer.LessThan(currentVer) {
return errors.New("running version is not older")
}
return nil
}
*/

View File

@ -0,0 +1,32 @@
// Copyright (c) 2022 Proton AG
//
// This file is part of Proton Mail Bridge.
//
// Proton Mail Bridge is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Proton Mail Bridge is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Proton Mail Bridge. If not, see <https://www.gnu.org/licenses/>.
//go:build windows
// +build windows
package app
import (
"os"
"github.com/Masterminds/semver/v3"
"github.com/allan-simon/go-singleinstance"
)
func checkSingleInstance(lockFilePath string, _ *semver.Version) (*os.File, error) {
return singleinstance.CreateLockFile(lockFilePath)
}

View File

@ -124,7 +124,7 @@ func New(
return nil, nil, fmt.Errorf("failed to create IMAP server: %w", err) return nil, nil, fmt.Errorf("failed to create IMAP server: %w", err)
} }
focusService, err := focus.NewService() focusService, err := focus.NewService(curVersion)
if err != nil { if err != nil {
return nil, nil, fmt.Errorf("failed to create focus service: %w", err) return nil, nil, fmt.Errorf("failed to create focus service: %w", err)
} }

View File

@ -6,7 +6,9 @@ import (
"net" "net"
"time" "time"
"github.com/Masterminds/semver/v3"
"github.com/ProtonMail/proton-bridge/v2/internal/focus/proto" "github.com/ProtonMail/proton-bridge/v2/internal/focus/proto"
"github.com/sirupsen/logrus"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/credentials/insecure"
"google.golang.org/protobuf/types/known/emptypb" "google.golang.org/protobuf/types/known/emptypb"
@ -27,6 +29,12 @@ func TryRaise() bool {
return false return false
} }
defer func() {
if err := cc.Close(); err != nil {
logrus.WithError(err).Warn("Failed to close focus connection")
}
}()
if _, err := proto.NewFocusClient(cc).Raise(ctx, &emptypb.Empty{}); err != nil { if _, err := proto.NewFocusClient(cc).Raise(ctx, &emptypb.Empty{}); err != nil {
return false return false
} }
@ -37,3 +45,37 @@ func TryRaise() bool {
return true return true
} }
// TryRaise tries to raise the application by dialing the focus service.
// It returns true if the service is running and the application was told to raise.
func TryVersion() (*semver.Version, bool) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
cc, err := grpc.DialContext(
ctx,
net.JoinHostPort(Host, fmt.Sprint(Port)),
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil {
return nil, false
}
defer func() {
if err := cc.Close(); err != nil {
logrus.WithError(err).Warn("Failed to close focus connection")
}
}()
raw, err := proto.NewFocusClient(cc).Version(ctx, &emptypb.Empty{})
if err != nil {
return nil, false
}
version, err := semver.NewVersion(raw.GetVersion())
if err != nil {
return nil, false
}
return version, true
}

View File

@ -3,12 +3,13 @@ package focus
import ( import (
"testing" "testing"
"github.com/Masterminds/semver/v3"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
func TestFocusRaise(t *testing.T) { func TestFocus_Raise(t *testing.T) {
// Start the focus service. // Start the focus service.
service, err := NewService() service, err := NewService(semver.MustParse("1.2.3"))
require.NoError(t, err) require.NoError(t, err)
// Try to dial it, it should succeed. // Try to dial it, it should succeed.
@ -23,3 +24,14 @@ func TestFocusRaise(t *testing.T) {
// Try to dial it, it should fail. // Try to dial it, it should fail.
require.False(t, TryRaise()) require.False(t, TryRaise())
} }
func TestFocus_Version(t *testing.T) {
// Start the focus service.
_, err := NewService(semver.MustParse("1.2.3"))
require.NoError(t, err)
// Try to dial it, it should succeed.
version, ok := TryVersion()
require.True(t, ok)
require.Equal(t, "1.2.3", version.String())
}

View File

@ -18,17 +18,17 @@
// Code generated by protoc-gen-go. DO NOT EDIT. // Code generated by protoc-gen-go. DO NOT EDIT.
// versions: // versions:
// protoc-gen-go v1.28.0 // protoc-gen-go v1.28.0
// protoc v3.21.3 // protoc v3.21.7
// source: focus.proto // source: focus.proto
package proto package proto
import ( import (
reflect "reflect"
protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl" protoimpl "google.golang.org/protobuf/runtime/protoimpl"
emptypb "google.golang.org/protobuf/types/known/emptypb" emptypb "google.golang.org/protobuf/types/known/emptypb"
reflect "reflect"
sync "sync"
) )
const ( const (
@ -38,31 +38,101 @@ const (
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
) )
type VersionResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Version string `protobuf:"bytes,1,opt,name=version,proto3" json:"version,omitempty"`
}
func (x *VersionResponse) Reset() {
*x = VersionResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_focus_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *VersionResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*VersionResponse) ProtoMessage() {}
func (x *VersionResponse) ProtoReflect() protoreflect.Message {
mi := &file_focus_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use VersionResponse.ProtoReflect.Descriptor instead.
func (*VersionResponse) Descriptor() ([]byte, []int) {
return file_focus_proto_rawDescGZIP(), []int{0}
}
func (x *VersionResponse) GetVersion() string {
if x != nil {
return x.Version
}
return ""
}
var File_focus_proto protoreflect.FileDescriptor var File_focus_proto protoreflect.FileDescriptor
var file_focus_proto_rawDesc = []byte{ var file_focus_proto_rawDesc = []byte{
0x0a, 0x0b, 0x66, 0x6f, 0x63, 0x75, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x05, 0x70, 0x0a, 0x0b, 0x66, 0x6f, 0x63, 0x75, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x05, 0x70,
0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1b, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1b, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x32, 0x40, 0x0a, 0x05, 0x46, 0x6f, 0x63, 0x75, 0x73, 0x12, 0x37, 0x0a, 0x05, 0x52, 0x61, 0x6f, 0x22, 0x2b, 0x0a, 0x0f, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70,
0x69, 0x73, 0x65, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18,
0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x32, 0x7b,
0x0a, 0x05, 0x46, 0x6f, 0x63, 0x75, 0x73, 0x12, 0x37, 0x0a, 0x05, 0x52, 0x61, 0x69, 0x73, 0x65,
0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62,
0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c,
0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79,
0x12, 0x39, 0x0a, 0x07, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x16, 0x2e, 0x67, 0x6f,
0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d,
0x70, 0x74, 0x79, 0x42, 0x3d, 0x5a, 0x3b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x70, 0x74, 0x79, 0x1a, 0x16, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x56, 0x65, 0x72, 0x73,
0x6d, 0x2f, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x6e, 0x4d, 0x61, 0x69, 0x6c, 0x2f, 0x70, 0x72, 0x6f, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x3d, 0x5a, 0x3b, 0x67,
0x74, 0x6f, 0x6e, 0x2d, 0x62, 0x72, 0x69, 0x64, 0x67, 0x65, 0x2f, 0x76, 0x32, 0x2f, 0x69, 0x6e, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x6e,
0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x66, 0x6f, 0x63, 0x75, 0x73, 0x2f, 0x70, 0x72, 0x6f, 0x4d, 0x61, 0x69, 0x6c, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x6e, 0x2d, 0x62, 0x72, 0x69, 0x64,
0x74, 0x6f, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, 0x67, 0x65, 0x2f, 0x76, 0x32, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x66,
0x6f, 0x63, 0x75, 0x73, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x33,
} }
var (
file_focus_proto_rawDescOnce sync.Once
file_focus_proto_rawDescData = file_focus_proto_rawDesc
)
func file_focus_proto_rawDescGZIP() []byte {
file_focus_proto_rawDescOnce.Do(func() {
file_focus_proto_rawDescData = protoimpl.X.CompressGZIP(file_focus_proto_rawDescData)
})
return file_focus_proto_rawDescData
}
var file_focus_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_focus_proto_goTypes = []interface{}{ var file_focus_proto_goTypes = []interface{}{
(*emptypb.Empty)(nil), // 0: google.protobuf.Empty (*VersionResponse)(nil), // 0: proto.VersionResponse
(*emptypb.Empty)(nil), // 1: google.protobuf.Empty
} }
var file_focus_proto_depIdxs = []int32{ var file_focus_proto_depIdxs = []int32{
0, // 0: proto.Focus.Raise:input_type -> google.protobuf.Empty 1, // 0: proto.Focus.Raise:input_type -> google.protobuf.Empty
0, // 1: proto.Focus.Raise:output_type -> google.protobuf.Empty 1, // 1: proto.Focus.Version:input_type -> google.protobuf.Empty
1, // [1:2] is the sub-list for method output_type 1, // 2: proto.Focus.Raise:output_type -> google.protobuf.Empty
0, // [0:1] is the sub-list for method input_type 0, // 3: proto.Focus.Version:output_type -> proto.VersionResponse
2, // [2:4] is the sub-list for method output_type
0, // [0:2] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name 0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee 0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name 0, // [0:0] is the sub-list for field type_name
@ -73,18 +143,33 @@ func file_focus_proto_init() {
if File_focus_proto != nil { if File_focus_proto != nil {
return return
} }
if !protoimpl.UnsafeEnabled {
file_focus_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*VersionResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{} type x struct{}
out := protoimpl.TypeBuilder{ out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{ File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(), GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_focus_proto_rawDesc, RawDescriptor: file_focus_proto_rawDesc,
NumEnums: 0, NumEnums: 0,
NumMessages: 0, NumMessages: 1,
NumExtensions: 0, NumExtensions: 0,
NumServices: 1, NumServices: 1,
}, },
GoTypes: file_focus_proto_goTypes, GoTypes: file_focus_proto_goTypes,
DependencyIndexes: file_focus_proto_depIdxs, DependencyIndexes: file_focus_proto_depIdxs,
MessageInfos: file_focus_proto_msgTypes,
}.Build() }.Build()
File_focus_proto = out.File File_focus_proto = out.File
file_focus_proto_rawDesc = nil file_focus_proto_rawDesc = nil

View File

@ -28,4 +28,11 @@ package proto;
//**********************************************************************************************************************≠–– //**********************************************************************************************************************≠––
service Focus { service Focus {
rpc Raise(google.protobuf.Empty) returns (google.protobuf.Empty); rpc Raise(google.protobuf.Empty) returns (google.protobuf.Empty);
rpc Version(google.protobuf.Empty) returns (VersionResponse);
}
//**********************************************************************************************************************
message VersionResponse {
string version = 1;
} }

View File

@ -1,14 +1,13 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT. // Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions: // versions:
// - protoc-gen-go-grpc v1.2.0 // - protoc-gen-go-grpc v1.2.0
// - protoc v3.21.3 // - protoc v3.21.7
// source: focus.proto // source: focus.proto
package proto package proto
import ( import (
context "context" context "context"
grpc "google.golang.org/grpc" grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes" codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status" status "google.golang.org/grpc/status"
@ -25,6 +24,7 @@ const _ = grpc.SupportPackageIsVersion7
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type FocusClient interface { type FocusClient interface {
Raise(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*emptypb.Empty, error) Raise(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*emptypb.Empty, error)
Version(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*VersionResponse, error)
} }
type focusClient struct { type focusClient struct {
@ -44,11 +44,21 @@ func (c *focusClient) Raise(ctx context.Context, in *emptypb.Empty, opts ...grpc
return out, nil return out, nil
} }
func (c *focusClient) Version(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*VersionResponse, error) {
out := new(VersionResponse)
err := c.cc.Invoke(ctx, "/proto.Focus/Version", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// FocusServer is the server API for Focus service. // FocusServer is the server API for Focus service.
// All implementations must embed UnimplementedFocusServer // All implementations must embed UnimplementedFocusServer
// for forward compatibility // for forward compatibility
type FocusServer interface { type FocusServer interface {
Raise(context.Context, *emptypb.Empty) (*emptypb.Empty, error) Raise(context.Context, *emptypb.Empty) (*emptypb.Empty, error)
Version(context.Context, *emptypb.Empty) (*VersionResponse, error)
mustEmbedUnimplementedFocusServer() mustEmbedUnimplementedFocusServer()
} }
@ -59,6 +69,9 @@ type UnimplementedFocusServer struct {
func (UnimplementedFocusServer) Raise(context.Context, *emptypb.Empty) (*emptypb.Empty, error) { func (UnimplementedFocusServer) Raise(context.Context, *emptypb.Empty) (*emptypb.Empty, error) {
return nil, status.Errorf(codes.Unimplemented, "method Raise not implemented") return nil, status.Errorf(codes.Unimplemented, "method Raise not implemented")
} }
func (UnimplementedFocusServer) Version(context.Context, *emptypb.Empty) (*VersionResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Version not implemented")
}
func (UnimplementedFocusServer) mustEmbedUnimplementedFocusServer() {} func (UnimplementedFocusServer) mustEmbedUnimplementedFocusServer() {}
// UnsafeFocusServer may be embedded to opt out of forward compatibility for this service. // UnsafeFocusServer may be embedded to opt out of forward compatibility for this service.
@ -90,6 +103,24 @@ func _Focus_Raise_Handler(srv interface{}, ctx context.Context, dec func(interfa
return interceptor(ctx, in, info, handler) return interceptor(ctx, in, info, handler)
} }
func _Focus_Version_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(emptypb.Empty)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(FocusServer).Version(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/proto.Focus/Version",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(FocusServer).Version(ctx, req.(*emptypb.Empty))
}
return interceptor(ctx, in, info, handler)
}
// Focus_ServiceDesc is the grpc.ServiceDesc for Focus service. // Focus_ServiceDesc is the grpc.ServiceDesc for Focus service.
// It's only intended for direct use with grpc.RegisterService, // It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy) // and not to be introspected or modified (even as a copy)
@ -101,6 +132,10 @@ var Focus_ServiceDesc = grpc.ServiceDesc{
MethodName: "Raise", MethodName: "Raise",
Handler: _Focus_Raise_Handler, Handler: _Focus_Raise_Handler,
}, },
{
MethodName: "Version",
Handler: _Focus_Version_Handler,
},
}, },
Streams: []grpc.StreamDesc{}, Streams: []grpc.StreamDesc{},
Metadata: "focus.proto", Metadata: "focus.proto",

View File

@ -6,6 +6,7 @@ import (
"fmt" "fmt"
"net" "net"
"github.com/Masterminds/semver/v3"
"github.com/ProtonMail/proton-bridge/v2/internal/focus/proto" "github.com/ProtonMail/proton-bridge/v2/internal/focus/proto"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/protobuf/types/known/emptypb" "google.golang.org/protobuf/types/known/emptypb"
@ -24,11 +25,12 @@ type Service struct {
server *grpc.Server server *grpc.Server
listener net.Listener listener net.Listener
raiseCh chan struct{} raiseCh chan struct{}
version *semver.Version
} }
// NewService creates a new focus service. // NewService creates a new focus service.
// It listens on the local host and port 1042 (by default). // It listens on the local host and port 1042 (by default).
func NewService() (*Service, error) { func NewService(version *semver.Version) (*Service, error) {
listener, err := net.Listen("tcp", net.JoinHostPort(Host, fmt.Sprint(Port))) listener, err := net.Listen("tcp", net.JoinHostPort(Host, fmt.Sprint(Port)))
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to listen: %w", err) return nil, fmt.Errorf("failed to listen: %w", err)
@ -38,6 +40,7 @@ func NewService() (*Service, error) {
server: grpc.NewServer(), server: grpc.NewServer(),
listener: listener, listener: listener,
raiseCh: make(chan struct{}, 1), raiseCh: make(chan struct{}, 1),
version: version,
} }
proto.RegisterFocusServer(service.server, service) proto.RegisterFocusServer(service.server, service)
@ -57,6 +60,13 @@ func (service *Service) Raise(context.Context, *emptypb.Empty) (*emptypb.Empty,
return &emptypb.Empty{}, nil return &emptypb.Empty{}, nil
} }
// Version implements the gRPC FocusService interface; it returns the version of the service.
func (service *Service) Version(context.Context, *emptypb.Empty) (*proto.VersionResponse, error) {
return &proto.VersionResponse{
Version: service.version.Original(),
}, nil
}
// GetRaiseCh returns a channel on which events are sent when the application should be raised. // GetRaiseCh returns a channel on which events are sent when the application should be raised.
func (service *Service) GetRaiseCh() <-chan struct{} { func (service *Service) GetRaiseCh() <-chan struct{} {
return service.raiseCh return service.raiseCh

View File

@ -341,6 +341,9 @@ func (f *frontendCLI) watchEvents(eventCh <-chan events.Event) {
case events.TLSIssue: case events.TLSIssue:
f.notifyCertIssue() f.notifyCertIssue()
case events.Raise:
f.Printf("Hello!")
} }
} }

View File

@ -51,7 +51,12 @@ func New(provider Provider, configName string) *Locations {
} }
} }
// GetGuiLockFile returns the path to the lock file (e.g. ~/.cache/<company>/<app>/<app>.lock). // GetLockFile returns the path to the bridge lock file (e.g. ~/.cache/<company>/<app>/<app>.lock).
func (l *Locations) GetLockFile() string {
return filepath.Join(l.userCache, l.configName+".lock")
}
// GetGuiLockFile returns the path to the GUI lock file (e.g. ~/.cache/<company>/<app>/<app>.lock).
func (l *Locations) GetGuiLockFile() string { func (l *Locations) GetGuiLockFile() string {
return filepath.Join(l.userCache, l.configGuiName+".lock") return filepath.Join(l.userCache, l.configGuiName+".lock")
} }