ntpquery.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. /*
  2. * Copyright (c) 2020, Nico Weber <thakis@chromium.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #define _BSD_SOURCE
  7. #define _DEFAULT_SOURCE
  8. #include <AK/Assertions.h>
  9. #include <AK/Endian.h>
  10. #include <AK/Random.h>
  11. #include <LibCore/ArgsParser.h>
  12. #include <LibCore/System.h>
  13. #include <LibMain/Main.h>
  14. #include <arpa/inet.h>
  15. #include <inttypes.h>
  16. #include <math.h>
  17. #include <netdb.h>
  18. #include <netinet/in.h>
  19. #include <stdio.h>
  20. #include <string.h>
  21. #include <sys/socket.h>
  22. #include <sys/time.h>
  23. #include <sys/uio.h>
  24. #include <time.h>
  25. // An NtpTimestamp is a 64-bit integer that's a 32.32 binary-fixed point number.
  26. // The integral part in the upper 32 bits represents seconds since 1900-01-01.
  27. // The fractional part in the lower 32 bits stores fractional bits times 2 ** 32.
  28. using NtpTimestamp = uint64_t;
  29. struct [[gnu::packed]] NtpPacket {
  30. uint8_t li_vn_mode;
  31. uint8_t stratum;
  32. int8_t poll;
  33. int8_t precision;
  34. uint32_t root_delay;
  35. uint32_t root_dispersion;
  36. uint32_t reference_id;
  37. NtpTimestamp reference_timestamp;
  38. NtpTimestamp origin_timestamp;
  39. NtpTimestamp receive_timestamp;
  40. NtpTimestamp transmit_timestamp;
  41. uint8_t leap_information() const { return li_vn_mode >> 6; }
  42. uint8_t version_number() const { return (li_vn_mode >> 3) & 7; }
  43. uint8_t mode() const { return li_vn_mode & 7; }
  44. };
  45. static_assert(AssertSize<NtpPacket, 48>());
  46. // NTP measures time in seconds since 1900-01-01, POSIX in seconds since 1970-01-01.
  47. // 1900 wasn't a leap year, so there are 70/4 leap years between 1900 and 1970.
  48. // Overflows a 32-bit signed int, but not a 32-bit unsigned int.
  49. unsigned const SecondsFrom1900To1970 = (70u * 365u + 70u / 4u) * 24u * 60u * 60u;
  50. static NtpTimestamp ntp_timestamp_from_timeval(timeval const& t)
  51. {
  52. VERIFY(t.tv_usec >= 0 && t.tv_usec < 1'000'000); // Fits in 20 bits when normalized.
  53. // Seconds just need translation to the different origin.
  54. uint32_t seconds = t.tv_sec + SecondsFrom1900To1970;
  55. // Fractional bits are decimal fixed point (*1'000'000) in timeval, but binary fixed-point (* 2**32) in NTP timestamps.
  56. uint32_t fractional_bits = static_cast<uint32_t>((static_cast<uint64_t>(t.tv_usec) << 32) / 1'000'000);
  57. return (static_cast<NtpTimestamp>(seconds) << 32) | fractional_bits;
  58. }
  59. static timeval timeval_from_ntp_timestamp(NtpTimestamp const& ntp_timestamp)
  60. {
  61. timeval t;
  62. t.tv_sec = static_cast<time_t>(ntp_timestamp >> 32) - SecondsFrom1900To1970;
  63. t.tv_usec = static_cast<suseconds_t>((static_cast<uint64_t>(ntp_timestamp & 0xFFFFFFFFu) * 1'000'000) >> 32);
  64. return t;
  65. }
  66. static String format_ntp_timestamp(NtpTimestamp ntp_timestamp)
  67. {
  68. char buffer[28]; // YYYY-MM-DDTHH:MM:SS.UUUUUUZ is 27 characters long.
  69. timeval t = timeval_from_ntp_timestamp(ntp_timestamp);
  70. struct tm tm;
  71. gmtime_r(&t.tv_sec, &tm);
  72. size_t written = strftime(buffer, sizeof(buffer), "%Y-%m-%dT%T.", &tm);
  73. VERIFY(written == 20);
  74. written += snprintf(buffer + written, sizeof(buffer) - written, "%06d", (int)t.tv_usec);
  75. VERIFY(written == 26);
  76. buffer[written++] = 'Z';
  77. buffer[written] = '\0';
  78. return buffer;
  79. }
  80. ErrorOr<int> serenity_main(Main::Arguments arguments)
  81. {
  82. TRY(Core::System::pledge("stdio inet unix settime"));
  83. bool adjust_time = false;
  84. bool set_time = false;
  85. bool verbose = false;
  86. // FIXME: Change to serenityos.pool.ntp.org once https://manage.ntppool.org/manage/vendor/zone?a=km5a8h&id=vz-14154g is approved.
  87. // Other NTP servers:
  88. // - time.nist.gov
  89. // - time.apple.com
  90. // - time.cloudflare.com (has NTS), https://blog.cloudflare.com/secure-time/
  91. // - time.windows.com
  92. //
  93. // Leap seconds smearing NTP servers:
  94. // - time.facebook.com , https://engineering.fb.com/production-engineering/ntp-service/ , sine-smears over 18 hours
  95. // - time.google.com , https://developers.google.com/time/smear , linear-smears over 24 hours
  96. char const* host = "time.google.com";
  97. Core::ArgsParser args_parser;
  98. args_parser.add_option(adjust_time, "Gradually adjust system time (requires root)", "adjust", 'a');
  99. args_parser.add_option(set_time, "Immediately set system time (requires root)", "set", 's');
  100. args_parser.add_option(verbose, "Verbose output", "verbose", 'v');
  101. args_parser.add_positional_argument(host, "NTP server", "host", Core::ArgsParser::Required::No);
  102. args_parser.parse(arguments);
  103. if (adjust_time && set_time) {
  104. warnln("-a and -s are mutually exclusive");
  105. return 1;
  106. }
  107. if (!adjust_time && !set_time) {
  108. TRY(Core::System::pledge("stdio inet unix"));
  109. }
  110. auto* hostent = gethostbyname(host);
  111. if (!hostent) {
  112. warnln("Lookup failed for '{}'", host);
  113. return 1;
  114. }
  115. TRY(Core::System::pledge((adjust_time || set_time) ? "stdio inet settime"sv : "stdio inet"sv));
  116. TRY(Core::System::unveil(nullptr, nullptr));
  117. int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  118. if (fd < 0) {
  119. perror("socket");
  120. return 1;
  121. }
  122. struct timeval timeout {
  123. 5, 0
  124. };
  125. if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) {
  126. perror("setsockopt");
  127. return 1;
  128. }
  129. int enable = 1;
  130. if (setsockopt(fd, SOL_SOCKET, SO_TIMESTAMP, &enable, sizeof(enable)) < 0) {
  131. perror("setsockopt");
  132. return 1;
  133. }
  134. sockaddr_in peer_address;
  135. memset(&peer_address, 0, sizeof(peer_address));
  136. peer_address.sin_family = AF_INET;
  137. peer_address.sin_port = htons(123);
  138. peer_address.sin_addr.s_addr = *(in_addr_t const*)hostent->h_addr_list[0];
  139. NtpPacket packet;
  140. memset(&packet, 0, sizeof(packet));
  141. packet.li_vn_mode = (4 << 3) | 3; // Version 4, client connection.
  142. // The server will copy the transmit_timestamp to origin_timestamp in the reply.
  143. // To not leak the local time, keep the time we sent the packet locally and
  144. // send random bytes to the server.
  145. auto random_transmit_timestamp = get_random<NtpTimestamp>();
  146. timeval local_transmit_time;
  147. gettimeofday(&local_transmit_time, nullptr);
  148. packet.transmit_timestamp = random_transmit_timestamp;
  149. ssize_t rc;
  150. rc = sendto(fd, &packet, sizeof(packet), 0, (const struct sockaddr*)&peer_address, sizeof(peer_address));
  151. if (rc < 0) {
  152. perror("sendto");
  153. return 1;
  154. }
  155. if ((size_t)rc < sizeof(packet)) {
  156. warnln("incomplete packet send");
  157. return 1;
  158. }
  159. iovec iov { &packet, sizeof(packet) };
  160. char control_message_buffer[CMSG_SPACE(sizeof(timeval))];
  161. msghdr msg = { &peer_address, sizeof(peer_address), &iov, 1, control_message_buffer, sizeof(control_message_buffer), 0 };
  162. rc = recvmsg(fd, &msg, 0);
  163. if (rc < 0) {
  164. perror("recvmsg");
  165. return 1;
  166. }
  167. timeval userspace_receive_time;
  168. gettimeofday(&userspace_receive_time, nullptr);
  169. if ((size_t)rc < sizeof(packet)) {
  170. warnln("incomplete packet recv");
  171. return 1;
  172. }
  173. cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
  174. VERIFY(cmsg->cmsg_level == SOL_SOCKET);
  175. VERIFY(cmsg->cmsg_type == SCM_TIMESTAMP);
  176. VERIFY(!CMSG_NXTHDR(&msg, cmsg));
  177. timeval kernel_receive_time;
  178. memcpy(&kernel_receive_time, CMSG_DATA(cmsg), sizeof(kernel_receive_time));
  179. // Checks 3 and 4 from end of section 5 of rfc4330.
  180. if (packet.version_number() != 3 && packet.version_number() != 4) {
  181. warnln("unexpected version number {}", packet.version_number());
  182. return 1;
  183. }
  184. if (packet.mode() != 4) { // 4 means "server", which should be the reply to our 3 ("client") request.
  185. warnln("unexpected mode {}", packet.mode());
  186. return 1;
  187. }
  188. if (packet.stratum == 0 || packet.stratum >= 16) {
  189. warnln("unexpected stratum value {}", packet.stratum);
  190. return 1;
  191. }
  192. if (packet.origin_timestamp != random_transmit_timestamp) {
  193. warnln("expected {:#016x} as origin timestamp, got {:#016x}", random_transmit_timestamp, packet.origin_timestamp);
  194. return 1;
  195. }
  196. if (packet.transmit_timestamp == 0) {
  197. warnln("got transmit_timestamp 0");
  198. return 1;
  199. }
  200. NtpTimestamp origin_timestamp = ntp_timestamp_from_timeval(local_transmit_time);
  201. NtpTimestamp receive_timestamp = be64toh(packet.receive_timestamp);
  202. NtpTimestamp transmit_timestamp = be64toh(packet.transmit_timestamp);
  203. NtpTimestamp destination_timestamp = ntp_timestamp_from_timeval(kernel_receive_time);
  204. timeval kernel_to_userspace_latency;
  205. timersub(&userspace_receive_time, &kernel_receive_time, &kernel_to_userspace_latency);
  206. if (set_time) {
  207. // FIXME: Do all the time filtering described in 5905, or at least correct for time of flight.
  208. timeval t = timeval_from_ntp_timestamp(transmit_timestamp);
  209. if (settimeofday(&t, nullptr) < 0) {
  210. perror("settimeofday");
  211. return 1;
  212. }
  213. }
  214. if (verbose) {
  215. outln("NTP response from {}:", inet_ntoa(peer_address.sin_addr));
  216. outln("Leap Information: {}", packet.leap_information());
  217. outln("Version Number: {}", packet.version_number());
  218. outln("Mode: {}", packet.mode());
  219. outln("Stratum: {}", packet.stratum);
  220. outln("Poll: {}", packet.stratum);
  221. outln("Precision: {}", packet.precision);
  222. outln("Root delay: {:x}", ntohl(packet.root_delay));
  223. outln("Root dispersion: {:x}", ntohl(packet.root_dispersion));
  224. u32 ref_id = ntohl(packet.reference_id);
  225. out("Reference ID: {:x}", ref_id);
  226. if (packet.stratum == 1) {
  227. out(" ('{:c}{:c}{:c}{:c}')", (ref_id & 0xff000000) >> 24, (ref_id & 0xff0000) >> 16, (ref_id & 0xff00) >> 8, ref_id & 0xff);
  228. }
  229. outln();
  230. outln("Reference timestamp: {:#016x} ({})", be64toh(packet.reference_timestamp), format_ntp_timestamp(be64toh(packet.reference_timestamp)).characters());
  231. outln("Origin timestamp: {:#016x} ({})", origin_timestamp, format_ntp_timestamp(origin_timestamp).characters());
  232. outln("Receive timestamp: {:#016x} ({})", receive_timestamp, format_ntp_timestamp(receive_timestamp).characters());
  233. outln("Transmit timestamp: {:#016x} ({})", transmit_timestamp, format_ntp_timestamp(transmit_timestamp).characters());
  234. outln("Destination timestamp: {:#016x} ({})", destination_timestamp, format_ntp_timestamp(destination_timestamp).characters());
  235. // When the system isn't under load, user-space t and packet_t are identical. If a shell with `yes` is running, it can be as high as 30ms in this program,
  236. // which gets user-space time immediately after the recvmsg() call. In programs that have an event loop reading from multiple sockets, it could be higher.
  237. outln("Receive latency: {}.{:06} s", (i64)kernel_to_userspace_latency.tv_sec, (int)kernel_to_userspace_latency.tv_usec);
  238. }
  239. // Parts of the "Clock Filter" computations, https://tools.ietf.org/html/rfc5905#section-10
  240. NtpTimestamp T1 = origin_timestamp;
  241. NtpTimestamp T2 = receive_timestamp;
  242. NtpTimestamp T3 = transmit_timestamp;
  243. NtpTimestamp T4 = destination_timestamp;
  244. auto timestamp_difference_in_seconds = [](NtpTimestamp from, NtpTimestamp to) {
  245. return static_cast<i64>(to - from) >> 32;
  246. };
  247. // The network round-trip time of the request.
  248. // T4-T1 is the wall clock roundtrip time, in local ticks.
  249. // T3-T2 is the server side processing time, in server ticks.
  250. double delay_s = timestamp_difference_in_seconds(T1, T4) - timestamp_difference_in_seconds(T2, T3);
  251. // The offset from local time to server time, ignoring network delay.
  252. // Both T2-T1 and T3-T4 estimate this; this takes the average of both.
  253. // Or, equivalently, (T1+T4)/2 estimates local time, (T2+T3)/2 estimate server time, this is the difference.
  254. double offset_s = 0.5 * (timestamp_difference_in_seconds(T1, T2) + timestamp_difference_in_seconds(T4, T3));
  255. if (verbose)
  256. outln("Delay: {}", delay_s);
  257. outln("Offset: {}", offset_s);
  258. if (adjust_time) {
  259. long delta_us = static_cast<long>(round(offset_s * 1'000'000));
  260. timeval delta_timeval;
  261. delta_timeval.tv_sec = delta_us / 1'000'000;
  262. delta_timeval.tv_usec = delta_us % 1'000'000;
  263. if (delta_timeval.tv_usec < 0) {
  264. delta_timeval.tv_sec--;
  265. delta_timeval.tv_usec += 1'000'000;
  266. }
  267. if (adjtime(&delta_timeval, nullptr) < 0) {
  268. perror("adjtime set");
  269. return 1;
  270. }
  271. }
  272. return 0;
  273. }