ntp.go 4.2 KB

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