ntpquery.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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 DeprecatedString 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 wpath rpath"));
  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. DeprecatedString host = "time.google.com"sv;
  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. TRY(Core::System::unveil("/tmp/portal/lookup", "rw"));
  104. TRY(Core::System::unveil("/etc/timezone", "r"));
  105. TRY(Core::System::unveil(nullptr, nullptr));
  106. if (adjust_time && set_time) {
  107. warnln("-a and -s are mutually exclusive");
  108. return 1;
  109. }
  110. if (!adjust_time && !set_time) {
  111. TRY(Core::System::pledge("stdio inet unix rpath"));
  112. }
  113. auto* hostent = gethostbyname(host.characters());
  114. if (!hostent) {
  115. warnln("Lookup failed for '{}'", host);
  116. return 1;
  117. }
  118. TRY(Core::System::pledge((adjust_time || set_time) ? "stdio inet settime wpath rpath"sv : "stdio inet rpath"sv));
  119. int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  120. if (fd < 0) {
  121. perror("socket");
  122. return 1;
  123. }
  124. struct timeval timeout {
  125. 5, 0
  126. };
  127. if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) {
  128. perror("setsockopt");
  129. return 1;
  130. }
  131. int enable = 1;
  132. if (setsockopt(fd, SOL_SOCKET, SO_TIMESTAMP, &enable, sizeof(enable)) < 0) {
  133. perror("setsockopt");
  134. return 1;
  135. }
  136. sockaddr_in peer_address;
  137. memset(&peer_address, 0, sizeof(peer_address));
  138. peer_address.sin_family = AF_INET;
  139. peer_address.sin_port = htons(123);
  140. peer_address.sin_addr.s_addr = *(in_addr_t const*)hostent->h_addr_list[0];
  141. NtpPacket packet;
  142. memset(&packet, 0, sizeof(packet));
  143. packet.li_vn_mode = (4 << 3) | 3; // Version 4, client connection.
  144. // The server will copy the transmit_timestamp to origin_timestamp in the reply.
  145. // To not leak the local time, keep the time we sent the packet locally and
  146. // send random bytes to the server.
  147. auto random_transmit_timestamp = get_random<NtpTimestamp>();
  148. timeval local_transmit_time;
  149. gettimeofday(&local_transmit_time, nullptr);
  150. packet.transmit_timestamp = random_transmit_timestamp;
  151. ssize_t rc;
  152. rc = sendto(fd, &packet, sizeof(packet), 0, (const struct sockaddr*)&peer_address, sizeof(peer_address));
  153. if (rc < 0) {
  154. perror("sendto");
  155. return 1;
  156. }
  157. if ((size_t)rc < sizeof(packet)) {
  158. warnln("incomplete packet send");
  159. return 1;
  160. }
  161. iovec iov { &packet, sizeof(packet) };
  162. char control_message_buffer[CMSG_SPACE(sizeof(timeval))];
  163. msghdr msg = {};
  164. msg.msg_name = &peer_address;
  165. msg.msg_namelen = sizeof(peer_address);
  166. msg.msg_iov = &iov;
  167. msg.msg_iovlen = 1;
  168. msg.msg_control = control_message_buffer;
  169. msg.msg_controllen = sizeof(control_message_buffer);
  170. msg.msg_flags = 0;
  171. rc = recvmsg(fd, &msg, 0);
  172. if (rc < 0) {
  173. perror("recvmsg");
  174. return 1;
  175. }
  176. timeval userspace_receive_time;
  177. gettimeofday(&userspace_receive_time, nullptr);
  178. if ((size_t)rc < sizeof(packet)) {
  179. warnln("incomplete packet recv");
  180. return 1;
  181. }
  182. cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
  183. VERIFY(cmsg->cmsg_level == SOL_SOCKET);
  184. VERIFY(cmsg->cmsg_type == SCM_TIMESTAMP);
  185. VERIFY(!CMSG_NXTHDR(&msg, cmsg));
  186. timeval kernel_receive_time;
  187. memcpy(&kernel_receive_time, CMSG_DATA(cmsg), sizeof(kernel_receive_time));
  188. // Checks 3 and 4 from end of section 5 of rfc4330.
  189. if (packet.version_number() != 3 && packet.version_number() != 4) {
  190. warnln("unexpected version number {}", packet.version_number());
  191. return 1;
  192. }
  193. if (packet.mode() != 4) { // 4 means "server", which should be the reply to our 3 ("client") request.
  194. warnln("unexpected mode {}", packet.mode());
  195. return 1;
  196. }
  197. if (packet.stratum == 0 || packet.stratum >= 16) {
  198. warnln("unexpected stratum value {}", packet.stratum);
  199. return 1;
  200. }
  201. if (packet.origin_timestamp != random_transmit_timestamp) {
  202. warnln("expected {:#016x} as origin timestamp, got {:#016x}", random_transmit_timestamp, packet.origin_timestamp);
  203. return 1;
  204. }
  205. if (packet.transmit_timestamp == 0) {
  206. warnln("got transmit_timestamp 0");
  207. return 1;
  208. }
  209. NtpTimestamp origin_timestamp = ntp_timestamp_from_timeval(local_transmit_time);
  210. NtpTimestamp receive_timestamp = be64toh(packet.receive_timestamp);
  211. NtpTimestamp transmit_timestamp = be64toh(packet.transmit_timestamp);
  212. NtpTimestamp destination_timestamp = ntp_timestamp_from_timeval(kernel_receive_time);
  213. timeval kernel_to_userspace_latency;
  214. timersub(&userspace_receive_time, &kernel_receive_time, &kernel_to_userspace_latency);
  215. if (set_time) {
  216. // FIXME: Do all the time filtering described in 5905, or at least correct for time of flight.
  217. timeval t = timeval_from_ntp_timestamp(transmit_timestamp);
  218. if (settimeofday(&t, nullptr) < 0) {
  219. perror("settimeofday");
  220. return 1;
  221. }
  222. }
  223. if (verbose) {
  224. outln("NTP response from {}:", inet_ntoa(peer_address.sin_addr));
  225. outln("Leap Information: {}", packet.leap_information());
  226. outln("Version Number: {}", packet.version_number());
  227. outln("Mode: {}", packet.mode());
  228. outln("Stratum: {}", packet.stratum);
  229. outln("Poll: {}", packet.stratum);
  230. outln("Precision: {}", packet.precision);
  231. outln("Root delay: {:x}", ntohl(packet.root_delay));
  232. outln("Root dispersion: {:x}", ntohl(packet.root_dispersion));
  233. u32 ref_id = ntohl(packet.reference_id);
  234. out("Reference ID: {:x}", ref_id);
  235. if (packet.stratum == 1) {
  236. out(" ('{:c}{:c}{:c}{:c}')", (ref_id & 0xff000000) >> 24, (ref_id & 0xff0000) >> 16, (ref_id & 0xff00) >> 8, ref_id & 0xff);
  237. }
  238. outln();
  239. outln("Reference timestamp: {:#016x} ({})", be64toh(packet.reference_timestamp), format_ntp_timestamp(be64toh(packet.reference_timestamp)).characters());
  240. outln("Origin timestamp: {:#016x} ({})", origin_timestamp, format_ntp_timestamp(origin_timestamp).characters());
  241. outln("Receive timestamp: {:#016x} ({})", receive_timestamp, format_ntp_timestamp(receive_timestamp).characters());
  242. outln("Transmit timestamp: {:#016x} ({})", transmit_timestamp, format_ntp_timestamp(transmit_timestamp).characters());
  243. outln("Destination timestamp: {:#016x} ({})", destination_timestamp, format_ntp_timestamp(destination_timestamp).characters());
  244. // 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,
  245. // 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.
  246. outln("Receive latency: {}.{:06} s", (i64)kernel_to_userspace_latency.tv_sec, (int)kernel_to_userspace_latency.tv_usec);
  247. }
  248. // Parts of the "Clock Filter" computations, https://tools.ietf.org/html/rfc5905#section-10
  249. NtpTimestamp T1 = origin_timestamp;
  250. NtpTimestamp T2 = receive_timestamp;
  251. NtpTimestamp T3 = transmit_timestamp;
  252. NtpTimestamp T4 = destination_timestamp;
  253. auto timestamp_difference_in_seconds = [](NtpTimestamp from, NtpTimestamp to) {
  254. return static_cast<i64>(to - from) >> 32;
  255. };
  256. // The network round-trip time of the request.
  257. // T4-T1 is the wall clock roundtrip time, in local ticks.
  258. // T3-T2 is the server side processing time, in server ticks.
  259. double delay_s = timestamp_difference_in_seconds(T1, T4) - timestamp_difference_in_seconds(T2, T3);
  260. // The offset from local time to server time, ignoring network delay.
  261. // Both T2-T1 and T3-T4 estimate this; this takes the average of both.
  262. // Or, equivalently, (T1+T4)/2 estimates local time, (T2+T3)/2 estimate server time, this is the difference.
  263. double offset_s = 0.5 * (timestamp_difference_in_seconds(T1, T2) + timestamp_difference_in_seconds(T4, T3));
  264. if (verbose)
  265. outln("Delay: {}", delay_s);
  266. outln("Offset: {}", offset_s);
  267. if (adjust_time) {
  268. long delta_us = lround(offset_s * 1'000'000);
  269. timeval delta_timeval;
  270. delta_timeval.tv_sec = delta_us / 1'000'000;
  271. delta_timeval.tv_usec = delta_us % 1'000'000;
  272. if (delta_timeval.tv_usec < 0) {
  273. delta_timeval.tv_sec--;
  274. delta_timeval.tv_usec += 1'000'000;
  275. }
  276. if (adjtime(&delta_timeval, nullptr) < 0) {
  277. perror("adjtime set");
  278. return 1;
  279. }
  280. }
  281. return 0;
  282. }