github.com/sagernet/sing-box@v1.9.0-rc.20/cmd/sing-box/cmd_tools_synctime.go (about) 1 package main 2 3 import ( 4 "context" 5 "os" 6 7 "github.com/sagernet/sing-box/common/settings" 8 C "github.com/sagernet/sing-box/constant" 9 "github.com/sagernet/sing-box/log" 10 E "github.com/sagernet/sing/common/exceptions" 11 M "github.com/sagernet/sing/common/metadata" 12 N "github.com/sagernet/sing/common/network" 13 "github.com/sagernet/sing/common/ntp" 14 15 "github.com/spf13/cobra" 16 ) 17 18 var ( 19 commandSyncTimeFlagServer string 20 commandSyncTimeOutputFormat string 21 commandSyncTimeWrite bool 22 ) 23 24 var commandSyncTime = &cobra.Command{ 25 Use: "synctime", 26 Short: "Sync time using the NTP protocol", 27 Args: cobra.NoArgs, 28 Run: func(cmd *cobra.Command, args []string) { 29 err := syncTime() 30 if err != nil { 31 log.Fatal(err) 32 } 33 }, 34 } 35 36 func init() { 37 commandSyncTime.Flags().StringVarP(&commandSyncTimeFlagServer, "server", "s", "time.apple.com", "Set NTP server") 38 commandSyncTime.Flags().StringVarP(&commandSyncTimeOutputFormat, "format", "f", C.TimeLayout, "Set output format") 39 commandSyncTime.Flags().BoolVarP(&commandSyncTimeWrite, "write", "w", false, "Write time to system") 40 commandTools.AddCommand(commandSyncTime) 41 } 42 43 func syncTime() error { 44 instance, err := createPreStartedClient() 45 if err != nil { 46 return err 47 } 48 dialer, err := createDialer(instance, N.NetworkUDP, commandToolsFlagOutbound) 49 if err != nil { 50 return err 51 } 52 defer instance.Close() 53 serverAddress := M.ParseSocksaddr(commandSyncTimeFlagServer) 54 if serverAddress.Port == 0 { 55 serverAddress.Port = 123 56 } 57 response, err := ntp.Exchange(context.Background(), dialer, serverAddress) 58 if err != nil { 59 return err 60 } 61 if commandSyncTimeWrite { 62 err = settings.SetSystemTime(response.Time) 63 if err != nil { 64 return E.Cause(err, "write time to system") 65 } 66 } 67 os.Stdout.WriteString(response.Time.Local().Format(commandSyncTimeOutputFormat)) 68 return nil 69 }