Skip to content

Commit

Permalink
Fix time service
Browse files Browse the repository at this point in the history
  • Loading branch information
nekohasekai committed Dec 14, 2024
1 parent 5f20c61 commit 3a68de2
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
16 changes: 12 additions & 4 deletions box.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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 != "" {
Expand Down Expand Up @@ -254,22 +263,21 @@ 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"),
Server: ntpOptions.ServerOptions.Build(),
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,
Expand Down
22 changes: 22 additions & 0 deletions common/tls/time_wrapper.go
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit 3a68de2

Please sign in to comment.