github.com/murrekatt/go-ethereum@v1.5.8-0.20170123175102-fc52f2c007fb/p2p/discv5/ntp.go (about)

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