github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/p2p/discv5/ntp.go (about)

     1  // This file is part of the go-sberex library. The go-sberex library is 
     2  // free software: you can redistribute it and/or modify it under the terms 
     3  // of the GNU Lesser General Public License as published by the Free 
     4  // Software Foundation, either version 3 of the License, or (at your option)
     5  // any later version.
     6  //
     7  // The go-sberex library is distributed in the hope that it will be useful, 
     8  // but WITHOUT ANY WARRANTY; without even the implied warranty of
     9  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 
    10  // General Public License <http://www.gnu.org/licenses/> for more details.
    11  
    12  // Contains the NTP time drift detection via the SNTP protocol:
    13  //   https://tools.ietf.org/html/rfc4330
    14  
    15  package discv5
    16  
    17  import (
    18  	"fmt"
    19  	"net"
    20  	"sort"
    21  	"strings"
    22  	"time"
    23  
    24  	"github.com/Sberex/go-sberex/log"
    25  )
    26  
    27  const (
    28  	ntpPool   = "pool.ntp.org" // ntpPool is the NTP server to query for the current time
    29  	ntpChecks = 3              // Number of measurements to do against the NTP server
    30  )
    31  
    32  // durationSlice attaches the methods of sort.Interface to []time.Duration,
    33  // sorting in increasing order.
    34  type durationSlice []time.Duration
    35  
    36  func (s durationSlice) Len() int           { return len(s) }
    37  func (s durationSlice) Less(i, j int) bool { return s[i] < s[j] }
    38  func (s durationSlice) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
    39  
    40  // checkClockDrift queries an NTP server for clock drifts and warns the user if
    41  // one large enough is detected.
    42  func checkClockDrift() {
    43  	drift, err := sntpDrift(ntpChecks)
    44  	if err != nil {
    45  		return
    46  	}
    47  	if drift < -driftThreshold || drift > driftThreshold {
    48  		warning := fmt.Sprintf("System clock seems off by %v, which can prevent network connectivity", drift)
    49  		howtofix := fmt.Sprintf("Please enable network time synchronisation in system settings")
    50  		separator := strings.Repeat("-", len(warning))
    51  
    52  		log.Warn(separator)
    53  		log.Warn(warning)
    54  		log.Warn(howtofix)
    55  		log.Warn(separator)
    56  	} else {
    57  		log.Debug(fmt.Sprintf("Sanity NTP check reported %v drift, all ok", drift))
    58  	}
    59  }
    60  
    61  // sntpDrift does a naive time resolution against an NTP server and returns the
    62  // measured drift. This method uses the simple version of NTP. It's not precise
    63  // but should be fine for these purposes.
    64  //
    65  // Note, it executes two extra measurements compared to the number of requested
    66  // ones to be able to discard the two extremes as outliers.
    67  func sntpDrift(measurements int) (time.Duration, error) {
    68  	// Resolve the address of the NTP server
    69  	addr, err := net.ResolveUDPAddr("udp", ntpPool+":123")
    70  	if err != nil {
    71  		return 0, err
    72  	}
    73  	// Construct the time request (empty package with only 2 fields set):
    74  	//   Bits 3-5: Protocol version, 3
    75  	//   Bits 6-8: Mode of operation, client, 3
    76  	request := make([]byte, 48)
    77  	request[0] = 3<<3 | 3
    78  
    79  	// Execute each of the measurements
    80  	drifts := []time.Duration{}
    81  	for i := 0; i < measurements+2; i++ {
    82  		// Dial the NTP server and send the time retrieval request
    83  		conn, err := net.DialUDP("udp", nil, addr)
    84  		if err != nil {
    85  			return 0, err
    86  		}
    87  		defer conn.Close()
    88  
    89  		sent := time.Now()
    90  		if _, err = conn.Write(request); err != nil {
    91  			return 0, err
    92  		}
    93  		// Retrieve the reply and calculate the elapsed time
    94  		conn.SetDeadline(time.Now().Add(5 * time.Second))
    95  
    96  		reply := make([]byte, 48)
    97  		if _, err = conn.Read(reply); err != nil {
    98  			return 0, err
    99  		}
   100  		elapsed := time.Since(sent)
   101  
   102  		// Reconstruct the time from the reply data
   103  		sec := uint64(reply[43]) | uint64(reply[42])<<8 | uint64(reply[41])<<16 | uint64(reply[40])<<24
   104  		frac := uint64(reply[47]) | uint64(reply[46])<<8 | uint64(reply[45])<<16 | uint64(reply[44])<<24
   105  
   106  		nanosec := sec*1e9 + (frac*1e9)>>32
   107  
   108  		t := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Duration(nanosec)).Local()
   109  
   110  		// Calculate the drift based on an assumed answer time of RRT/2
   111  		drifts = append(drifts, sent.Sub(t)+elapsed/2)
   112  	}
   113  	// Calculate average drif (drop two extremities to avoid outliers)
   114  	sort.Sort(durationSlice(drifts))
   115  
   116  	drift := time.Duration(0)
   117  	for i := 1; i < len(drifts)-1; i++ {
   118  		drift += drifts[i]
   119  	}
   120  	return drift / time.Duration(measurements), nil
   121  }