github.com/sixexorg/magnetic-ring@v0.0.0-20191119090307-31705a21e419/p2pserver/discover/ntp.go (about)

     1  package discover
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/sixexorg/magnetic-ring/log"
     6  	"net"
     7  	"sort"
     8  	"time"
     9  )
    10  
    11  const (
    12  	ntpPool   = "pool.ntp.org" // ntpPool is the NTP server to query for the current time
    13  	ntpChecks = 3              // Number of measurements to do against the NTP server
    14  )
    15  
    16  // durationSlice attaches the methods of sort.Interface to []time.Duration,
    17  // sorting in increasing order.
    18  type durationSlice []time.Duration
    19  
    20  func (s durationSlice) Len() int           { return len(s) }
    21  func (s durationSlice) Less(i, j int) bool { return s[i] < s[j] }
    22  func (s durationSlice) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
    23  
    24  // checkClockDrift queries an NTP server for clock drifts and warns the user if
    25  // one large enough is detected.
    26  func checkClockDrift() {
    27  	drift, err := sntpDrift(ntpChecks)
    28  	if err != nil {
    29  		return
    30  	}
    31  	if drift < -driftThreshold || drift > driftThreshold {
    32  		log.Warn(fmt.Sprintf("System clock seems off by %v, which can prevent network connectivity", drift))
    33  		log.Warn("Please enable network time synchronisation in system settings.")
    34  	} else {
    35  		log.Debug("NTP sanity check done", "drift", drift)
    36  	}
    37  }
    38  
    39  // sntpDrift does a naive time resolution against an NTP server and returns the
    40  // measured drift. This method uses the simple version of NTP. It's not precise
    41  // but should be fine for these purposes.
    42  //
    43  // Note, it executes two extra measurements compared to the number of requested
    44  // ones to be able to discard the two extremes as outliers.
    45  func sntpDrift(measurements int) (time.Duration, error) {
    46  	// Resolve the address of the NTP server
    47  	addr, err := net.ResolveUDPAddr("udp", ntpPool+":123")
    48  	if err != nil {
    49  		return 0, err
    50  	}
    51  	// Construct the time request (empty package with only 2 fields set):
    52  	//   Bits 3-5: Protocol version, 3
    53  	//   Bits 6-8: Mode of operation, client, 3
    54  	request := make([]byte, 48)
    55  	request[0] = 3<<3 | 3
    56  
    57  	// Execute each of the measurements
    58  	drifts := []time.Duration{}
    59  	for i := 0; i < measurements+2; i++ {
    60  		// Dial the NTP server and send the time retrieval request
    61  		conn, err := net.DialUDP("udp", nil, addr)
    62  		if err != nil {
    63  			return 0, err
    64  		}
    65  		defer conn.Close()
    66  
    67  		sent := time.Now()
    68  		if _, err = conn.Write(request); err != nil {
    69  			return 0, err
    70  		}
    71  		// Retrieve the reply and calculate the elapsed time
    72  		conn.SetDeadline(time.Now().Add(5 * time.Second))
    73  
    74  		reply := make([]byte, 48)
    75  		if _, err = conn.Read(reply); err != nil {
    76  			return 0, err
    77  		}
    78  		elapsed := time.Since(sent)
    79  
    80  		// Reconstruct the time from the reply data
    81  		sec := uint64(reply[43]) | uint64(reply[42])<<8 | uint64(reply[41])<<16 | uint64(reply[40])<<24
    82  		frac := uint64(reply[47]) | uint64(reply[46])<<8 | uint64(reply[45])<<16 | uint64(reply[44])<<24
    83  
    84  		nanosec := sec*1e9 + (frac*1e9)>>32
    85  
    86  		t := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Duration(nanosec)).Local()
    87  
    88  		// Calculate the drift based on an assumed answer time of RRT/2
    89  		drifts = append(drifts, sent.Sub(t)+elapsed/2)
    90  	}
    91  	// Calculate average drif (drop two extremities to avoid outliers)
    92  	sort.Sort(durationSlice(drifts))
    93  
    94  	drift := time.Duration(0)
    95  	for i := 1; i < len(drifts)-1; i++ {
    96  		drift += drifts[i]
    97  	}
    98  	return drift / time.Duration(measurements), nil
    99  }