From 593d86f3a7941a3024b06a5e4d242ec61e8a1ae2 Mon Sep 17 00:00:00 2001 From: James Houlahan Date: Wed, 12 Oct 2022 23:30:43 +0200 Subject: [PATCH] Other: Single instance --- go.mod | 1 + go.sum | 2 + internal/app/app.go | 106 +++++++++++++--------- internal/app/bridge.go | 7 +- internal/app/frontend.go | 39 ++++++++ internal/app/singleinstance_unix.go | 109 ++++++++++++++++++++++ internal/app/singleinstance_windows.go | 32 +++++++ internal/bridge/bridge.go | 2 +- internal/focus/client.go | 42 +++++++++ internal/focus/focus_test.go | 16 +++- internal/focus/proto/focus.pb.go | 119 +++++++++++++++++++++---- internal/focus/proto/focus.proto | 7 ++ internal/focus/proto/focus_grpc.pb.go | 39 +++++++- internal/focus/service.go | 12 ++- internal/frontend/cli/frontend.go | 3 + internal/locations/locations.go | 7 +- 16 files changed, 470 insertions(+), 73 deletions(-) create mode 100644 internal/app/frontend.go create mode 100644 internal/app/singleinstance_unix.go create mode 100644 internal/app/singleinstance_windows.go diff --git a/go.mod b/go.mod index 7d95c386..dc027458 100644 --- a/go.mod +++ b/go.mod @@ -11,6 +11,7 @@ require ( github.com/ProtonMail/gopenpgp/v2 v2.4.10 github.com/PuerkitoBio/goquery v1.8.0 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/cucumber/godog v0.12.5 github.com/cucumber/messages-go/v16 v16.0.1 diff --git a/go.sum b/go.sum index 34c6d438..2ba9856e 100644 --- a/go.sum +++ b/go.sum @@ -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/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/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/go.mod h1:R4bJ1UQfqADjvDa4P6HZHLh/3OxWWEqc0Sk8XGwHqvA= github.com/antlr/antlr4/runtime/Go/antlr v0.0.0-20220816024939-bc8df83d7b9d/go.mod h1:F7bn7fEU90QkQ3tnmaTx3LTKLEDqnwWODIYppRQ5hnY= diff --git a/internal/app/app.go b/internal/app/app.go index faddc405..4a1fbfba 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -6,14 +6,13 @@ import ( "net/http/cookiejar" "path/filepath" + "github.com/Masterminds/semver/v3" "github.com/ProtonMail/proton-bridge/v2/internal/bridge" "github.com/ProtonMail/proton-bridge/v2/internal/constants" "github.com/ProtonMail/proton-bridge/v2/internal/cookies" "github.com/ProtonMail/proton-bridge/v2/internal/crash" "github.com/ProtonMail/proton-bridge/v2/internal/events" "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/sentry" "github.com/ProtonMail/proton-bridge/v2/internal/useragent" @@ -112,9 +111,10 @@ func New() *cli.App { } func run(c *cli.Context) error { - // If there's another instance already running, try to raise it and exit. - if raised := focus.TryRaise(); raised { - return nil + // Get the current bridge version. + version, err := semver.NewVersion(constants.Version) + if err != nil { + return fmt.Errorf("could not create version: %w", err) } // 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 { // Load the locations where we store our files. return withLocations(func(locations *locations.Locations) error { - // Initialize the logging. - if err := initLogging(c, locations, crashHandler); err != nil { - return fmt.Errorf("could not initialize logging: %w", err) - } + // Initialize logging. + return withLogging(c, crashHandler, locations, func() error { + // 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. - 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, 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 { + logrus.Warn("The vault is corrupt and has been wiped") + b.PushError(bridge.ErrVaultCorrupt) + } - if corrupt { - logrus.Warn("The vault is corrupt and has been wiped") - 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() - } + // Run the frontend. + return runFrontend(c, crashHandler, restarter, locations, b, eventCh) + }) + }) }) }) }) @@ -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 { // Create a locations provider to determine where to store our files. 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. locations := locations.New(provider, constants.ConfigName) - // TODO: Add teardown actions (removing the lock file, etc.) - return fn(locations) } +// Start profiling if requested. func withProfiler(c *cli.Context, fn func() error) error { - // Start CPU profile if requested. if c.Bool(flagCPUProfile) { defer profile.Start(profile.CPUProfile, profile.ProfilePath(".")).Stop() } - // Start memory profile if requested. if c.Bool(flagMemProfile) { 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() } +// Restart the app if necessary. func withRestarter(fn func(*restarter.Restarter) error) error { restarter := restarter.New() defer restarter.Restart() @@ -212,6 +230,7 @@ func withRestarter(fn func(*restarter.Restarter) error) error { return fn(restarter) } +// Handle crashes if they occur. func withCrashHandler(restarter *restarter.Restarter, reporter *sentry.Reporter, fn func(*crash.Handler) error) error { crashHandler := crash.NewHandler(crash.ShowErrorNotification(constants.FullAppName)) defer crashHandler.HandlePanic() @@ -228,6 +247,7 @@ func withCrashHandler(restarter *restarter.Restarter, reporter *sentry.Reporter, return fn(crashHandler) } +// Use a custom cookie jar to persist values across runs. func withCookieJar(vault *vault.Vault, fn func(http.CookieJar) error) error { // Create the underlying cookie jar. jar, err := cookiejar.New(nil) diff --git a/internal/app/bridge.go b/internal/app/bridge.go index d089c75f..dc0518a5 100644 --- a/internal/app/bridge.go +++ b/internal/app/bridge.go @@ -29,18 +29,13 @@ const vaultSecretName = "bridge-vault-key" func withBridge( c *cli.Context, locations *locations.Locations, + version *semver.Version, identifier *useragent.UserAgent, reporter *sentry.Reporter, vault *vault.Vault, cookieJar http.CookieJar, fn func(*bridge.Bridge, <-chan events.Event) 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. // It only connects to trusted servers and reports any untrusted servers it finds. pinningDialer := dialer.NewPinningTLSDialer( diff --git a/internal/app/frontend.go b/internal/app/frontend.go new file mode 100644 index 00000000..2ba478a3 --- /dev/null +++ b/internal/app/frontend.go @@ -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() + } +} diff --git a/internal/app/singleinstance_unix.go b/internal/app/singleinstance_unix.go new file mode 100644 index 00000000..94976300 --- /dev/null +++ b/internal/app/singleinstance_unix.go @@ -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 . + +//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 +} +*/ diff --git a/internal/app/singleinstance_windows.go b/internal/app/singleinstance_windows.go new file mode 100644 index 00000000..6efaf0c0 --- /dev/null +++ b/internal/app/singleinstance_windows.go @@ -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 . + +//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) +} diff --git a/internal/bridge/bridge.go b/internal/bridge/bridge.go index 9f3e5ed2..e46b6b0e 100644 --- a/internal/bridge/bridge.go +++ b/internal/bridge/bridge.go @@ -124,7 +124,7 @@ func New( return nil, nil, fmt.Errorf("failed to create IMAP server: %w", err) } - focusService, err := focus.NewService() + focusService, err := focus.NewService(curVersion) if err != nil { return nil, nil, fmt.Errorf("failed to create focus service: %w", err) } diff --git a/internal/focus/client.go b/internal/focus/client.go index c1e46bac..83f20031 100644 --- a/internal/focus/client.go +++ b/internal/focus/client.go @@ -6,7 +6,9 @@ import ( "net" "time" + "github.com/Masterminds/semver/v3" "github.com/ProtonMail/proton-bridge/v2/internal/focus/proto" + "github.com/sirupsen/logrus" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "google.golang.org/protobuf/types/known/emptypb" @@ -27,6 +29,12 @@ func TryRaise() bool { 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 { return false } @@ -37,3 +45,37 @@ func TryRaise() bool { 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 +} diff --git a/internal/focus/focus_test.go b/internal/focus/focus_test.go index ce5e4beb..5e13a3db 100644 --- a/internal/focus/focus_test.go +++ b/internal/focus/focus_test.go @@ -3,12 +3,13 @@ package focus import ( "testing" + "github.com/Masterminds/semver/v3" "github.com/stretchr/testify/require" ) -func TestFocusRaise(t *testing.T) { +func TestFocus_Raise(t *testing.T) { // Start the focus service. - service, err := NewService() + service, err := NewService(semver.MustParse("1.2.3")) require.NoError(t, err) // Try to dial it, it should succeed. @@ -23,3 +24,14 @@ func TestFocusRaise(t *testing.T) { // Try to dial it, it should fail. 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()) +} diff --git a/internal/focus/proto/focus.pb.go b/internal/focus/proto/focus.pb.go index 2225da58..316367a4 100644 --- a/internal/focus/proto/focus.pb.go +++ b/internal/focus/proto/focus.pb.go @@ -18,17 +18,17 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.28.0 -// protoc v3.21.3 +// protoc v3.21.7 // source: focus.proto package proto import ( - reflect "reflect" - protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" emptypb "google.golang.org/protobuf/types/known/emptypb" + reflect "reflect" + sync "sync" ) const ( @@ -38,31 +38,101 @@ const ( _ = 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_rawDesc = []byte{ 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, 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, - 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, 0x22, 0x2b, 0x0a, 0x0f, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, + 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, + 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, - 0x70, 0x74, 0x79, 0x42, 0x3d, 0x5a, 0x3b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, - 0x6d, 0x2f, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x6e, 0x4d, 0x61, 0x69, 0x6c, 0x2f, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x6e, 0x2d, 0x62, 0x72, 0x69, 0x64, 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, + 0x70, 0x74, 0x79, 0x1a, 0x16, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x56, 0x65, 0x72, 0x73, + 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x3d, 0x5a, 0x3b, 0x67, + 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x6e, + 0x4d, 0x61, 0x69, 0x6c, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x6e, 0x2d, 0x62, 0x72, 0x69, 0x64, + 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{}{ - (*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{ - 0, // 0: proto.Focus.Raise:input_type -> google.protobuf.Empty - 0, // 1: proto.Focus.Raise:output_type -> google.protobuf.Empty - 1, // [1:2] is the sub-list for method output_type - 0, // [0:1] is the sub-list for method input_type + 1, // 0: proto.Focus.Raise:input_type -> google.protobuf.Empty + 1, // 1: proto.Focus.Version:input_type -> google.protobuf.Empty + 1, // 2: proto.Focus.Raise:output_type -> google.protobuf.Empty + 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 extendee 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 { 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{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_focus_proto_rawDesc, NumEnums: 0, - NumMessages: 0, + NumMessages: 1, NumExtensions: 0, NumServices: 1, }, GoTypes: file_focus_proto_goTypes, DependencyIndexes: file_focus_proto_depIdxs, + MessageInfos: file_focus_proto_msgTypes, }.Build() File_focus_proto = out.File file_focus_proto_rawDesc = nil diff --git a/internal/focus/proto/focus.proto b/internal/focus/proto/focus.proto index 9691d8d3..cd67352d 100644 --- a/internal/focus/proto/focus.proto +++ b/internal/focus/proto/focus.proto @@ -28,4 +28,11 @@ package proto; //**********************************************************************************************************************≠–– service Focus { rpc Raise(google.protobuf.Empty) returns (google.protobuf.Empty); + rpc Version(google.protobuf.Empty) returns (VersionResponse); +} + +//********************************************************************************************************************** + +message VersionResponse { + string version = 1; } diff --git a/internal/focus/proto/focus_grpc.pb.go b/internal/focus/proto/focus_grpc.pb.go index fb9dda1e..7ddc67e5 100644 --- a/internal/focus/proto/focus_grpc.pb.go +++ b/internal/focus/proto/focus_grpc.pb.go @@ -1,14 +1,13 @@ // Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: // - protoc-gen-go-grpc v1.2.0 -// - protoc v3.21.3 +// - protoc v3.21.7 // source: focus.proto package proto import ( context "context" - grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" 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. type FocusClient interface { 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 { @@ -44,11 +44,21 @@ func (c *focusClient) Raise(ctx context.Context, in *emptypb.Empty, opts ...grpc 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. // All implementations must embed UnimplementedFocusServer // for forward compatibility type FocusServer interface { Raise(context.Context, *emptypb.Empty) (*emptypb.Empty, error) + Version(context.Context, *emptypb.Empty) (*VersionResponse, error) mustEmbedUnimplementedFocusServer() } @@ -59,6 +69,9 @@ type UnimplementedFocusServer struct { func (UnimplementedFocusServer) Raise(context.Context, *emptypb.Empty) (*emptypb.Empty, error) { 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() {} // 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) } +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. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) @@ -101,6 +132,10 @@ var Focus_ServiceDesc = grpc.ServiceDesc{ MethodName: "Raise", Handler: _Focus_Raise_Handler, }, + { + MethodName: "Version", + Handler: _Focus_Version_Handler, + }, }, Streams: []grpc.StreamDesc{}, Metadata: "focus.proto", diff --git a/internal/focus/service.go b/internal/focus/service.go index 6a3f1f4a..c61e25b5 100644 --- a/internal/focus/service.go +++ b/internal/focus/service.go @@ -6,6 +6,7 @@ import ( "fmt" "net" + "github.com/Masterminds/semver/v3" "github.com/ProtonMail/proton-bridge/v2/internal/focus/proto" "google.golang.org/grpc" "google.golang.org/protobuf/types/known/emptypb" @@ -24,11 +25,12 @@ type Service struct { server *grpc.Server listener net.Listener raiseCh chan struct{} + version *semver.Version } // NewService creates a new focus service. // 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))) if err != nil { return nil, fmt.Errorf("failed to listen: %w", err) @@ -38,6 +40,7 @@ func NewService() (*Service, error) { server: grpc.NewServer(), listener: listener, raiseCh: make(chan struct{}, 1), + version: version, } proto.RegisterFocusServer(service.server, service) @@ -57,6 +60,13 @@ func (service *Service) Raise(context.Context, *emptypb.Empty) (*emptypb.Empty, 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. func (service *Service) GetRaiseCh() <-chan struct{} { return service.raiseCh diff --git a/internal/frontend/cli/frontend.go b/internal/frontend/cli/frontend.go index 375ae8aa..fc18d1a6 100644 --- a/internal/frontend/cli/frontend.go +++ b/internal/frontend/cli/frontend.go @@ -341,6 +341,9 @@ func (f *frontendCLI) watchEvents(eventCh <-chan events.Event) { case events.TLSIssue: f.notifyCertIssue() + + case events.Raise: + f.Printf("Hello!") } } diff --git a/internal/locations/locations.go b/internal/locations/locations.go index 6382d68a..dcc9a5c4 100644 --- a/internal/locations/locations.go +++ b/internal/locations/locations.go @@ -51,7 +51,12 @@ func New(provider Provider, configName string) *Locations { } } -// GetGuiLockFile returns the path to the lock file (e.g. ~/.cache///.lock). +// GetLockFile returns the path to the bridge lock file (e.g. ~/.cache///.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///.lock). func (l *Locations) GetGuiLockFile() string { return filepath.Join(l.userCache, l.configGuiName+".lock") }