From f08861185ab309d2375d5935d395a05dafc4036a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=96=E7=95=8C?= Date: Sat, 14 Dec 2024 22:41:58 +0800 Subject: [PATCH] Fix time service --- box.go | 16 ++++++++++++---- common/tls/time_wrapper.go | 22 ++++++++++++++++++++++ 2 files changed, 34 insertions(+), 4 deletions(-) create mode 100644 common/tls/time_wrapper.go diff --git a/box.go b/box.go index 5dc76ebc..1908f6db 100644 --- a/box.go +++ b/box.go @@ -14,6 +14,7 @@ import ( "github.com/sagernet/sing-box/adapter/outbound" "github.com/sagernet/sing-box/common/dialer" "github.com/sagernet/sing-box/common/taskmonitor" + "github.com/sagernet/sing-box/common/tls" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/experimental" "github.com/sagernet/sing-box/experimental/cachefile" @@ -149,6 +150,14 @@ func New(options Options) (*Box, error) { if err != nil { return nil, E.Cause(err, "initialize router") } + + ntpOptions := common.PtrValueOrDefault(options.NTP) + var timeService *tls.TimeServiceWrapper + if ntpOptions.Enabled { + timeService = new(tls.TimeServiceWrapper) + service.MustRegister[ntp.TimeService](ctx, timeService) + } + for i, endpointOptions := range options.Endpoints { var tag string if endpointOptions.Tag != "" { @@ -254,13 +263,12 @@ func New(options Options) (*Box, error) { service.MustRegister[adapter.V2RayServer](ctx, v2rayServer) } } - ntpOptions := common.PtrValueOrDefault(options.NTP) if ntpOptions.Enabled { ntpDialer, err := dialer.New(ctx, ntpOptions.DialerOptions) if err != nil { return nil, E.Cause(err, "create NTP service") } - timeService := ntp.NewService(ntp.Options{ + ntpService := ntp.NewService(ntp.Options{ Context: ctx, Dialer: ntpDialer, Logger: logFactory.NewLogger("ntp"), @@ -268,8 +276,8 @@ func New(options Options) (*Box, error) { Interval: time.Duration(ntpOptions.Interval), WriteToSystem: ntpOptions.WriteToSystem, }) - service.MustRegister[ntp.TimeService](ctx, timeService) - services = append(services, adapter.NewLifecycleService(timeService, "ntp service")) + timeService.TimeService = ntpService + services = append(services, adapter.NewLifecycleService(ntpService, "ntp service")) } return &Box{ network: networkManager, diff --git a/common/tls/time_wrapper.go b/common/tls/time_wrapper.go new file mode 100644 index 00000000..491fca98 --- /dev/null +++ b/common/tls/time_wrapper.go @@ -0,0 +1,22 @@ +package tls + +import ( + "time" + + "github.com/sagernet/sing/common/ntp" +) + +type TimeServiceWrapper struct { + ntp.TimeService +} + +func (w *TimeServiceWrapper) TimeFunc() func() time.Time { + if w.TimeService == nil { + return nil + } + return w.TimeService.TimeFunc() +} + +func (w *TimeServiceWrapper) Upstream() any { + return w.TimeService +}