ntp.go 4.0 KB

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